mastra 1.18.2-alpha.2 → 1.18.2
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/CHANGELOG.md +14 -0
- package/dist/{chunk-VEVDPDTU.js → chunk-WS6NKPDX.js} +3 -3
- package/dist/chunk-WS6NKPDX.js.map +1 -0
- package/dist/commands/create/create.js +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +2 -2
- package/dist/index.js +2 -2
- package/dist/studio/assets/{core-D6Mi7xny.js → core-DBaVdGg0.js} +1 -1
- package/dist/studio/assets/{index-DGXx1Ld6.js → index-0P3X8sNr.js} +2 -2
- package/dist/studio/assets/{main-BIgm0mcp.js → main-DkLhJJmS.js} +3 -3
- package/dist/studio/index.html +1 -1
- package/package.json +7 -7
- package/dist/chunk-VEVDPDTU.js.map +0 -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-DBaVdGg0.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as lo}from"./preload-helper-PPVm8Dsz.js";function X7t(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 Fj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function jc(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var hY={exports:{}},gA={};var RRe;function K7t(){if(RRe)return gA;RRe=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 gA.Fragment=t,gA.jsx=n,gA.jsxs=n,gA}var PRe;function J7t(){return PRe||(PRe=1,hY.exports=K7t()),hY.exports}var o=J7t(),mY={exports:{}},qr={},$Re;function eBt(){if($Re)return qr;$Re=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"),p=Symbol.for("react.activity"),h=Symbol.iterator;function m(q){return q===null||typeof q!="object"?null:(q=h&&q[h]||q["@@iterator"],typeof q=="function"?q:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function S(q,$,U){this.props=q,this.context=$,this.refs=b,this.updater=U||v}S.prototype.isReactComponent={},S.prototype.setState=function(q,$){if(typeof q!="object"&&typeof q!="function"&&q!=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,q,$,"setState")},S.prototype.forceUpdate=function(q){this.updater.enqueueForceUpdate(this,q,"forceUpdate")};function w(){}w.prototype=S.prototype;function k(q,$,U){this.props=q,this.context=$,this.refs=b,this.updater=U||v}var _=k.prototype=new w;_.constructor=k,y(_,S.prototype),_.isPureReactComponent=!0;var C=Array.isArray;function j(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(q,$,U){var Z=U.ref;return{$$typeof:t,type:q,key:$,ref:Z!==void 0?Z:null,props:U}}function A(q,$){return I(q.type,$,q.props)}function P(q){return typeof q=="object"&&q!==null&&q.$$typeof===t}function F(q){var $={"=":"=0",":":"=2"};return"$"+q.replace(/[=:]/g,function(U){return $[U]})}var D=/\/+/g;function V(q,$){return typeof q=="object"&&q!==null&&q.key!=null?F(""+q.key):$.toString(36)}function H(q){switch(q.status){case"fulfilled":return q.value;case"rejected":throw q.reason;default:switch(typeof q.status=="string"?q.then(j,j):(q.status="pending",q.then(function($){q.status==="pending"&&(q.status="fulfilled",q.value=$)},function($){q.status==="pending"&&(q.status="rejected",q.reason=$)})),q.status){case"fulfilled":return q.value;case"rejected":throw q.reason}}throw q}function L(q,$,U,Z,X){var te=typeof q;(te==="undefined"||te==="boolean")&&(q=null);var J=!1;if(q===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(q.$$typeof){case t:case n:J=!0;break;case f:return J=q._init,L(J(q._payload),$,U,Z,X)}}if(J)return X=X(q),J=Z===""?"."+V(q,0):Z,C(X)?(U="",J!=null&&(U=J.replace(D,"$&/")+"/"),L(X,$,U,"",function(ce){return ce})):X!=null&&(P(X)&&(X=A(X,U+(X.key==null||q&&q.key===X.key?"":(""+X.key).replace(D,"$&/")+"/")+J)),$.push(X)),1;J=0;var ee=Z===""?".":Z+":";if(C(q))for(var ae=0;ae<q.length;ae++)Z=q[ae],te=ee+V(Z,ae),J+=L(Z,$,U,te,X);else if(ae=m(q),typeof ae=="function")for(q=ae.call(q),ae=0;!(Z=q.next()).done;)Z=Z.value,te=ee+V(Z,ae++),J+=L(Z,$,U,te,X);else if(te==="object"){if(typeof q.then=="function")return L(H(q),$,U,Z,X);throw $=String(q),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(q).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return J}function z(q,$,U){if(q==null)return q;var Z=[],X=0;return L(q,Z,"","",function(te){return $.call(U,te,X++)}),Z}function B(q){if(q._status===-1){var $=q._result;$=$(),$.then(function(U){(q._status===0||q._status===-1)&&(q._status=1,q._result=U)},function(U){(q._status===0||q._status===-1)&&(q._status=2,q._result=U)}),q._status===-1&&(q._status=0,q._result=$)}if(q._status===1)return q._result.default;throw q._result}var M=typeof reportError=="function"?reportError:function(q){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof q=="object"&&q!==null&&typeof q.message=="string"?String(q.message):String(q),error:q});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",q);return}console.error(q)},G={map:z,forEach:function(q,$,U){z(q,function(){$.apply(this,arguments)},U)},count:function(q){var $=0;return z(q,function(){$++}),$},toArray:function(q){return z(q,function($){return $})||[]},only:function(q){if(!P(q))throw Error("React.Children.only expected to receive a single React element child.");return q}};return qr.Activity=p,qr.Children=G,qr.Component=S,qr.Fragment=r,qr.Profiler=a,qr.PureComponent=k,qr.StrictMode=s,qr.Suspense=u,qr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,qr.__COMPILER_RUNTIME={__proto__:null,c:function(q){return E.H.useMemoCache(q)}},qr.cache=function(q){return function(){return q.apply(null,arguments)}},qr.cacheSignal=function(){return null},qr.cloneElement=function(q,$,U){if(q==null)throw Error("The argument must be a React element, but you passed "+q+".");var Z=y({},q.props),X=q.key;if($!=null)for(te in $.key!==void 0&&(X=""+$.key),$)!N.call($,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&$.ref===void 0||(Z[te]=$[te]);var te=arguments.length-2;if(te===1)Z.children=U;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];Z.children=J}return I(q.type,X,Z)},qr.createContext=function(q){return q={$$typeof:l,_currentValue:q,_currentValue2:q,_threadCount:0,Provider:null,Consumer:null},q.Provider=q,q.Consumer={$$typeof:i,_context:q},q},qr.createElement=function(q,$,U){var Z,X={},te=null;if($!=null)for(Z in $.key!==void 0&&(te=""+$.key),$)N.call($,Z)&&Z!=="key"&&Z!=="__self"&&Z!=="__source"&&(X[Z]=$[Z]);var J=arguments.length-2;if(J===1)X.children=U;else if(1<J){for(var ee=Array(J),ae=0;ae<J;ae++)ee[ae]=arguments[ae+2];X.children=ee}if(q&&q.defaultProps)for(Z in J=q.defaultProps,J)X[Z]===void 0&&(X[Z]=J[Z]);return I(q,te,X)},qr.createRef=function(){return{current:null}},qr.forwardRef=function(q){return{$$typeof:c,render:q}},qr.isValidElement=P,qr.lazy=function(q){return{$$typeof:f,_payload:{_status:-1,_result:q},_init:B}},qr.memo=function(q,$){return{$$typeof:d,type:q,compare:$===void 0?null:$}},qr.startTransition=function(q){var $=E.T,U={};E.T=U;try{var Z=q(),X=E.S;X!==null&&X(U,Z),typeof Z=="object"&&Z!==null&&typeof Z.then=="function"&&Z.then(j,M)}catch(te){M(te)}finally{$!==null&&U.types!==null&&($.types=U.types),E.T=$}},qr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},qr.use=function(q){return E.H.use(q)},qr.useActionState=function(q,$,U){return E.H.useActionState(q,$,U)},qr.useCallback=function(q,$){return E.H.useCallback(q,$)},qr.useContext=function(q){return E.H.useContext(q)},qr.useDebugValue=function(){},qr.useDeferredValue=function(q,$){return E.H.useDeferredValue(q,$)},qr.useEffect=function(q,$){return E.H.useEffect(q,$)},qr.useEffectEvent=function(q){return E.H.useEffectEvent(q)},qr.useId=function(){return E.H.useId()},qr.useImperativeHandle=function(q,$,U){return E.H.useImperativeHandle(q,$,U)},qr.useInsertionEffect=function(q,$){return E.H.useInsertionEffect(q,$)},qr.useLayoutEffect=function(q,$){return E.H.useLayoutEffect(q,$)},qr.useMemo=function(q,$){return E.H.useMemo(q,$)},qr.useOptimistic=function(q,$){return E.H.useOptimistic(q,$)},qr.useReducer=function(q,$,U){return E.H.useReducer(q,$,U)},qr.useRef=function(q){return E.H.useRef(q)},qr.useState=function(q){return E.H.useState(q)},qr.useSyncExternalStore=function(q,$,U){return E.H.useSyncExternalStore(q,$,U)},qr.useTransition=function(){return E.H.useTransition()},qr.version="19.2.6",qr}var MRe;function fN(){return MRe||(MRe=1,mY.exports=eBt()),mY.exports}var g=fN();const Le=jc(g),pN=X7t({__proto__:null,default:Le},[g]);var gY={exports:{}},vA={},vY={exports:{}},yY={};var DRe;function tBt(){return DRe||(DRe=1,(function(e){function t(H,L){var z=H.length;H.push(L);e:for(;0<z;){var B=z-1>>>1,M=H[B];if(0<s(M,L))H[B]=L,H[z]=M,z=B;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var L=H[0],z=H.pop();if(z!==L){H[0]=z;e:for(var B=0,M=H.length,G=M>>>1;B<G;){var q=2*(B+1)-1,$=H[q],U=q+1,Z=H[U];if(0>s($,z))U<M&&0>s(Z,$)?(H[B]=Z,H[U]=z,B=U):(H[B]=$,H[q]=z,B=q);else if(U<M&&0>s(Z,z))H[B]=Z,H[U]=z,B=U;else break e}}return L}function s(H,L){var z=H.sortIndex-L.sortIndex;return z!==0?z:H.id-L.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,p=3,h=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var L=n(u);L!==null;){if(L.callback===null)r(u);else if(L.startTime<=H)r(u),L.sortIndex=L.expirationTime,t(c,L);else break;L=n(u)}}function _(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,C||(C=!0,P());else{var L=n(u);L!==null&&V(_,L.startTime-H)}}var C=!1,j=-1,E=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<E)}function A(){if(y=!1,C){var H=e.unstable_now();N=H;var L=!0;try{e:{m=!1,v&&(v=!1,S(j),j=-1),h=!0;var z=p;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var B=f.callback;if(typeof B=="function"){f.callback=null,p=f.priorityLevel;var M=B(f.expirationTime<=H);if(H=e.unstable_now(),typeof M=="function"){f.callback=M,k(H),L=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)L=!0;else{var G=n(u);G!==null&&V(_,G.startTime-H),L=!1}}break e}finally{f=null,p=z,h=!1}L=void 0}}finally{L?P():C=!1}}}var P;if(typeof w=="function")P=function(){w(A)};else if(typeof MessageChannel<"u"){var F=new MessageChannel,D=F.port2;F.port1.onmessage=A,P=function(){D.postMessage(null)}}else P=function(){b(A,0)};function V(H,L){j=b(function(){H(e.unstable_now())},L)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(H){switch(p){case 1:case 2:case 3:var L=3;break;default:L=p}var z=p;p=L;try{return H()}finally{p=z}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,L){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var z=p;p=H;try{return L()}finally{p=z}},e.unstable_scheduleCallback=function(H,L,z){var B=e.unstable_now();switch(typeof z=="object"&&z!==null?(z=z.delay,z=typeof z=="number"&&0<z?B+z:B):z=B,H){case 1:var M=-1;break;case 2:M=250;break;case 5:M=1073741823;break;case 4:M=1e4;break;default:M=5e3}return M=z+M,H={id:d++,callback:L,priorityLevel:H,startTime:z,expirationTime:M,sortIndex:-1},z>B?(H.sortIndex=z,t(u,H),n(c)===null&&H===n(u)&&(v?(S(j),j=-1):v=!0,V(_,z-B))):(H.sortIndex=M,t(c,H),m||h||(m=!0,C||(C=!0,P()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var L=p;return function(){var z=p;p=L;try{return H.apply(this,arguments)}finally{p=z}}}})(yY)),yY}var LRe;function nBt(){return LRe||(LRe=1,vY.exports=tBt()),vY.exports}var bY={exports:{}},mu={};var FRe;function rBt(){if(FRe)return mu;FRe=1;var e=fN();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 mu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,mu.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)},mu.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()}},mu.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))},mu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},mu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),p=typeof u.integrity=="string"?u.integrity:void 0,h=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:p,fetchPriority:h}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:p,fetchPriority:h,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},mu.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)},mu.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})}},mu.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)},mu.requestFormReset=function(c){r.d.r(c)},mu.unstable_batchedUpdates=function(c,u){return c(u)},mu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},mu.useFormStatus=function(){return i.H.useHostTransitionStatus()},mu.version="19.2.6",mu}var zRe;function wrt(){if(zRe)return bY.exports;zRe=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(),bY.exports=rBt(),bY.exports}var BRe;function sBt(){if(BRe)return vA;BRe=1;var e={env:{}};var t=nBt(),n=fN(),r=wrt();function s(x){var O="https://react.dev/errors/"+x;if(1<arguments.length){O+="?args[]="+encodeURIComponent(arguments[1]);for(var T=2;T<arguments.length;T++)O+="&args[]="+encodeURIComponent(arguments[T])}return"Minified React error #"+x+"; visit "+O+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(x){return!(!x||x.nodeType!==1&&x.nodeType!==9&&x.nodeType!==11)}function i(x){var O=x,T=x;if(x.alternate)for(;O.return;)O=O.return;else{x=O;do O=x,(O.flags&4098)!==0&&(T=O.return),x=O.return;while(x)}return O.tag===3?T:null}function l(x){if(x.tag===13){var O=x.memoizedState;if(O===null&&(x=x.alternate,x!==null&&(O=x.memoizedState)),O!==null)return O.dehydrated}return null}function c(x){if(x.tag===31){var O=x.memoizedState;if(O===null&&(x=x.alternate,x!==null&&(O=x.memoizedState)),O!==null)return O.dehydrated}return null}function u(x){if(i(x)!==x)throw Error(s(188))}function d(x){var O=x.alternate;if(!O){if(O=i(x),O===null)throw Error(s(188));return O!==x?null:x}for(var T=x,R=O;;){var W=T.return;if(W===null)break;var Q=W.alternate;if(Q===null){if(R=W.return,R!==null){T=R;continue}break}if(W.child===Q.child){for(Q=W.child;Q;){if(Q===T)return u(W),x;if(Q===R)return u(W),O;Q=Q.sibling}throw Error(s(188))}if(T.return!==R.return)T=W,R=Q;else{for(var ie=!1,we=W.child;we;){if(we===T){ie=!0,T=W,R=Q;break}if(we===R){ie=!0,R=W,T=Q;break}we=we.sibling}if(!ie){for(we=Q.child;we;){if(we===T){ie=!0,T=Q,R=W;break}if(we===R){ie=!0,R=Q,T=W;break}we=we.sibling}if(!ie)throw Error(s(189))}}if(T.alternate!==R)throw Error(s(190))}if(T.tag!==3)throw Error(s(188));return T.stateNode.current===T?x:O}function f(x){var O=x.tag;if(O===5||O===26||O===27||O===6)return x;for(x=x.child;x!==null;){if(O=f(x),O!==null)return O;x=x.sibling}return null}var p=Object.assign,h=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"),S=Symbol.for("react.profiler"),w=Symbol.for("react.consumer"),k=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),C=Symbol.for("react.suspense"),j=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),P=Symbol.iterator;function F(x){return x===null||typeof x!="object"?null:(x=P&&x[P]||x["@@iterator"],typeof x=="function"?x:null)}var D=Symbol.for("react.client.reference");function V(x){if(x==null)return null;if(typeof x=="function")return x.$$typeof===D?null:x.displayName||x.name||null;if(typeof x=="string")return x;switch(x){case y:return"Fragment";case S:return"Profiler";case b:return"StrictMode";case C:return"Suspense";case j:return"SuspenseList";case I:return"Activity"}if(typeof x=="object")switch(x.$$typeof){case v:return"Portal";case k:return x.displayName||"Context";case w:return(x._context.displayName||"Context")+".Consumer";case _:var O=x.render;return x=x.displayName,x||(x=O.displayName||O.name||"",x=x!==""?"ForwardRef("+x+")":"ForwardRef"),x;case E:return O=x.displayName||null,O!==null?O:V(x.type)||"Memo";case N:O=x._payload,x=x._init;try{return V(x(O))}catch{}}return null}var H=Array.isArray,L=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,z=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B={pending:!1,data:null,method:null,action:null},M=[],G=-1;function q(x){return{current:x}}function $(x){0>G||(x.current=M[G],M[G]=null,G--)}function U(x,O){G++,M[G]=x.current,x.current=O}var Z=q(null),X=q(null),te=q(null),J=q(null);function ee(x,O){switch(U(te,O),U(X,x),U(Z,null),O.nodeType){case 9:case 11:x=(x=O.documentElement)&&(x=x.namespaceURI)?nRe(x):0;break;default:if(x=O.tagName,O=O.namespaceURI)O=nRe(O),x=rRe(O,x);else switch(x){case"svg":x=1;break;case"math":x=2;break;default:x=0}}$(Z),U(Z,x)}function ae(){$(Z),$(X),$(te)}function ce(x){x.memoizedState!==null&&U(J,x);var O=Z.current,T=rRe(O,x.type);O!==T&&(U(X,x),U(Z,T))}function Y(x){X.current===x&&($(Z),$(X)),J.current===x&&($(J),fA._currentValue=B)}var ne,ue;function pe(x){if(ne===void 0)try{throw Error()}catch(T){var O=T.stack.trim().match(/\n( *(at )?)/);ne=O&&O[1]||"",ue=-1<T.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<T.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+ne+x+ue}var oe=!1;function ve(x,O){if(!x||oe)return"";oe=!0;var T=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var R={DetermineComponentFrameRoot:function(){try{if(O){var Ct=function(){throw Error()};if(Object.defineProperty(Ct.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Ct,[])}catch(ft){var ct=ft}Reflect.construct(x,[],Ct)}else{try{Ct.call()}catch(ft){ct=ft}x.call(Ct.prototype)}}else{try{throw Error()}catch(ft){ct=ft}(Ct=x())&&typeof Ct.catch=="function"&&Ct.catch(function(){})}}catch(ft){if(ft&&ct&&typeof ft.stack=="string")return[ft.stack,ct.stack]}return[null,null]}};R.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var W=Object.getOwnPropertyDescriptor(R.DetermineComponentFrameRoot,"name");W&&W.configurable&&Object.defineProperty(R.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Q=R.DetermineComponentFrameRoot(),ie=Q[0],we=Q[1];if(ie&&we){var Be=ie.split(`
|
|
@@ -333,7 +333,7 @@ attempted value: ${i}
|
|
|
333
333
|
\${}
|
|
334
334
|
}
|
|
335
335
|
}`,{label:"class",detail:"definition",type:"keyword"}),zd('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),zd('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],hbt=Xwe.concat([zd("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),zd("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),zd("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),e6e=new ygt,mbt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function VA(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const sFn=["FunctionDeclaration"],aFn={FunctionDeclaration:VA("function"),ClassDeclaration:VA("class"),ClassExpression:()=>!0,EnumDeclaration:VA("constant"),TypeAliasDeclaration:VA("type"),NamespaceDeclaration:VA("namespace"),VariableDefinition(e,t){e.matchContext(sFn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function gbt(e,t){let n=e6e.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(za.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=aFn[i.name];if(l&&l(i,a)||mbt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of gbt(e,i.node))r.push(l);return!1}}),e6e.set(t,r),r}const w7=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,Kwe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function vbt(e){let t=hi(e.state).resolveInner(e.pos,-1);if(Kwe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&w7.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)mbt.has(s.name)&&(r=r.concat(gbt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:w7}}function UK(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 ybt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=hi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?UK(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?UK(t,n.parent,""):Kwe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&w7.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?UK(t,n,""):e.explicit?{path:[],name:""}:null}function iFn(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 oFn(e){let t=new Map;return n=>{let r=ybt(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=iFn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:w7}}}const Zh=CO.define({name:"javascript",parser:rFn.configure({props:[j_.add({IfStatement:xj({except:/^\s*({|else\b)/}),TryStatement:xj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:t5n,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:e5n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":xj({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}}),T_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Iwe,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:"$"}}),bbt={test:e=>/^JSX/.test(e.name),facet:xV({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Jwe=Zh.configure({dialect:"ts"},"typescript"),e1e=Zh.configure({dialect:"jsx",props:[jwe.add(e=>e.isTop?[bbt]:void 0)]}),t1e=Zh.configure({dialect:"jsx ts",props:[jwe.add(e=>e.isTop?[bbt]:void 0)]},"typescript");let xbt=e=>({label:e,type:"keyword"});const wbt="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(xbt),lFn=wbt.concat(["declare","implements","private","protected","public"].map(xbt));function S7(e={}){let t=e.jsx?e.typescript?t1e:e1e:e.typescript?Jwe:Zh,n=e.typescript?hbt.concat(lFn):Xwe.concat(wbt);return new jO(t,[Zh.data.of({autocomplete:z5n(Kwe,byt(n))}),Zh.data.of({autocomplete:vbt}),e.jsx?Sbt:[]])}function cFn(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 t6e(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 uFn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Sbt=Nt.inputHandler.of((e,t,n,r,s)=>{if((uFn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!Zh.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=hi(i).resolveInner(d-1,-1),p;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 h=f.parent,m=h.parent;if(m&&h.from==d-2&&((p=t6e(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${p}>`;return{range:bt.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let h=cFn(f);if(h&&h.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(p=t6e(i.doc,h,d)))return{range:c,changes:{from:d,insert:`</${p}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function dFn(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 Zh.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(fFn(u,r.doc,c))}return s}}function n6e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function fFn(e,t,n){let r=n6e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?n6e(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 v6=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:Sbt,completionPath:ybt,esLint:dFn,javascript:S7,javascriptLanguage:Zh,jsxLanguage:e1e,localCompletionSource:vbt,scopeCompletionSource:oFn,snippets:Xwe,tsxLanguage:t1e,typescriptLanguage:Jwe,typescriptSnippets:hbt},Symbol.toStringTag,{value:"Module"})),HA=["_blank","_self","_top","_parent"],qK=["ascii","utf-8","utf-16","latin1","latin1"],VK=["get","post","put","delete"],HK=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],Gf=["true","false"],Jn={},pFn={a:{attrs:{href:null,ping:null,type:null,media:null,target:HA,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:HA}},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:HK,formmethod:VK,formnovalidate:["novalidate"],formtarget:HA,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":qK,autocomplete:["on","off"],enctype:HK,method:VK,novalidate:["novalidate"],target:HA}},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:HK,formmethod:VK,formnovalidate:["novalidate"],formtarget:HA,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:qK,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:qK}},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},kbt={accesskey:null,class:null,contenteditable:Gf,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:Gf,autocorrect:Gf,autocapitalize:Gf,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":Gf,"aria-autocomplete":["inline","list","both","none"],"aria-busy":Gf,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":Gf,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":Gf,"aria-hidden":Gf,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":Gf,"aria-multiselectable":Gf,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":Gf,"aria-relevant":null,"aria-required":Gf,"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},Obt="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 Obt)kbt[e]=null;class G${constructor(t,n){this.tags={...pFn,...t},this.globalAttrs={...kbt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}G$.default=new G$;function vT(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 yT(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function _bt(e,t,n){let r=n.tags[vT(e,yT(t))];return r?.children||n.allTags}function n1e(e,t){let n=[];for(let r=yT(t);r&&!r.type.isTop;r=yT(r.parent)){let s=vT(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 Cbt=/^[:\-\.\w\u00b7-\uffff]*$/;function r6e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=yT(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:_bt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(n1e(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function s6e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:n1e(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:Cbt}}function hFn(e,t,n,r){let s=[],a=0;for(let i of _bt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of n1e(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function mFn(e,t,n,r,s){let a=yT(n),i=a?t.tags[vT(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:Cbt}}function gFn(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=yT(n),p=f?t.tags[vT(e.doc,f)]:null;d=p?.attrs&&p.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),p='"',h='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,p="",h=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:p+m+h,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function Ebt(e,t){let{state:n,pos:r}=t,s=hi(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)?s6e(n,s,s.from,r):r6e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?r6e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?s6e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?mFn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?gFn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?hFn(n,e,s,r):null}function vFn(e){return Ebt(G$.default,e)}function yFn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new G$(t,n):G$.default;return s=>Ebt(r,s)}const bFn=Zh.parser.configure({top:"SingleExpression"}),jbt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:Jwe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:e1e.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:t1e.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:bFn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:Zh.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:x7.parser}],Tbt=[{name:"style",parser:x7.parser.configure({top:"Styles"})}].concat(Obt.map(e=>({name:e,parser:Zh.parser}))),Nbt=CO.define({name:"html",parser:V6n.configure({props:[j_.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}}),T_.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}}}),fyt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),QF=Nbt.configure({wrap:obt(jbt,Tbt)});function xFn(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=obt((e.nestedLanguages||[]).concat(jbt),(e.nestedAttributes||[]).concat(Tbt)));let r=n?Nbt.configure({wrap:n,dialect:t}):t?QF.configure({dialect:t}):QF;return new jO(r,[QF.data.of({autocomplete:yFn(e)}),e.autoCloseTags!==!1?wFn:[],S7().support,C9n().support])}const a6e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),wFn=Nt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!QF.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let p=i.doc.sliceString(c.from-1,c.to)==r,{head:h}=c,m=hi(i).resolveInner(h,-1),v;if(p&&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=vT(i.doc,y.parent,h))&&!a6e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),S=`</${v}>`;return{range:c,changes:{from:h,to:b,insert:S}}}}else if(p&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==h-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=vT(i.doc,y,h))&&!a6e.has(v)){let b=h+(i.doc.sliceString(h,h+1)===">"?1:0),S=`${v}>`;return{range:bt.cursor(h+S.length,-1),changes:{from:h,to:b,insert:S}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Ibt=xV({commentTokens:{block:{open:"<!--",close:"-->"}}}),Abt=new $r,Rbt=WLn.configure({props:[T_.add(e=>!e.is("Block")||e.is("Document")||whe(e)!=null||SFn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),Abt.add(whe),j_.add({Document:()=>null}),gw.add({Document:Ibt})]});function whe(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function SFn(e){return e.name=="OrderedList"||e.name=="BulletList"}function kFn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=whe(r.type))!=null&&s<=t)break;n=r}return n.to}const OFn=eyt.of((e,t,n)=>{for(let r=hi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(Abt);if(s==null)continue;let a=kFn(r,s);if(a>n)return{from:n,to:a}}return null});function r1e(e){return new bp(Ibt,e,[],"markdown")}const Pbt=r1e(Rbt),_Fn=Rbt.configure([r6n,a6n,s6n,i6n,{props:[T_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),IO=r1e(_Fn);function CFn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=Jm.matchLanguageName(e,n,!0),r instanceof Jm)return r.support?r.support.language.parser:EO.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class WK{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(+Mbt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function $bt(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 WK(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 WK(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 WK(a.parent,c,c+d,i[1],u,f,a))}}return r}function Mbt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function ZK(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=Mbt(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 s1e(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(FN)!=" ")return e;let r=Tg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const Dbt=(e={})=>({state:t,dispatch:n})=>{let r=hi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!IO.isActiveAt(t,l.from,-1)&&!IO.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=$bt(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 p=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&p){let b=f.node.firstChild,S=f.node.getChild("ListItem","ListItem");if(b.to>=c||S&&S.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,_="";w&&w.item?(k=u.from+w.from,_=w.marker(s,1)):k=u.from+(w?w.to:0);let C=[{from:k,to:c,insert:_}];return f.node.name=="OrderedList"&&ZK(f.item,s,C,-2),w&&w.node.name=="OrderedList"&&ZK(w.item,s,C),{range:bt.cursor(k+_.length),changes:C}}else{let w=o6e(d,t,u);return{range:bt.cursor(c+w.length+1),changes:{from:u.from,insert:w+t.lineBreak}}}}if(f.node.name=="Blockquote"&&p&&u.from){let b=s.lineAt(u.from-1),S=/>\s*$/.exec(b.text);if(S&&S.index==f.from){let w=t.changes([{from:b.from+S.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(w),changes:w}}}let h=[];f.node.name=="OrderedList"&&ZK(f.item,s,h);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,S=d.length-1;b<=S;b++)v+=b==S&&!m?d[b].marker(s,1):d[b].blank(b<S?Tg(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=s1e(v,t),EFn(f.node,t.doc)&&(v=o6e(d,t,u)+t.lineBreak+v),h.push({from:y,to:c,insert:t.lineBreak+v}),{range:bt.cursor(y+v.length+1),changes:h}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},Lbt=Dbt();function i6e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function EFn(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 o6e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Tg(n.text,4,e[s+1].from)-r.length:null,s<a);return s1e(r,t)}function jFn(e,t){let n=e.resolveInner(t,-1),r=t;i6e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(i6e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const Fbt=({state:e,dispatch:t})=>{let n=hi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&IO.isActiveAt(e,a.from)){let c=l.lineAt(i),u=$bt(jFn(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:bt.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 p=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let h=d.blank(Tg(c.text,4,d.to)-Tg(c.text,4,d.from));return p==c.from&&(h=s1e(h,e)),{range:bt.cursor(p+h.length),changes:{from:p,to:c.from+d.to,insert:h}}}if(p<i)return{range:bt.cursor(p),changes:{from:p,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},zbt=[{key:"Enter",run:Lbt},{key:"Backspace",run:Fbt}],Bbt=xFn({matchClosingTags:!1});function a1e(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=Pbt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=Bbt}=e;if(!(s instanceof OV))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,OFn],d;i&&u.push(Ubt),n instanceof jO?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?CFn(t,d):void 0;c.push(GLn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(Xp.high(LN.of(zbt)));let p=r1e(s.configure(c));return a&&u.push(p.data.of({autocomplete:TFn})),new jO(p,u)}function TFn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=hi(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:NFn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let GK=null;function NFn(){if(GK)return GK;let e=vFn(new $we(os.create({extensions:Bbt}),0,!0));return GK=e?e.options:[]}const IFn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,Ubt=Nt.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),!IO.isActiveAt(t.state,r.from,1)))return!1;let a=hi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||IFn.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)}}),AFn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:Pbt,deleteMarkupBackward:Fbt,insertNewlineContinueMarkup:Lbt,insertNewlineContinueMarkupCommand:Dbt,markdown:a1e,markdownKeymap:zbt,markdownLanguage:IO,pasteURLAsLink:Ubt},Symbol.toStringTag,{value:"Module"}));function AO(){return AO=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},AO.apply(null,arguments)}var RFn=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=Nt.theme(i,{dark:t==="dark"}),d=Lg.define(a),f=[u,z1(d)];return f},PFn={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)"},$Fn=[{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"}],BN=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 RFn({theme:r,settings:AO({},PFn,a),styles:[...$Fn,...l]})};BN();function qbt(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 MFn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=o1e(e.state,n.from);return r.line?DFn(e):r.block?FFn(e):!1};function i1e(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 DFn=i1e(UFn,0),LFn=i1e(Vbt,0),FFn=i1e((e,t)=>Vbt(e,t,BFn(t)),0);function o1e(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const WA=50;function zFn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-WA,r),i=e.sliceDoc(s,s+WA),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*WA?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+WA),f=e.sliceDoc(s-WA,s));let p=/^\s*/.exec(d)[0].length,h=/\s*$/.exec(f)[0].length,m=f.length-h-n.length;return d.slice(p,p+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+p+t.length,margin:/\s/.test(d.charAt(p+t.length))?1:0},close:{pos:s-h-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function BFn(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 Vbt(e,t,n=t.selection.ranges){let r=n.map(a=>o1e(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>zFn(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 UFn(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=o1e(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let p=/^\s*/.exec(f.text)[0].length,h=p==f.length,m=f.text.slice(p,p+u.length)==u?p:-1;p<f.text.length&&p<c&&(c=p),r.push({line:f,comment:m,token:u,indent:p,empty:h,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 She=Py.define(),qFn=Py.define(),VFn=On.define(),Hbt=On.define({combine(e){return $y(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)})}}),Wbt=gl.define({create(){return Bv.empty},update(e,t){let n=t.state.facet(Hbt),r=t.annotation(She);if(r){let c=tf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=k7(d,d.length,n.minDepth,c):d=Qbt(d,t.startState.selection),new Bv(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(qFn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Tl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=tf.fromTransaction(t),i=t.annotation(Tl.time),l=t.annotation(Tl.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 Bv(e.done.map(tf.fromJSON),e.undone.map(tf.fromJSON))}});function HFn(e={}){return[Wbt,Hbt.of(e),Nt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?Zbt:t.inputType=="historyRedo"?khe:null;return r?(t.preventDefault(),r(n)):!1}})]}function _V(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(Wbt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const Zbt=_V(0,!1),khe=_V(1,!1),WFn=_V(0,!0),ZFn=_V(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&&El.fromJSON(t.changes),[],t.mapped&&Jv.fromJSON(t.mapped),t.startSelection&&bt.fromJSON(t.startSelection),t.selectionsAfter.map(bt.fromJSON))}static fromTransaction(t,n){let r=Lh;for(let s of t.startState.facet(VFn)){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,Lh)}static selection(t){return new tf(void 0,Lh,void 0,void 0,t)}}function k7(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 GFn(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 QFn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function Gbt(e,t){return e.length?t.length?e.concat(t):e:t}const Lh=[],YFn=200;function Qbt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-YFn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),k7(e,e.length-1,1e9,n.setSelAfter(r)))}else return[tf.selection([t])]}function XFn(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 QK(e,t){if(!e.length)return e;let n=e.length,r=Lh;for(;n;){let s=KFn(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)]:Lh}function KFn(e,t,n){let r=Gbt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Lh,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,vr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const JFn=/^(input\.type|delete)($|\.)/;class Bv{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 Bv(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||JFn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,GFn(l.changes,t.changes))||r=="input.type.compose")?i=k7(i,i.length-1,s.minDepth,new tf(t.changes.compose(l.changes),Gbt(vr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Lh)):i=k7(i,i.length,s.minDepth,t),new Bv(i,Lh,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Lh;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&QFn(a[a.length-1],t)?this:new Bv(Qbt(this.done,t),this.undone,n,r)}addMapping(t){return new Bv(QK(this.done,t),QK(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:She.of({side:t,rest:XFn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Lh:s.slice(0,s.length-1);return a.mapped&&(l=QK(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:She.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}Bv.empty=new Bv(Lh,Lh);const e8n=[{key:"Mod-z",run:Zbt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:khe,preventDefault:!0},{linux:"Ctrl-Shift-z",run:khe,preventDefault:!0},{key:"Mod-u",run:WFn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:ZFn,preventDefault:!0}];function UN(e,t){return bt.create(e.ranges.map(t),e.mainIndex)}function Fg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function zg({state:e,dispatch:t},n){let r=UN(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Fg(e,r)),!0)}function CV(e,t){return bt.cursor(t?e.to:e.from)}function Ybt(e,t){return zg(e,n=>n.empty?e.moveByChar(n,t):CV(n,t))}function Vu(e){return e.textDirectionAt(e.state.selection.main.head)==Si.LTR}const Xbt=e=>Ybt(e,!Vu(e)),Kbt=e=>Ybt(e,Vu(e));function Jbt(e,t){return zg(e,n=>n.empty?e.moveByGroup(n,t):CV(n,t))}const t8n=e=>Jbt(e,!Vu(e)),n8n=e=>Jbt(e,Vu(e));function r8n(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 EV(e,t,n){let r=hi(e).resolveInner(t.head),s=n?$r.closedBy:$r.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;r8n(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?zv(e,r.from,1):zv(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,bt.cursor(l,n?-1:1)}const s8n=e=>zg(e,t=>EV(e.state,t,!Vu(e))),a8n=e=>zg(e,t=>EV(e.state,t,Vu(e)));function ext(e,t){return zg(e,n=>{if(!n.empty)return CV(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const txt=e=>ext(e,!1),nxt=e=>ext(e,!0);function rxt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Nt.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 sxt(e,t){let n=rxt(e),{state:r}=e,s=UN(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):CV(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=Nt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Fg(r,s),{effects:a}),!0}const l6e=e=>sxt(e,!1),Ohe=e=>sxt(e,!0);function B1(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=bt.cursor(r.from+a))}return s}const i8n=e=>zg(e,t=>B1(e,t,!0)),o8n=e=>zg(e,t=>B1(e,t,!1)),l8n=e=>zg(e,t=>B1(e,t,!Vu(e))),c8n=e=>zg(e,t=>B1(e,t,Vu(e))),u8n=e=>zg(e,t=>bt.cursor(e.lineBlockAt(t.head).from,1)),d8n=e=>zg(e,t=>bt.cursor(e.lineBlockAt(t.head).to,-1));function f8n(e,t,n){let r=!1,s=UN(e.selection,a=>{let i=zv(e,a.head,-1)||zv(e,a.head,1)||a.head>0&&zv(e,a.head-1,1)||a.head<e.doc.length&&zv(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 bt.cursor(l)});return r?(t(Fg(e,s)),!0):!1}const p8n=({state:e,dispatch:t})=>f8n(e,t);function wm(e,t){let n=UN(e.state.selection,r=>{let s=t(r);return bt.range(r.anchor,s.head,s.goalColumn,s.bidiLevel||void 0,s.assoc)});return n.eq(e.state.selection)?!1:(e.dispatch(Fg(e.state,n)),!0)}function axt(e,t){return wm(e,n=>e.moveByChar(n,t))}const ixt=e=>axt(e,!Vu(e)),oxt=e=>axt(e,Vu(e));function lxt(e,t){return wm(e,n=>e.moveByGroup(n,t))}const h8n=e=>lxt(e,!Vu(e)),m8n=e=>lxt(e,Vu(e)),g8n=e=>wm(e,t=>EV(e.state,t,!Vu(e))),v8n=e=>wm(e,t=>EV(e.state,t,Vu(e)));function cxt(e,t){return wm(e,n=>e.moveVertically(n,t))}const uxt=e=>cxt(e,!1),dxt=e=>cxt(e,!0);function fxt(e,t){return wm(e,n=>e.moveVertically(n,t,rxt(e).height))}const c6e=e=>fxt(e,!1),u6e=e=>fxt(e,!0),y8n=e=>wm(e,t=>B1(e,t,!0)),b8n=e=>wm(e,t=>B1(e,t,!1)),x8n=e=>wm(e,t=>B1(e,t,!Vu(e))),w8n=e=>wm(e,t=>B1(e,t,Vu(e))),S8n=e=>wm(e,t=>bt.cursor(e.lineBlockAt(t.head).from)),k8n=e=>wm(e,t=>bt.cursor(e.lineBlockAt(t.head).to)),d6e=({state:e,dispatch:t})=>(t(Fg(e,{anchor:0})),!0),f6e=({state:e,dispatch:t})=>(t(Fg(e,{anchor:e.doc.length})),!0),p6e=({state:e,dispatch:t})=>(t(Fg(e,{anchor:e.selection.main.anchor,head:0})),!0),h6e=({state:e,dispatch:t})=>(t(Fg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),O8n=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),_8n=({state:e,dispatch:t})=>{let n=jV(e).map(({from:r,to:s})=>bt.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:bt.create(n),userEvent:"select"})),!0},C8n=({state:e,dispatch:t})=>{let n=UN(e.selection,r=>{let s=hi(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 bt.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(Fg(e,n)),!0)};function pxt(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(Fg(n,bt.create(s,s.length-1))),!0)}const E8n=e=>pxt(e,!1),j8n=e=>pxt(e,!0),T8n=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=bt.create([n.main]):n.main.empty||(r=bt.create([bt.cursor(n.main.head)])),r?(t(Fg(e,r)),!0):!1};function u3(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=y6(e,c,!1)):c>i&&(n="delete.forward",c=y6(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=y6(e,i,!1),l=y6(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:bt.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"?Nt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function y6(e,t,n){if(e instanceof Nt)for(let r of e.state.facet(Nt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const hxt=(e,t,n)=>u3(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=Tg(l,a.tabSize),d=u%TO(a)||TO(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=bc(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=bc(i.text,c-i.from,!1,!1)+i.from);return c}),_he=e=>hxt(e,!1,!0),mxt=e=>hxt(e,!0,!1),gxt=(e,t)=>u3(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=bc(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}),vxt=e=>gxt(e,!1),N8n=e=>gxt(e,!0),I8n=e=>u3(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),A8n=e=>u3(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),R8n=e=>u3(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),P8n=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:Sa.of(["",""])},range:bt.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},$8n=({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:bc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:bc(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:bt.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function jV(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 yxt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of jV(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(bt.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(bt.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:bt.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const M8n=({state:e,dispatch:t})=>yxt(e,t,!1),D8n=({state:e,dispatch:t})=>yxt(e,t,!0);function bxt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of jV(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 L8n=({state:e,dispatch:t})=>bxt(e,t,!1),F8n=({state:e,dispatch:t})=>bxt(e,t,!0),z8n=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(jV(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=UN(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 B8n(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=hi(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($r.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 m6e=xxt(!1),U8n=xxt(!0);function xxt(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&&B8n(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new wV(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=Twe(u,a);for(d==null&&(d=Tg(/^\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=["",z$(t,d)];return c&&f.push(z$(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:Sa.of(f)},range:bt.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function l1e(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:bt.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const q8n=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new wV(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=l1e(e,(a,i,l)=>{let c=Twe(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=z$(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},wxt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(l1e(e,(n,r)=>{r.push({from:n.from,insert:e.facet(FN)})}),{userEvent:"input.indent"})),!0),Sxt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(l1e(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Tg(s,e.tabSize),i=0,l=z$(e,Math.max(0,a-TO(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),V8n=e=>(e.setTabFocusMode(),!0),H8n=[{key:"Ctrl-b",run:Xbt,shift:ixt,preventDefault:!0},{key:"Ctrl-f",run:Kbt,shift:oxt},{key:"Ctrl-p",run:txt,shift:uxt},{key:"Ctrl-n",run:nxt,shift:dxt},{key:"Ctrl-a",run:u8n,shift:S8n},{key:"Ctrl-e",run:d8n,shift:k8n},{key:"Ctrl-d",run:mxt},{key:"Ctrl-h",run:_he},{key:"Ctrl-k",run:I8n},{key:"Ctrl-Alt-h",run:vxt},{key:"Ctrl-o",run:P8n},{key:"Ctrl-t",run:$8n},{key:"Ctrl-v",run:Ohe}],W8n=[{key:"ArrowLeft",run:Xbt,shift:ixt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:t8n,shift:h8n,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:l8n,shift:x8n,preventDefault:!0},{key:"ArrowRight",run:Kbt,shift:oxt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:n8n,shift:m8n,preventDefault:!0},{mac:"Cmd-ArrowRight",run:c8n,shift:w8n,preventDefault:!0},{key:"ArrowUp",run:txt,shift:uxt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:d6e,shift:p6e},{mac:"Ctrl-ArrowUp",run:l6e,shift:c6e},{key:"ArrowDown",run:nxt,shift:dxt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:f6e,shift:h6e},{mac:"Ctrl-ArrowDown",run:Ohe,shift:u6e},{key:"PageUp",run:l6e,shift:c6e},{key:"PageDown",run:Ohe,shift:u6e},{key:"Home",run:o8n,shift:b8n,preventDefault:!0},{key:"Mod-Home",run:d6e,shift:p6e},{key:"End",run:i8n,shift:y8n,preventDefault:!0},{key:"Mod-End",run:f6e,shift:h6e},{key:"Enter",run:m6e,shift:m6e},{key:"Mod-a",run:O8n},{key:"Backspace",run:_he,shift:_he,preventDefault:!0},{key:"Delete",run:mxt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:vxt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:N8n,preventDefault:!0},{mac:"Mod-Backspace",run:A8n,preventDefault:!0},{mac:"Mod-Delete",run:R8n,preventDefault:!0}].concat(H8n.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),Z8n=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:s8n,shift:g8n},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:a8n,shift:v8n},{key:"Alt-ArrowUp",run:M8n},{key:"Shift-Alt-ArrowUp",run:L8n},{key:"Alt-ArrowDown",run:D8n},{key:"Shift-Alt-ArrowDown",run:F8n},{key:"Mod-Alt-ArrowUp",run:E8n},{key:"Mod-Alt-ArrowDown",run:j8n},{key:"Escape",run:T8n},{key:"Mod-Enter",run:U8n},{key:"Alt-l",mac:"Ctrl-l",run:_8n},{key:"Mod-i",run:C8n,preventDefault:!0},{key:"Mod-[",run:Sxt},{key:"Mod-]",run:wxt},{key:"Mod-Alt-\\",run:q8n},{key:"Shift-Mod-k",run:z8n},{key:"Shift-Mod-\\",run:p8n},{key:"Mod-/",run:MFn},{key:"Alt-A",run:LFn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:V8n}].concat(W8n),G8n={key:"Tab",run:wxt,shift:Sxt},g6e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class kx{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(g6e(l)):g6e,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 Wd(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=uwe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=jv(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"&&(kx.prototype[Symbol.iterator]=function(){return this});const kxt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},c1e="gm"+(/x/.unicode==null?"":"u");class Oxt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=kxt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new _xt(t,n,r,s,a);this.re=new RegExp(n,c1e+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=O7(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=O7(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 YK=new WeakMap;class Sj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=YK.get(t);if(!s||s.from>=r||s.to<=n){let l=new Sj(n,t.sliceString(n,r));return YK.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)),YK.set(t,new Sj(i,a)),new Sj(n,a.slice(n-i,r-i))}}class _xt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=kxt,this.matchPos=O7(t,s),this.re=new RegExp(n,c1e+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=Sj.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=O7(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Sj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(Oxt.prototype[Symbol.iterator]=_xt.prototype[Symbol.iterator]=function(){return this});function Q8n(e){try{return new RegExp(e,c1e),!0}catch{return!1}}function O7(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 Y8n=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=I4n(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,p=d?+d.slice(1):0,h=u?+u:l.number;if(u&&f){let y=h/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),h=Math.round(t.doc.lines*y)}else u&&c&&(h=h*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,h))),v=bt.cursor(m.from+Math.max(0,Math.min(p,m.length)));e.dispatch({effects:[r,Nt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},X8n={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},K8n=On.define({combine(e){return $y(e,X8n,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function J8n(e){return[szn,rzn]}const ezn=Cn.mark({class:"cm-selectionMatch"}),tzn=Cn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function v6e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=po.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=po.Word)}function nzn(e,t,n,r){return e(t.sliceDoc(n,n+1))==po.Word&&e(t.sliceDoc(r-1,r))==po.Word}const rzn=bo.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(K8n),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Cn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Cn.none;let c=n.wordAt(s.head);if(!c)return Cn.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 Cn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(v6e(i,n,s.from,s.to)&&nzn(i,n,s.from,s.to)))return Cn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Cn.none}let l=[];for(let c of e.visibleRanges){let u=new kx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||v6e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(tzn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(ezn.range(d,f)),l.length>t.maxMatches))return Cn.none}}return Cn.set(l)}},{decorations:e=>e.decorations}),szn=Nt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),azn=({state:e,dispatch:t})=>{let{selection:n}=e,r=bt.create(n.ranges.map(s=>e.wordAt(s.head)||bt.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function izn(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 kx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new kx(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 ozn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return azn({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=izn(e,r);return s?(t(e.update({selection:e.selection.addRange(bt.range(s.from,s.to),!1),effects:Nt.scrollIntoView(s.to)})),!0):!1},qN=On.define({combine(e){return $y(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new wzn(t),scrollToMatch:t=>Nt.scrollIntoView(t)})}});class Cxt{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||Q8n(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"?`
|
|
336
|
-
`: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 pzn(this):new uzn(this)}getCursor(t,n=0,r){let s=t.doc?t:os.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?wE(this,s,n,r):xE(this,s,n,r)}}class Ext{constructor(t){this.spec=t}}function lzn(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 xE(e,t,n,r){let s;return e.wholeWord&&(s=czn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=lzn(e.test,t,s)),new kx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function czn(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(_7(s,n-a))!=po.Word||t(C7(s,n-a))!=po.Word)&&(t(C7(s,r-a))!=po.Word||t(_7(s,r-a))!=po.Word))}class uzn extends Ext{constructor(t){super(t)}nextMatch(t,n,r){let s=xE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=xE(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=xE(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=xE(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=xE(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 dzn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function wE(e,t,n,r){let s;return e.wholeWord&&(s=fzn(t.charCategorizer(t.selection.main.head))),e.test&&(s=dzn(e.test,t,s)),new Oxt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function _7(e,t){return e.slice(bc(e,t,!1),t)}function C7(e,t){return e.slice(t,bc(e,t))}function fzn(e){return(t,n,r)=>!r[0].length||(e(_7(r.input,r.index))!=po.Word||e(C7(r.input,r.index))!=po.Word)&&(e(C7(r.input,r.index+r[0].length))!=po.Word||e(_7(r.input,r.index+r[0].length))!=po.Word)}class pzn extends Ext{nextMatch(t,n,r){let s=wE(this.spec,t,r,t.doc.length).next();return s.done&&(s=wE(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=wE(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=wE(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=wE(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 Q$=vr.define(),u1e=vr.define(),Pw=gl.define({create(e){return new XK(Che(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Q$)?e=new XK(n.value.create(),e.panel):n.is(u1e)&&(e=new XK(e.query,n.value?d1e:null));return e},provide:e=>F$.from(e,t=>t.panel)});class XK{constructor(t,n){this.query=t,this.panel=n}}const hzn=Cn.mark({class:"cm-searchMatch"}),mzn=Cn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),gzn=bo.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Pw))}update(e){let t=e.state.field(Pw);(t!=e.startState.field(Pw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Cn.none;let{view:n}=this,r=new kd;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(p=>p.from==u&&p.to==d);r.add(u,d,f?mzn:hzn)})}return r.finish()}},{decorations:e=>e.decorations});function d3(e){return t=>{let n=t.state.field(Pw,!1);return n&&n.query.spec.valid?e(t,n):Nxt(t)}}const E7=d3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(qN);return e.dispatch({selection:s,effects:[f1e(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Txt(e),!0}),j7=d3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(qN);return e.dispatch({selection:a,effects:[f1e(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Txt(e),!0}),vzn=d3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),yzn=({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 kx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},y6e=d3((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}),d.push(Nt.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=bt.single(i.from,i.to).map(f),d.push(f1e(e,i)),d.push(n.facet(qN).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),bzn=d3((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:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function d1e(e){return e.state.facet(qN).createPanel(e)}function Che(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(qN);return new Cxt({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 jxt(e){let t=Ewe(e,d1e);return t&&t.dom.querySelector("[main-field]")}function Txt(e){let t=jxt(e);t&&t==e.root.activeElement&&t.select()}const Nxt=e=>{let t=e.state.field(Pw,!1);if(t&&t.panel){let n=jxt(e);if(n&&n!=e.root.activeElement){let r=Che(e.state,t.query.spec);r.valid&&e.dispatch({effects:Q$.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[u1e.of(!0),t?Q$.of(Che(e.state,t.query.spec)):vr.appendConfig.of(kzn)]});return!0},Ixt=e=>{let t=e.state.field(Pw,!1);if(!t||!t.panel)return!1;let n=Ewe(e,d1e);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:u1e.of(!1)}),!0},xzn=[{key:"Mod-f",run:Nxt,scope:"editor search-panel"},{key:"F3",run:E7,shift:j7,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:E7,shift:j7,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Ixt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:yzn},{key:"Mod-Alt-g",run:Y8n},{key:"Mod-d",run:ozn,preventDefault:!0}];class wzn{constructor(t){this.view=t;let n=this.query=t.state.field(Pw).query.spec;this.commit=this.commit.bind(this),this.searchField=ci("input",{value:n.search,placeholder:Qf(t,"Find"),"aria-label":Qf(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ci("input",{value:n.replace,placeholder:Qf(t,"Replace"),"aria-label":Qf(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ci("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ci("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ci("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ci("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ci("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>E7(t),[Qf(t,"next")]),r("prev",()=>j7(t),[Qf(t,"previous")]),r("select",()=>vzn(t),[Qf(t,"all")]),ci("label",null,[this.caseField,Qf(t,"match case")]),ci("label",null,[this.reField,Qf(t,"regexp")]),ci("label",null,[this.wordField,Qf(t,"by word")]),...t.state.readOnly?[]:[ci("br"),this.replaceField,r("replace",()=>y6e(t),[Qf(t,"replace")]),r("replaceAll",()=>bzn(t),[Qf(t,"replace all")])],ci("button",{name:"close",onclick:()=>Ixt(t),"aria-label":Qf(t,"close"),type:"button"},["×"])])}commit(){let t=new Cxt({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:Q$.of(t)}))}keydown(t){B3n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?j7:E7)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),y6e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Q$)&&!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(qN).top}}function Qf(e,t){return e.state.phrase(t)}const b6=30,x6=/[\s\.,:;?!]/;function f1e(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-b6),i=Math.min(s,n+b6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<b6;c++)if(!x6.test(l[c+1])&&x6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-b6;c--)if(!x6.test(l[c-1])&&x6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const Szn=Nt.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"}}),kzn=[Pw,Xp.low(gzn),Szn];class b6e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class pk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(Y$).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new kd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=Mzn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Cn.widget({widget:new Azn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Cn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new pk(u,n,bT(u))}}function bT(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 b6e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new b6e(r.from,a,r.diagnostic)}}),r}function Ozn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(Y$).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(Axt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function _zn(e,t){return e.field(xp,!1)?t:t.concat(vr.appendConfig.of(Dzn))}const Axt=vr.define(),p1e=vr.define(),Rxt=vr.define(),xp=gl.define({create(){return new pk(Cn.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=bT(n,e.selected.diagnostic,a)||bT(n,null,a)}!n.size&&s&&t.state.facet(Y$).autoPanel&&(s=null),e=new pk(n,s,r)}for(let n of t.effects)if(n.is(Axt)){let r=t.state.facet(Y$).autoPanel?n.value.length?X$.open:null:e.panel;e=pk.init(n.value,r,t.state)}else n.is(p1e)?e=new pk(e.diagnostics,n.value?X$.open:null,e.selected):n.is(Rxt)&&(e=new pk(e.diagnostics,e.panel,n.value));return e},provide:e=>[F$.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),Czn=Cn.mark({class:"cm-lintRange cm-lintRange-active"});function Ezn(e,t,n){let{diagnostics:r}=e.state.field(xp),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(Y$).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:jzn(e,s)}}}:null}function jzn(e,t){return ci("ul",{class:"cm-tooltip-lint"},t.map(n=>$xt(e,n,!1)))}const Tzn=e=>{let t=e.state.field(xp,!1);(!t||!t.panel)&&e.dispatch({effects:_zn(e.state,[p1e.of(!0)])});let n=Ewe(e,X$.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},x6e=e=>{let t=e.state.field(xp,!1);return!t||!t.panel?!1:(e.dispatch({effects:p1e.of(!1)}),!0)},Nzn=e=>{let t=e.state.field(xp,!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)},Izn=[{key:"Mod-Shift-m",run:Tzn,preventDefault:!0},{key:"F8",run:Nzn}],Y$=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...$y(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:w6e,tooltipFilter:w6e,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 w6e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Pxt(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 $xt(e,t,n){var r;let s=n?Pxt(t.actions):[];return ci("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ci("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=h=>{if(h.preventDefault(),l)return;l=!0;let m=bT(e.state.field(xp).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),ci("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ci("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ci("div",{class:"cm-diagnosticSource"},t.source))}class Azn extends Kp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ci("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class S6e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=$xt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class X${constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)x6e(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=Pxt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=bT(this.view.state.field(xp).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=ci("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ci("div",{class:"cm-panel-lint"},this.list,ci("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>x6e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(xp).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(xp),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,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new S6e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.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 S6e(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(xp),r=bT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Rxt.of(r)})}static open(t){return new X$(t)}}function Rzn(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 w6(e){return Rzn(`<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 Pzn=Nt.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:w6("#d11")},".cm-lintRange-warning":{backgroundImage:w6("orange")},".cm-lintRange-info":{backgroundImage:w6("#999")},".cm-lintRange-hint":{backgroundImage:w6("#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 $zn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function Mzn(e){let t="hint",n=1;for(let r of e){let s=$zn(r.severity);s>n&&(n=s,t=r.severity)}return t}const Dzn=[xp,Nt.decorations.compute([xp],e=>{let{selected:t,panel:n}=e.field(xp);return!t||!n||t.from==t.to?Cn.none:Cn.set([Czn.range(t.from,t.to)])}),T4n(Ezn,{hideOn:Ozn}),Pzn];var k6e=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(CLn)),t.defaultKeymap!==!1&&(a=a.concat(Z8n)),t.searchKeymap!==!1&&(a=a.concat(xzn)),t.historyKeymap!==!1&&(a=a.concat(e8n)),t.foldKeymap!==!1&&(a=a.concat(d5n)),t.completionKeymap!==!1&&(a=a.concat(Tyt)),t.lintKeymap!==!1&&(a=a.concat(Izn));var i=[];return t.lineNumbers!==!1&&i.push(B4n()),t.highlightActiveLineGutter!==!1&&i.push(V4n()),t.highlightSpecialChars!==!1&&i.push(r4n()),t.history!==!1&&i.push(HFn()),t.foldGutter!==!1&&i.push(m5n()),t.drawSelection!==!1&&i.push(Z3n()),t.dropCursor!==!1&&i.push(K3n()),t.allowMultipleSelections!==!1&&i.push(os.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(r5n()),t.syntaxHighlighting!==!1&&i.push(z1(b5n,{fallback:!0})),t.bracketMatching!==!1&&i.push(C5n()),t.closeBrackets!==!1&&i.push(SLn()),t.autocompletion!==!1&&i.push(jyt()),t.rectangularSelection!==!1&&i.push(v4n()),s!==!1&&i.push(x4n()),t.highlightActiveLine!==!1&&i.push(c4n()),t.highlightSelectionMatches!==!1&&i.push(J8n()),t.tabSize&&typeof t.tabSize=="number"&&i.push(FN.of(" ".repeat(t.tabSize))),i.concat([LN.of(a.flat())]).filter(Boolean)};const Lzn="#e5c07b",O6e="#e06c75",Fzn="#56b6c2",zzn="#ffffff",YF="#abb2bf",Ehe="#7d8799",Bzn="#61afef",Uzn="#98c379",_6e="#d19a66",qzn="#c678dd",Vzn="#21252b",C6e="#2c313a",E6e="#282c34",KK="#353a42",Hzn="#3E4451",j6e="#528bff",Wzn=Nt.theme({"&":{color:YF,backgroundColor:E6e},".cm-content":{caretColor:j6e},".cm-cursor, .cm-dropCursor":{borderLeftColor:j6e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Hzn},".cm-panels":{backgroundColor:Vzn,color:YF},".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:E6e,color:Ehe,border:"none"},".cm-activeLineGutter":{backgroundColor:C6e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:KK},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:KK,borderBottomColor:KK},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:C6e,color:YF}}},{dark:!0}),Zzn=Lg.define([{tag:fe.keyword,color:qzn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:O6e},{tag:[fe.function(fe.variableName),fe.labelName],color:Bzn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:_6e},{tag:[fe.definition(fe.name),fe.separator],color:YF},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:Lzn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:Fzn},{tag:[fe.meta,fe.comment],color:Ehe},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Ehe,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:O6e},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:_6e},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:Uzn},{tag:fe.invalid,color:zzn}]),Gzn=[Wzn,z1(Zzn)];var Qzn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),Yzn=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,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(LN.of([G8n])),m&&(typeof m=="boolean"?v.unshift(k6e()):v.unshift(k6e(m))),p&&v.unshift(p4n(p)),d){case"light":v.push(Qzn);break;case"dark":v.push(Gzn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Nt.editable.of(!1)),c&&v.push(os.readOnly.of(!0)),[...v]},Xzn=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 Kzn{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 T6e{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 JK=null,Jzn=()=>typeof window>"u"?new T6e:(JK||(JK=new T6e),JK),N6e=Py.define(),e7n=200,t7n=[];function n7n(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?t7n:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,S=e.width,w=S===void 0?null:S,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,j=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,P=e.readOnly,F=P===void 0?!1:P,D=e.indentWithTab,V=D===void 0?!0:D,H=e.basicSetup,L=H===void 0?!0:H,z=e.root,B=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),U=$[0],Z=$[1],X=g.useState(),te=X[0],J=X[1],ee=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],ce=Nt.theme({"&":{height:h,minHeight:v,maxHeight:b,width:w,minWidth:_,maxWidth:j},"& .cm-scroller":{height:"100% !important"}}),Y=Nt.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ye=>ye.annotation(N6e))){ee.current?ee.current.reset():(ee.current=new Kzn(()=>{if(ae.current){var ye=ae.current;ae.current=null,ye()}ee.current=null},e7n),Jzn().add(ee.current));var oe=pe.state.doc,ve=oe.toString();r(ve,pe)}s&&s(Xzn(pe))}),ne=Yzn({theme:f,editable:A,readOnly:F,placeholder:N,indentWithTab:V,basicSetup:L}),ue=[Y,ce,...ne];return i&&typeof i=="function"&&ue.push(Nt.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var pe={doc:t,selection:n,extensions:ue},oe=B?os.fromJSON(B.json,pe,B.fields):os.create(pe);if(J(oe),!U){var ve=new Nt({state:oe,parent:G,root:z});Z(ve),a&&a(ve,oe)}}return()=>{U&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(ue)})},[f,c,h,v,b,w,_,j,N,A,F,V,L,r,i]),g.useEffect(()=>{if(t!==void 0){var pe=U?U.state.doc.toString():"";if(U&&t!==pe){var oe=ee.current&&!ee.current.isDone,ve=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[N6e.of(!0)]})};oe?ae.current=ve:ve()}}},[t,U]),{state:te,setState:J,view:U,setView:Z,container:G,setContainer:q}}var r7n=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],au=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,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,S=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,j=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=qbt(e,r7n),F=g.useRef(null),D=n7n({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:S,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:j,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),V=D.state,H=D.view,L=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:F.current,state:V,view:H}),[F,L,V,H]);var B=g.useCallback(G=>{F.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",AO({ref:B,className:""+M+(n?" "+n:"")},P))});au.displayName="CodeMirror";const s7n={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"};let eJ=null;function a7n(){return eJ||(eJ=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([lo(()=>import("./core-D6Mi7xny.js"),__vite__mapDeps([0,1,2]),import.meta.url),lo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[lo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),lo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[lo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),lo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),lo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),lo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),lo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),lo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),lo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),lo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),eJ}async function i7n(e,t){const n=s7n[t?.toLowerCase()];if(!n)return null;const r=await a7n(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function o7n(e){return new jO(Awe.define(e))}const Mxt=[Jm.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript())}}),Jm.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return lo(()=>Promise.resolve().then(()=>L5n),void 0,import.meta.url).then(e=>e.json())}}),Jm.of({name:"JSX",extensions:["jsx"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Jm.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return lo(()=>Promise.resolve().then(()=>AFn),void 0,import.meta.url).then(e=>e.markdown())}}),Jm.of({name:"TSX",extensions:["tsx"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Jm.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),Jm.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return lo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>o7n(e.shell))}})];function l7n(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 c7n(e){const t=l7n(e);return jyt({override:[u7n(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function u7n(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,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const d7n=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,f7n=Cn.mark({class:"cm-variable-highlight"}),I6e=new Uvt({regexp:d7n,decoration:()=>f7n}),p7n=bo.fromClass(class{decorations;constructor(e){this.decorations=I6e.createDeco(e)}update(e){this.decorations=I6e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),h7n=p7n;function m7n(){const e=BN({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=Nt.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 g7n(){const e=Nt.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=Lg.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,z1(t)]}const My=()=>{const e=RN().resolvedTheme==="dark";return g.useMemo(()=>e?m7n():g7n(),[e])},v7n=Fo(K("font-mono relative overflow-hidden outline-hidden focus:outline-hidden focus-within:outline-hidden","transition-colors duration-normal ease-out-custom"),{variants:{variant:{default:"rounded-md bg-surface3 border border-border1 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),y7n=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),b7n=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),x7n=[y7n,b7n],Yr=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:p,variant:h,...m},v)=>{const y=My(),b=e?JSON.stringify(e,null,2):t??"",S=g.useMemo(()=>{const w=[...x7n];return f&&w.push(Nt.lineWrapping),a==="json"?w.push(ff):a==="markdown"&&w.push(a1e({base:IO,codeLanguages:Mxt})),i&&a==="markdown"&&w.push(h7n),c&&a==="markdown"&&w.push(c7n(c)),p===!1&&w.push(os.readOnly.of(!0)),w},[a,i,c,p,f]);return o.jsxs("div",{className:K(v7n({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(au,{ref:v,value:b,theme:y,extensions:S,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),w7n=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},S7n=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=My(),{settings:r,setSettings:s}=tV(),a=r?.tracingOptions,i=g.useMemo(()=>w7n(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}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(au,{value:l,onChange:d,theme:n,extensions:[ff],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(de,{type:"button",onClick:f,children:"Save"})})]})},k7n=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(de,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ue,{children:o.jsx(hq,{})})})}),o.jsx(Ln,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Qs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Pr,{children:o.jsx(S7n,{onSaved:()=>t(!1)})})]})})]})};function O7n({status:e}){switch(e){case"running":return o.jsx(Gt,{});case"failed":return o.jsx(vs,{className:"text-accent2"});case"canceled":return o.jsx(Of,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(Gj,{className:"text-neutral3"});case"suspended":return o.jsx(lq,{className:"text-accent3"});case"success":return o.jsx(ea,{className:"text-accent1"});default:return o.jsx(Gj,{className:"text-neutral3"})}}function Dxt({status:e}){return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(Ue,{"aria-label":e,className:"shrink-0",children:o.jsx(O7n,{status:e})})}),o.jsx(Ln,{children:e})]})}var tJ,A6e;function h1e(){if(A6e)return tJ;A6e=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 p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.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 p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),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 p=f;p!==void 0;p=this.parent(p))if(p===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 h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.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 p=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,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[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 p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==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?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);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,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.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,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return tJ=r,tJ}var nJ,R6e;function _7n(){return R6e||(R6e=1,nJ="2.2.4"),nJ}var rJ,P6e;function C7n(){return P6e||(P6e=1,rJ={Graph:h1e(),version:_7n()}),rJ}var sJ,$6e;function E7n(){if($6e)return sJ;$6e=1;var e=h1e();sJ={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 sJ}var aJ,M6e;function j7n(){if(M6e)return aJ;M6e=1,aJ=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 aJ}var iJ,D6e;function Lxt(){if(D6e)return iJ;D6e=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 iJ=e,iJ}var oJ,L6e;function Fxt(){if(L6e)return oJ;L6e=1;var e=Lxt();oJ=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,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return oJ}var lJ,F6e;function T7n(){if(F6e)return lJ;F6e=1;var e=Fxt();lJ=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return lJ}var cJ,z6e;function zxt(){if(z6e)return cJ;z6e=1,cJ=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 cJ}var uJ,B6e;function N7n(){if(B6e)return uJ;B6e=1;var e=zxt();uJ=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return uJ}var dJ,U6e;function I7n(){if(U6e)return dJ;U6e=1,dJ=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(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return dJ}var fJ,q6e;function Bxt(){if(q6e)return fJ;q6e=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 fJ=e,e.CycleException=t,fJ}var pJ,V6e;function A7n(){if(V6e)return pJ;V6e=1;var e=Bxt();pJ=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return pJ}var hJ,H6e;function Uxt(){if(H6e)return hJ;H6e=1,hJ=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 hJ}var mJ,W6e;function R7n(){if(W6e)return mJ;W6e=1;var e=Uxt();mJ=t;function t(n,r){return e(n,r,"post")}return mJ}var gJ,Z6e;function P7n(){if(Z6e)return gJ;Z6e=1;var e=Uxt();gJ=t;function t(n,r){return e(n,r,"pre")}return gJ}var vJ,G6e;function $7n(){if(G6e)return vJ;G6e=1;var e=h1e(),t=Lxt();vJ=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,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 vJ}var yJ,Q6e;function M7n(){return Q6e||(Q6e=1,yJ={components:j7n(),dijkstra:Fxt(),dijkstraAll:T7n(),findCycles:N7n(),floydWarshall:I7n(),isAcyclic:A7n(),postorder:R7n(),preorder:P7n(),prim:$7n(),tarjan:zxt(),topsort:Bxt()}),yJ}var bJ,Y6e;function Ig(){if(Y6e)return bJ;Y6e=1;var e=C7n();return bJ={Graph:e.Graph,json:E7n(),alg:M7n(),version:e.version},bJ}var xJ,X6e;function D7n(){if(X6e)return xJ;X6e=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 xJ=e,xJ}var wJ,K6e;function L7n(){if(K6e)return wJ;K6e=1;let e=Ig().Graph,t=D7n();wJ=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(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,S=u.node(b);S.in-=y,l(d,f,S)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=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,S=d(y),w=b+S;f.setEdge(y.v,y.w,w),h=Math.max(h,f.node(y.v).out+=S),p=Math.max(p,f.node(y.w).in+=S)});let m=c(h+p+3).map(()=>new t),v=p+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 wJ}var SJ,J6e;function Nl(){if(J6e)return SJ;J6e=1;let e=Ig().Graph;SJ={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:j};function t(E,N,I,A){for(var P=A;E.hasNode(P);)P=w(A);return I.dummy=N,E.setNode(P,I),P}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},P=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+P.weight,minlen:Math.max(A.minlen,P.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(P=>{A[P.w]=(A[P.w]||0)+E.edge(P).weight}),A});return j(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(P=>{A[P.v]=(A[P.v]||0)+E.edge(P).weight}),A});return j(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,P=N.x-I,F=N.y-A,D=E.width/2,V=E.height/2;if(!P&&!F)throw new Error("Not possible to find intersection inside of the rectangle");let H,L;return Math.abs(F)*D>Math.abs(P)*V?(F<0&&(V=-V),H=V*P/F,L=V):(P<0&&(D=-D),H=D,L=D*F/P),{x:I+H,y:A+L}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),P=A.rank;P!==void 0&&(N[P][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MAX_VALUE:P}),I=h(Math.min,N);E.nodes().forEach(A=>{let P=E.node(A);Object.hasOwn(P,"rank")&&(P.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=h(Math.min,N),A=[];E.nodes().forEach(D=>{let V=E.node(D).rank-I;A[V]||(A[V]=[]),A[V].push(D)});let P=0,F=E.graph().nodeRankFactor;Array.from(A).forEach((D,V)=>{D===void 0&&V%F!==0?--P:D!==void 0&&P&&D.forEach(H=>E.node(H).rank+=P)})}function d(E,N,I,A){let P={width:0,height:0};return arguments.length>=4&&(P.rank=I,P.order=A),t(E,"border",P,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const P=E.slice(A,A+N);I.push(P)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MIN_VALUE:P});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let S=0;function w(E){var N=++S;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=F=>F<N;I<0&&(A=F=>N<F);const P=[];for(let F=E;A(F);F+=I)P.push(F);return P}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[P,F])=>(A[P]=I(F,P),A),{})}function j(E,N){return E.reduce((I,A,P)=>(I[A]=N[P],I),{})}return SJ}var kJ,e9e;function F7n(){if(e9e)return kJ;e9e=1;let e=L7n(),t=Nl().uniqueId;kJ={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 kJ}var OJ,t9e;function z7n(){if(t9e)return OJ;t9e=1;let e=Nl();OJ={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),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;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 OJ}var _J,n9e;function T7(){if(n9e)return _J;n9e=1;const{applyWithChunking:e}=Nl();_J={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 _J}var CJ,r9e;function qxt(){if(r9e)return CJ;r9e=1;var e=Ig().Graph,t=T7().slack;CJ=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,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}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 CJ}var EJ,s9e;function B7n(){if(s9e)return EJ;s9e=1;var e=qxt(),t=T7().slack,n=T7().longestPath,r=Ig().alg.preorder,s=Ig().alg.postorder,a=Nl().simplify;EJ=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(S){S=a(S),n(S);var w=e(S);d(w),l(w,S);for(var k,_;k=p(w);)_=h(w,S,k),m(w,S,k,_)}function l(S,w){var k=s(S,S.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(S,w,_))}function c(S,w,k){var _=S.node(k),C=_.parent;S.edge(k,C).cutvalue=u(S,w,k)}function u(S,w,k){var _=S.node(k),C=_.parent,j=!0,E=w.edge(k,C),N=0;return E||(j=!1,E=w.edge(C,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,P=A?I.w:I.v;if(P!==C){var F=A===j,D=w.edge(I).weight;if(N+=F?D:-D,y(S,k,P)){var V=S.edge(k,P).cutvalue;N+=F?-V:V}}}),N}function d(S,w){arguments.length<2&&(w=S.nodes()[0]),f(S,{},1,w)}function f(S,w,k,_,C){var j=k,E=S.node(_);return w[_]=!0,S.neighbors(_).forEach(N=>{Object.hasOwn(w,N)||(k=f(S,w,k,N,_))}),E.low=j,E.lim=k++,C?E.parent=C:delete E.parent,k}function p(S){return S.edges().find(w=>S.edge(w).cutvalue<0)}function h(S,w,k){var _=k.v,C=k.w;w.hasEdge(_,C)||(_=k.w,C=k.v);var j=S.node(_),E=S.node(C),N=j,I=!1;j.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(P=>I===b(S,S.node(P.v),N)&&I!==b(S,S.node(P.w),N));return A.reduce((P,F)=>t(w,F)<t(w,P)?F:P)}function m(S,w,k,_){var C=k.v,j=k.w;S.removeEdge(C,j),S.setEdge(_.v,_.w,{}),d(S),l(S,w),v(S,w)}function v(S,w){var k=S.nodes().find(C=>!w.node(C).parent),_=r(S,k);_=_.slice(1),_.forEach(C=>{var j=S.node(C).parent,E=w.edge(C,j),N=!1;E||(E=w.edge(j,C),N=!0),w.node(C).rank=w.node(j).rank+(N?E.minlen:-E.minlen)})}function y(S,w,k){return S.hasEdge(w,k)}function b(S,w,k){return k.low<=w.lim&&w.lim<=k.lim}return EJ}var jJ,a9e;function U7n(){if(a9e)return jJ;a9e=1;var e=T7(),t=e.longestPath,n=qxt(),r=B7n();jJ=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 jJ}var TJ,i9e;function q7n(){if(i9e)return TJ;i9e=1,TJ=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,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),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,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}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 TJ}var NJ,o9e;function V7n(){if(o9e)return NJ;o9e=1;let e=Nl();NJ={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(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let S=i.node(b),w=S.borderTop?S.borderTop:b,k=S.borderBottom?S.borderBottom:b,_=S.borderTop?u:2*u,C=w!==k?1:d-f[p]+1;i.setEdge(m,w,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,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 NJ}var IJ,l9e;function H7n(){if(l9e)return IJ;l9e=1;let e=Nl();IJ=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 IJ}var AJ,c9e;function W7n(){if(c9e)return AJ;c9e=1,AJ={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 AJ}var RJ,u9e;function Z7n(){if(u9e)return RJ;u9e=1;let e=Nl();RJ=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 RJ}var PJ,d9e;function G7n(){if(d9e)return PJ;d9e=1;let e=Nl().zipObject;PJ=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((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.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(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return PJ}var $J,f9e;function Q7n(){if(f9e)return $J;f9e=1,$J=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 $J}var MJ,p9e;function Y7n(){if(p9e)return MJ;p9e=1;let e=Nl();MJ=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 MJ}var DJ,h9e;function X7n(){if(h9e)return DJ;h9e=1;let e=Nl();DJ=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,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}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 DJ}var LJ,m9e;function K7n(){if(m9e)return LJ;m9e=1;let e=Q7n(),t=Y7n(),n=X7n();LJ=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(S=>S!==p&&S!==h));let v=e(i,d);v.forEach(S=>{if(i.children(S.v).length){let w=r(i,S.v,c,u);m[S.v]=w,Object.hasOwn(w,"barycenter")&&a(S,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let S=i.node(i.predecessors(p)[0]),w=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+S.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 LJ}var FJ,g9e;function J7n(){if(g9e)return FJ;g9e=1;let e=Ig().Graph,t=Nl();FJ=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),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).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 FJ}var zJ,v9e;function eBn(){if(v9e)return zJ;v9e=1,zJ=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 zJ}var BJ,y9e;function tBn(){if(y9e)return BJ;y9e=1;let e=Z7n(),t=G7n(),n=K7n(),r=J7n(),s=eBn(),a=Ig().Graph,i=Nl();BJ=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,S;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,S=Object.assign({},y),b=_)}d(f,S)}function c(f,p,h){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 S=b.minRank;S<=b.maxRank;S++)S!==b.rank&&v(S,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,S)=>m.node(b).order=S),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return BJ}var UJ,b9e;function nBn(){if(b9e)return UJ;b9e=1;let e=Ig().Graph,t=Nl();UJ={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let S={};function w(k,_){let C=0,j=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let P=s(y,I),F=P?y.node(P).order:E;(P||I===N)&&(_.slice(j,A+1).forEach(D=>{y.predecessors(D).forEach(V=>{let H=y.node(V),L=H.order;(L<C||F<L)&&!(H.dummy&&y.node(D).dummy)&&a(S,V,D)})}),j=A+1,C=F)}),_}return b.length&&b.reduce(w),S}function r(y,b){let S={};function w(_,C,j,E,N){let I;t.range(C,j).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(P=>{let F=y.node(P);F.dummy&&(F.order<E||F.order>N)&&a(S,P,I)})})}function k(_,C){let j=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let P=y.predecessors(I);P.length&&(E=y.node(P[0]).order,w(C,N,A,j,E),N=A,j=E)}w(C,N,C.length,E,_.length)}),C}return b.length&&b.reduce(k),S}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(S=>y.node(S).dummy)}function a(y,b,S){if(b>S){let k=b;b=S,S=k}let w=y[b];w||(y[b]=w={}),w[S]=!0}function i(y,b,S){if(b>S){let w=b;b=S,S=w}return!!y[b]&&Object.hasOwn(y[b],S)}function l(y,b,S,w){let k={},_={},C={};return b.forEach(j=>{j.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(j=>{let E=-1;j.forEach(N=>{let I=w(N);if(I.length){I=I.sort((P,F)=>C[P]-C[F]);let A=(I.length-1)/2;for(let P=Math.floor(A),F=Math.ceil(A);P<=F;++P){let D=I[P];_[N]===N&&E<C[D]&&!i(S,N,D)&&(_[D]=N,_[N]=k[N]=k[D],E=C[D])}}})}),{root:k,align:_}}function c(y,b,S,w,k){let _={},C=u(y,b,S,k),j=k?"borderLeft":"borderRight";function E(A,P){let F=C.nodes(),D=F.pop(),V={};for(;D;)V[D]?A(D):(V[D]=!0,F.push(D),F=F.concat(P(D))),D=F.pop()}function N(A){_[A]=C.inEdges(A).reduce((P,F)=>Math.max(P,_[F.v]+C.edge(F)),0)}function I(A){let P=C.outEdges(A).reduce((D,V)=>Math.min(D,_[V.w]-C.edge(V)),Number.POSITIVE_INFINITY),F=y.node(A);P!==Number.POSITIVE_INFINITY&&F.borderType!==j&&(_[A]=Math.max(_[A],P))}return E(N,C.predecessors.bind(C)),E(I,C.successors.bind(C)),Object.keys(w).forEach(A=>_[A]=_[S[A]]),_}function u(y,b,S,w){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,w);return b.forEach(j=>{let E;j.forEach(N=>{let I=S[N];if(k.setNode(I),E){var A=S[E],P=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),P||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((S,w)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([j,E])=>{let N=v(y,j)/2;k=Math.max(E+N,k),_=Math.min(E-N,_)});const C=k-_;return C<S[0]&&(S=[C,w]),S},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let S=Object.values(b),w=t.applyWithChunking(Math.min,S),k=t.applyWithChunking(Math.max,S);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let j=_+C,E=y[j];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[j]=t.mapValues(E,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(S,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(_=>_[w]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),S=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(j=>{j==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,S,E),I=c(y,k,N.root,N.align,j==="r");j==="r"&&(I=t.mapValues(I,A=>-A)),w[C+j]=I})});let _=d(y,w);return f(w,_),p(w,y.graph().align)}function m(y,b,S){return(w,k,_)=>{let C=w.node(k),j=w.node(_),E=0,N;if(E+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(E+=S?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(j.dummy?b:y)/2,E+=j.width/2,Object.hasOwn(j,"labelpos"))switch(j.labelpos.toLowerCase()){case"l":N=j.width/2;break;case"r":N=-j.width/2;break}return N&&(E+=S?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return UJ}var qJ,x9e;function rBn(){if(x9e)return qJ;x9e=1;let e=Nl(),t=nBn().positionX;qJ=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 p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return qJ}var VJ,w9e;function sBn(){if(w9e)return VJ;w9e=1;let e=F7n(),t=z7n(),n=U7n(),r=Nl().normalizeRanks,s=q7n(),a=Nl().removeEmptyRanks,i=V7n(),l=H7n(),c=W7n(),u=tBn(),d=rBn(),f=Nl(),p=Ig().Graph;VJ=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let X=Z(" buildLayoutGraph",()=>E($));Z(" runLayout",()=>m(X,Z,U)),Z(" updateInputGraph",()=>v($,X))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>z($)),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",()=>P($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>B($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>M($)),U(" removeBorderNodes",()=>L($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>V($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>F($)),U(" assignNodeIntersects",()=>D($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(Z=>{let X=$.node(Z),te=U.node(Z);X&&(X.x=te.x,X.y=te.y,X.rank=te.rank,U.children(Z).length&&(X.width=te.width,X.height=te.height))}),$.edges().forEach(Z=>{let X=$.edge(Z),te=U.edge(Z);X.points=te.points,Object.hasOwn(te,"x")&&(X.x=te.x,X.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"},S=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},j=["labelpos"];function E($){let U=new p({multigraph:!0,compound:!0}),Z=q($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,S))),$.nodes().forEach(X=>{let te=q($.node(X));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),U.setNode(X,J),U.setParent(X,$.parent(X))}),$.edges().forEach(X=>{let te=q($.edge(X));U.setEdge(X,Object.assign({},C,G(te,_),f.pick(te,j)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let X=$.edge(Z);X.minlen*=2,X.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?X.width+=X.labeloffset:X.height+=X.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let X=$.node(U.v),J={rank:($.node(U.w).rank-X.rank)/2+X.rank,e:U};f.addDummyNode($,"edge-proxy",J,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let X=$.node(Z);X.borderTop&&(X.minRank=$.node(X.borderTop).rank,X.maxRank=$.node(X.borderBottom).rank,U=Math.max(U,X.maxRank))}),$.graph().maxRank=U}function P($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function F($){let U=Number.POSITIVE_INFINITY,Z=0,X=Number.POSITIVE_INFINITY,te=0,J=$.graph(),ee=J.marginx||0,ae=J.marginy||0;function ce(Y){let ne=Y.x,ue=Y.y,pe=Y.width,oe=Y.height;U=Math.min(U,ne-pe/2),Z=Math.max(Z,ne+pe/2),X=Math.min(X,ue-oe/2),te=Math.max(te,ue+oe/2)}$.nodes().forEach(Y=>ce($.node(Y))),$.edges().forEach(Y=>{let ne=$.edge(Y);Object.hasOwn(ne,"x")&&ce(ne)}),U-=ee,X-=ae,$.nodes().forEach(Y=>{let ne=$.node(Y);ne.x-=U,ne.y-=X}),$.edges().forEach(Y=>{let ne=$.edge(Y);ne.points.forEach(ue=>{ue.x-=U,ue.y-=X}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=X)}),J.width=Z-U+ee,J.height=te-X+ae}function D($){$.edges().forEach(U=>{let Z=$.edge(U),X=$.node(U.v),te=$.node(U.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=X),Z.points.unshift(f.intersectRect(X,J)),Z.points.push(f.intersectRect(te,ee))})}function V($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function L($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),X=$.node(Z.borderTop),te=$.node(Z.borderBottom),J=$.node(Z.borderLeft[Z.borderLeft.length-1]),ee=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-X.y),Z.x=J.x+Z.width/2,Z.y=X.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function z($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function B($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var X=0;Z.forEach((te,J)=>{var ee=$.node(te);ee.order=J+X,(ee.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:ee.rank,order:J+ ++X,e:ae.e,label:ae.label},"_se")}),delete ee.selfEdges})})}function M($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var X=$.node(Z.e.v),te=X.x+X.width/2,J=X.y,ee=Z.x-te,ae=X.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:te+2*ee/3,y:J-ae},{x:te+5*ee/6,y:J-ae},{x:te+ee,y:J},{x:te+5*ee/6,y:J+ae},{x:te+2*ee/3,y:J+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function q($){var U={};return $&&Object.entries($).forEach(([Z,X])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=X}),U}return VJ}var HJ,S9e;function aBn(){if(S9e)return HJ;S9e=1;let e=Nl(),t=Ig().Graph;HJ={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 HJ}var WJ,k9e;function iBn(){return k9e||(k9e=1,WJ="1.1.8"),WJ}var ZJ,O9e;function oBn(){return O9e||(O9e=1,ZJ={graphlib:Ig(),layout:sBn(),debug:aBn(),util:{time:Nl().time,notime:Nl().notime},version:iBn()}),ZJ}var lBn=oBn();const _9e=jc(lBn);function Ml(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=Ml(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var cBn={value:()=>{}};function TV(){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 XF(n)}function XF(e){this._=e}function uBn(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}})}XF.prototype=TV.prototype={constructor:XF,on:function(e,t){var n=this._,r=uBn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=dBn(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]=C9e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=C9e(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 XF(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 dBn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function C9e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=cBn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var jhe="http://www.w3.org/1999/xhtml";const E9e={svg:"http://www.w3.org/2000/svg",xhtml:jhe,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function NV(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),E9e.hasOwnProperty(t)?{space:E9e[t],local:e}:e}function fBn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===jhe&&t.documentElement.namespaceURI===jhe?t.createElement(e):t.createElementNS(n,e)}}function pBn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Vxt(e){var t=NV(e);return(t.local?pBn:fBn)(t)}function hBn(){}function m1e(e){return e==null?hBn:function(){return this.querySelector(e)}}function mBn(e){typeof e!="function"&&(e=m1e(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 Up(r,this._parents)}function gBn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function vBn(){return[]}function Hxt(e){return e==null?vBn:function(){return this.querySelectorAll(e)}}function yBn(e){return function(){return gBn(e.apply(this,arguments))}}function bBn(e){typeof e=="function"?e=yBn(e):e=Hxt(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 Up(r,s)}function Wxt(e){return function(){return this.matches(e)}}function Zxt(e){return function(t){return t.matches(e)}}var xBn=Array.prototype.find;function wBn(e){return function(){return xBn.call(this.children,e)}}function SBn(){return this.firstElementChild}function kBn(e){return this.select(e==null?SBn:wBn(typeof e=="function"?e:Zxt(e)))}var OBn=Array.prototype.filter;function _Bn(){return Array.from(this.children)}function CBn(e){return function(){return OBn.call(this.children,e)}}function EBn(e){return this.selectAll(e==null?_Bn:CBn(typeof e=="function"?e:Zxt(e)))}function jBn(e){typeof e!="function"&&(e=Wxt(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 Up(r,this._parents)}function Gxt(e){return new Array(e.length)}function TBn(){return new Up(this._enter||this._groups.map(Gxt),this._parents)}function N7(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}N7.prototype={constructor:N7,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 NBn(e){return function(){return e}}function IBn(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 N7(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function ABn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new N7(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function RBn(e){return e.__data__}function PBn(e,t){if(!arguments.length)return Array.from(this,RBn);var n=t?ABn:IBn,r=this._parents,s=this._groups;typeof e!="function"&&(e=NBn(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],p=f.length,h=$Bn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var S=0,w=0,k,_;S<m;++S)if(k=v[S]){for(S>=w&&(w=S+1);!(_=y[w])&&++w<m;);k._next=_||null}}return i=new Up(i,r),i._enter=l,i._exit=c,i}function $Bn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function MBn(){return new Up(this._exit||this._groups.map(Gxt),this._parents)}function DBn(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 LBn(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,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Up(l,this._parents)}function FBn(){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 zBn(e){e||(e=BBn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}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 Up(s,this._parents).order()}function BBn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function UBn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function qBn(){return Array.from(this)}function VBn(){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 HBn(){let e=0;for(const t of this)++e;return e}function WBn(){return!this.node()}function ZBn(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 GBn(e){return function(){this.removeAttribute(e)}}function QBn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function YBn(e,t){return function(){this.setAttribute(e,t)}}function XBn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function KBn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function JBn(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 eUn(e,t){var n=NV(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?QBn:GBn:typeof t=="function"?n.local?JBn:KBn:n.local?XBn:YBn)(n,t))}function Qxt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function tUn(e){return function(){this.style.removeProperty(e)}}function nUn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function rUn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function sUn(e,t,n){return arguments.length>1?this.each((t==null?tUn:typeof t=="function"?rUn:nUn)(e,t,n??"")):xT(this.node(),e)}function xT(e,t){return e.style.getPropertyValue(t)||Qxt(e).getComputedStyle(e,null).getPropertyValue(t)}function aUn(e){return function(){delete this[e]}}function iUn(e,t){return function(){this[e]=t}}function oUn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function lUn(e,t){return arguments.length>1?this.each((t==null?aUn:typeof t=="function"?oUn:iUn)(e,t)):this.node()[e]}function Yxt(e){return e.trim().split(/^|\s+/)}function g1e(e){return e.classList||new Xxt(e)}function Xxt(e){this._node=e,this._names=Yxt(e.getAttribute("class")||"")}Xxt.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 Kxt(e,t){for(var n=g1e(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Jxt(e,t){for(var n=g1e(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function cUn(e){return function(){Kxt(this,e)}}function uUn(e){return function(){Jxt(this,e)}}function dUn(e,t){return function(){(t.apply(this,arguments)?Kxt:Jxt)(this,e)}}function fUn(e,t){var n=Yxt(e+"");if(arguments.length<2){for(var r=g1e(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?dUn:t?cUn:uUn)(n,t))}function pUn(){this.textContent=""}function hUn(e){return function(){this.textContent=e}}function mUn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function gUn(e){return arguments.length?this.each(e==null?pUn:(typeof e=="function"?mUn:hUn)(e)):this.node().textContent}function vUn(){this.innerHTML=""}function yUn(e){return function(){this.innerHTML=e}}function bUn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function xUn(e){return arguments.length?this.each(e==null?vUn:(typeof e=="function"?bUn:yUn)(e)):this.node().innerHTML}function wUn(){this.nextSibling&&this.parentNode.appendChild(this)}function SUn(){return this.each(wUn)}function kUn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function OUn(){return this.each(kUn)}function _Un(e){var t=typeof e=="function"?e:Vxt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function CUn(){return null}function EUn(e,t){var n=typeof e=="function"?e:Vxt(e),r=t==null?CUn:typeof t=="function"?t:m1e(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function jUn(){var e=this.parentNode;e&&e.removeChild(this)}function TUn(){return this.each(jUn)}function NUn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function IUn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function AUn(e){return this.select(e?IUn:NUn)}function RUn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function PUn(e){return function(t){e.call(this,t,this.__data__)}}function $Un(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 MUn(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 DUn(e,t,n){return function(){var r=this.__on,s,a=PUn(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 LUn(e,t,n){var r=$Un(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?DUn:MUn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function e0t(e,t,n){var r=Qxt(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 FUn(e,t){return function(){return e0t(this,e,t)}}function zUn(e,t){return function(){return e0t(this,e,t.apply(this,arguments))}}function BUn(e,t){return this.each((typeof t=="function"?zUn:FUn)(e,t))}function*UUn(){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 t0t=[null];function Up(e,t){this._groups=e,this._parents=t}function f3(){return new Up([[document.documentElement]],t0t)}function qUn(){return this}Up.prototype=f3.prototype={constructor:Up,select:mBn,selectAll:bBn,selectChild:kBn,selectChildren:EBn,filter:jBn,data:PBn,enter:TBn,exit:MBn,join:DBn,merge:LBn,selection:qUn,order:FBn,sort:zBn,call:UBn,nodes:qBn,node:VBn,size:HBn,empty:WBn,each:ZBn,attr:eUn,style:sUn,property:lUn,classed:fUn,text:gUn,html:xUn,raise:SUn,lower:OUn,append:_Un,insert:EUn,remove:TUn,clone:AUn,datum:RUn,on:LUn,dispatch:BUn,[Symbol.iterator]:UUn};function gp(e){return typeof e=="string"?new Up([[document.querySelector(e)]],[document.documentElement]):new Up([[e]],t0t)}function VUn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function eg(e,t){if(e=VUn(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 HUn={passive:!1},K$={capture:!0,passive:!1};function GJ(e){e.stopImmediatePropagation()}function kj(e){e.preventDefault(),e.stopImmediatePropagation()}function n0t(e){var t=e.document.documentElement,n=gp(e).on("dragstart.drag",kj,K$);"onselectstart"in t?n.on("selectstart.drag",kj,K$):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function r0t(e,t){var n=e.document.documentElement,r=gp(e).on("dragstart.drag",null);t&&(r.on("click.drag",kj,K$),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 S6=e=>()=>e;function The(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}})}The.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function WUn(e){return!e.ctrlKey&&!e.button}function ZUn(){return this.parentNode}function GUn(e,t){return t??{x:e.x,y:e.y}}function QUn(){return navigator.maxTouchPoints||"ontouchstart"in this}function s0t(){var e=WUn,t=ZUn,n=GUn,r=QUn,s={},a=TV("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,HUn).on("touchend.drag touchcancel.drag",S).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=w(this,t.call(this,k,_),k,_,"mouse");C&&(gp(k.view).on("mousemove.drag",m,K$).on("mouseup.drag",v,K$),n0t(k.view),GJ(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(kj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){gp(k.view).on("mousemove.drag mouseup.drag",null),r0t(k.view,u),kj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,j=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=w(this,j,k,_,C[N].identifier,C[N]))&&(GJ(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,j,E;for(j=0;j<C;++j)(E=s[_[j].identifier])&&(kj(k),E("drag",k,_[j]))}function S(k){var _=k.changedTouches,C=_.length,j,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),j=0;j<C;++j)(E=s[_[j].identifier])&&(GJ(k),E("end",k,_[j]))}function w(k,_,C,j,E,N){var I=a.copy(),A=eg(N||C,_),P,F,D;if((D=n.call(k,new The("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),j))!=null)return P=D.x-A[0]||0,F=D.y-A[1]||0,function V(H,L,z){var B=A,M;switch(H){case"start":s[E]=V,M=i++;break;case"end":delete s[E],--i;case"drag":A=eg(z||L,_),M=i;break}I.call(H,k,new The(H,{sourceEvent:L,subject:D,target:p,identifier:E,active:M,x:A[0]+P,y:A[1]+F,dx:A[0]-B[0],dy:A[1]-B[1],dispatch:I}),j)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:S6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:S6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:S6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:S6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function v1e(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function a0t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function p3(){}var J$=.7,I7=1/J$,Oj="\\s*([+-]?\\d+)\\s*",eM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ey="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",YUn=/^#([0-9a-f]{3,8})$/,XUn=new RegExp(`^rgb\\(${Oj},${Oj},${Oj}\\)$`),KUn=new RegExp(`^rgb\\(${ey},${ey},${ey}\\)$`),JUn=new RegExp(`^rgba\\(${Oj},${Oj},${Oj},${eM}\\)$`),eqn=new RegExp(`^rgba\\(${ey},${ey},${ey},${eM}\\)$`),tqn=new RegExp(`^hsl\\(${eM},${ey},${ey}\\)$`),nqn=new RegExp(`^hsla\\(${eM},${ey},${ey},${eM}\\)$`),j9e={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};v1e(p3,RO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:T9e,formatHex:T9e,formatHex8:rqn,formatHsl:sqn,formatRgb:N9e,toString:N9e});function T9e(){return this.rgb().formatHex()}function rqn(){return this.rgb().formatHex8()}function sqn(){return i0t(this).formatHsl()}function N9e(){return this.rgb().formatRgb()}function RO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=YUn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?I9e(t):n===3?new nf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?k6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?k6(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=XUn.exec(e))?new nf(t[1],t[2],t[3],1):(t=KUn.exec(e))?new nf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=JUn.exec(e))?k6(t[1],t[2],t[3],t[4]):(t=eqn.exec(e))?k6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=tqn.exec(e))?P9e(t[1],t[2]/100,t[3]/100,1):(t=nqn.exec(e))?P9e(t[1],t[2]/100,t[3]/100,t[4]):j9e.hasOwnProperty(e)?I9e(j9e[e]):e==="transparent"?new nf(NaN,NaN,NaN,0):null}function I9e(e){return new nf(e>>16&255,e>>8&255,e&255,1)}function k6(e,t,n,r){return r<=0&&(e=t=n=NaN),new nf(e,t,n,r)}function aqn(e){return e instanceof p3||(e=RO(e)),e?(e=e.rgb(),new nf(e.r,e.g,e.b,e.opacity)):new nf}function Nhe(e,t,n,r){return arguments.length===1?aqn(e):new nf(e,t,n,r??1)}function nf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}v1e(nf,Nhe,a0t(p3,{brighter(e){return e=e==null?I7:Math.pow(I7,e),new nf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?J$:Math.pow(J$,e),new nf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new nf(Hk(this.r),Hk(this.g),Hk(this.b),A7(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:A9e,formatHex:A9e,formatHex8:iqn,formatRgb:R9e,toString:R9e}));function A9e(){return`#${Tk(this.r)}${Tk(this.g)}${Tk(this.b)}`}function iqn(){return`#${Tk(this.r)}${Tk(this.g)}${Tk(this.b)}${Tk((isNaN(this.opacity)?1:this.opacity)*255)}`}function R9e(){const e=A7(this.opacity);return`${e===1?"rgb(":"rgba("}${Hk(this.r)}, ${Hk(this.g)}, ${Hk(this.b)}${e===1?")":`, ${e})`}`}function A7(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Hk(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tk(e){return e=Hk(e),(e<16?"0":"")+e.toString(16)}function P9e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ig(e,t,n,r)}function i0t(e){if(e instanceof ig)return new ig(e.h,e.s,e.l,e.opacity);if(e instanceof p3||(e=RO(e)),!e)return new ig;if(e instanceof ig)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 ig(i,l,c,e.opacity)}function oqn(e,t,n,r){return arguments.length===1?i0t(e):new ig(e,t,n,r??1)}function ig(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}v1e(ig,oqn,a0t(p3,{brighter(e){return e=e==null?I7:Math.pow(I7,e),new ig(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?J$:Math.pow(J$,e),new ig(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new nf(QJ(e>=240?e-240:e+120,s,r),QJ(e,s,r),QJ(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ig($9e(this.h),O6(this.s),O6(this.l),A7(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=A7(this.opacity);return`${e===1?"hsl(":"hsla("}${$9e(this.h)}, ${O6(this.s)*100}%, ${O6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function $9e(e){return e=(e||0)%360,e<0?e+360:e}function O6(e){return Math.max(0,Math.min(1,e||0))}function QJ(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 y1e=e=>()=>e;function lqn(e,t){return function(n){return e+n*t}}function cqn(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 uqn(e){return(e=+e)==1?o0t:function(t,n){return n-t?cqn(t,n,e):y1e(isNaN(t)?n:t)}}function o0t(e,t){var n=t-e;return n?lqn(e,n):y1e(isNaN(e)?t:e)}const R7=(function e(t){var n=uqn(t);function r(s,a){var i=n((s=Nhe(s)).r,(a=Nhe(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=o0t(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 dqn(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 fqn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function pqn(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]=sx(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 hqn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ng(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function mqn(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]=sx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Ihe=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,YJ=new RegExp(Ihe.source,"g");function gqn(e){return function(){return e}}function vqn(e){return function(t){return e(t)+""}}function l0t(e,t){var n=Ihe.lastIndex=YJ.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Ihe.exec(e))&&(s=YJ.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:ng(r,s)})),n=YJ.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?vqn(c[0].x):gqn(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 sx(e,t){var n=typeof t,r;return t==null||n==="boolean"?y1e(t):(n==="number"?ng:n==="string"?(r=RO(t))?(t=r,R7):l0t:t instanceof RO?R7:t instanceof Date?hqn:fqn(t)?dqn:Array.isArray(t)?pqn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?mqn:ng)(e,t)}function b1e(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var M9e=180/Math.PI,Ahe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function c0t(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)*M9e,skewX:Math.atan(c)*M9e,scaleX:i,scaleY:l}}var _6;function yqn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ahe:c0t(t.a,t.b,t.c,t.d,t.e,t.f)}function bqn(e){return e==null||(_6||(_6=document.createElementNS("http://www.w3.org/2000/svg","g")),_6.setAttribute("transform",e),!(e=_6.transform.baseVal.consolidate()))?Ahe:(e=e.matrix,c0t(e.a,e.b,e.c,e.d,e.e,e.f))}function u0t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ng(u,f)},{i:v-2,x:ng(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ng(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ng(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ng(u,f)},{i:v-2,x:ng(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var xqn=u0t(yqn,"px, ","px)","deg)"),wqn=u0t(bqn,", ",")",")"),Sqn=1e-12;function D9e(e){return((e=Math.exp(e))+1/e)/2}function kqn(e){return((e=Math.exp(e))-1/e)/2}function Oqn(e){return((e=Math.exp(2*e))-1)/(e+1)}const KF=(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],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<Sqn)b=Math.log(p/u)/t,y=function(j){return[l+j*h,c+j*m,u*Math.exp(t*j*b)]};else{var S=Math.sqrt(v),w=(p*p-u*u+r*v)/(2*u*n*S),k=(p*p-u*u-r*v)/(2*p*n*S),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(j){var E=j*b,N=D9e(_),I=u/(n*S)*(N*Oqn(t*E+_)-kqn(_));return[l+I*h,c+I*m,u*N/D9e(t*E+_)]}}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 _qn(e,t){t===void 0&&(t=e,e=sx);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 wT=0,o2=0,ZA=0,d0t=1e3,P7,l2,$7=0,PO=0,IV=0,tM=typeof performance=="object"&&performance.now?performance:Date,f0t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function x1e(){return PO||(f0t(Cqn),PO=tM.now()+IV)}function Cqn(){PO=0}function M7(){this._call=this._time=this._next=null}M7.prototype=p0t.prototype={constructor:M7,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?x1e():+n)+(t==null?0:+t),!this._next&&l2!==this&&(l2?l2._next=this:P7=this,l2=this),this._call=e,this._time=n,Rhe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Rhe())}};function p0t(e,t,n){var r=new M7;return r.restart(e,t,n),r}function Eqn(){x1e(),++wT;for(var e=P7,t;e;)(t=PO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--wT}function L9e(){PO=($7=tM.now())+IV,wT=o2=0;try{Eqn()}finally{wT=0,Tqn(),PO=0}}function jqn(){var e=tM.now(),t=e-$7;t>d0t&&(IV-=t,$7=e)}function Tqn(){for(var e,t=P7,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:P7=n);l2=e,Rhe(r)}function Rhe(e){if(!wT){o2&&(o2=clearTimeout(o2));var t=e-PO;t>24?(e<1/0&&(o2=setTimeout(L9e,e-tM.now()-IV)),ZA&&(ZA=clearInterval(ZA))):(ZA||($7=tM.now(),ZA=setInterval(jqn,d0t)),wT=1,f0t(L9e))}}function F9e(e,t,n){var r=new M7;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var Nqn=TV("start","end","cancel","interrupt"),Iqn=[],h0t=0,z9e=1,Phe=2,JF=3,B9e=4,$he=5,e8=6;function AV(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Aqn(e,n,{name:t,index:r,group:s,on:Nqn,tween:Iqn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:h0t})}function w1e(e,t){var n=Bg(e,t);if(n.state>h0t)throw new Error("too late; already scheduled");return n}function Dy(e,t){var n=Bg(e,t);if(n.state>JF)throw new Error("too late; already running");return n}function Bg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Aqn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=p0t(a,0,n.time);function a(u){n.state=z9e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==z9e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===JF)return F9e(i);h.state===B9e?(h.state=e8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=e8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(F9e(function(){n.state===JF&&(n.state=B9e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Phe,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Phe){for(n.state=JF,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);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=$he,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===$he&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=e8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function t8(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>Phe&&r.state<$he,r.state=e8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function Rqn(e){return this.each(function(){t8(this,e)})}function Pqn(e,t){var n,r;return function(){var s=Dy(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 $qn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Dy(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 Mqn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Bg(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?Pqn:$qn)(n,e,t))}function S1e(e,t,n){var r=e._id;return e.each(function(){var s=Dy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Bg(s,r).value[t]}}function m0t(e,t){var n;return(typeof t=="number"?ng:t instanceof RO?R7:(n=RO(t))?(t=n,R7):l0t)(e,t)}function Dqn(e){return function(){this.removeAttribute(e)}}function Lqn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Fqn(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 zqn(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 Bqn(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 Uqn(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 qqn(e,t){var n=NV(e),r=n==="transform"?wqn:m0t;return this.attrTween(e,typeof t=="function"?(n.local?Uqn:Bqn)(n,r,S1e(this,"attr."+e,t)):t==null?(n.local?Lqn:Dqn)(n):(n.local?zqn:Fqn)(n,r,t))}function Vqn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Hqn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Wqn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&Hqn(e,a)),n}return s._value=t,s}function Zqn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&Vqn(e,a)),n}return s._value=t,s}function Gqn(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=NV(e);return this.tween(n,(r.local?Wqn:Zqn)(r,t))}function Qqn(e,t){return function(){w1e(this,e).delay=+t.apply(this,arguments)}}function Yqn(e,t){return t=+t,function(){w1e(this,e).delay=t}}function Xqn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Qqn:Yqn)(t,e)):Bg(this.node(),t).delay}function Kqn(e,t){return function(){Dy(this,e).duration=+t.apply(this,arguments)}}function Jqn(e,t){return t=+t,function(){Dy(this,e).duration=t}}function eVn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Kqn:Jqn)(t,e)):Bg(this.node(),t).duration}function tVn(e,t){if(typeof t!="function")throw new Error;return function(){Dy(this,e).ease=t}}function nVn(e){var t=this._id;return arguments.length?this.each(tVn(t,e)):Bg(this.node(),t).ease}function rVn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Dy(this,e).ease=n}}function sVn(e){if(typeof e!="function")throw new Error;return this.each(rVn(this._id,e))}function aVn(e){typeof e!="function"&&(e=Wxt(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 Ox(r,this._parents,this._name,this._id)}function iVn(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),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Ox(i,this._parents,this._name,this._id)}function oVn(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 lVn(e,t,n){var r,s,a=oVn(t)?w1e:Dy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function cVn(e,t){var n=this._id;return arguments.length<2?Bg(this.node(),n).on.on(e):this.each(lVn(n,e,t))}function uVn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function dVn(){return this.on("end.remove",uVn(this._id))}function fVn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=m1e(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,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,AV(u[p],t,n,p,u,Bg(d,n)));return new Ox(a,this._parents,t,n)}function pVn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Hxt(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 p=e.call(d,d.__data__,f,c),h,m=Bg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&AV(h,t,n,v,p,m);a.push(p),i.push(d)}return new Ox(a,i,t,n)}var hVn=f3.prototype.constructor;function mVn(){return new hVn(this._groups,this._parents)}function gVn(e,t){var n,r,s;return function(){var a=xT(this,e),i=(this.style.removeProperty(e),xT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function g0t(e){return function(){this.style.removeProperty(e)}}function vVn(e,t,n){var r,s=n+"",a;return function(){var i=xT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function yVn(e,t,n){var r,s,a;return function(){var i=xT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),xT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function bVn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Dy(this,e),u=c.on,d=c.value[a]==null?l||(l=g0t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function xVn(e,t,n){var r=(e+="")=="transform"?xqn:m0t;return t==null?this.styleTween(e,gVn(e,r)).on("end.style."+e,g0t(e)):typeof t=="function"?this.styleTween(e,yVn(e,r,S1e(this,"style."+e,t))).each(bVn(this._id,e)):this.styleTween(e,vVn(e,r,t),n).on("end.style."+e,null)}function wVn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function SVn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&wVn(e,i,n)),r}return a._value=t,a}function kVn(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,SVn(e,t,n??""))}function OVn(e){return function(){this.textContent=e}}function _Vn(e){return function(){var t=e(this);this.textContent=t??""}}function CVn(e){return this.tween("text",typeof e=="function"?_Vn(S1e(this,"text",e)):OVn(e==null?"":e+""))}function EVn(e){return function(t){this.textContent=e.call(this,t)}}function jVn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&EVn(s)),t}return r._value=e,r}function TVn(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,jVn(e))}function NVn(){for(var e=this._name,t=this._id,n=v0t(),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=Bg(c,t);AV(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Ox(r,this._parents,e,n)}function IVn(){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=Dy(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 AVn=0;function Ox(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function v0t(){return++AVn}var gb=f3.prototype;Ox.prototype={constructor:Ox,select:fVn,selectAll:pVn,selectChild:gb.selectChild,selectChildren:gb.selectChildren,filter:aVn,merge:iVn,selection:mVn,transition:NVn,call:gb.call,nodes:gb.nodes,node:gb.node,size:gb.size,empty:gb.empty,each:gb.each,on:cVn,attr:qqn,attrTween:Gqn,style:xVn,styleTween:kVn,text:CVn,textTween:TVn,remove:dVn,tween:Mqn,delay:Xqn,duration:eVn,ease:nVn,easeVarying:sVn,end:IVn,[Symbol.iterator]:gb[Symbol.iterator]};function RVn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var PVn={time:null,delay:0,duration:250,ease:RVn};function $Vn(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 MVn(e){var t,n;e instanceof Ox?(t=e._id,e=e._name):(t=v0t(),(n=PVn).time=x1e(),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])&&AV(c,e,t,u,i,n||$Vn(c,t));return new Ox(r,this._parents,e,t)}f3.prototype.interrupt=Rqn;f3.prototype.transition=MVn;const C6=e=>()=>e;function DVn(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 Wb(e,t,n){this.k=e,this.x=t,this.y=n}Wb.prototype={constructor:Wb,scale:function(e){return e===1?this:new Wb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Wb(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 RV=new Wb(1,0,0);y0t.prototype=Wb.prototype;function y0t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return RV;return e.__zoom}function XJ(e){e.stopImmediatePropagation()}function GA(e){e.preventDefault(),e.stopImmediatePropagation()}function LVn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function FVn(){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 U9e(){return this.__zoom||RV}function zVn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function BVn(){return navigator.maxTouchPoints||"ontouchstart"in this}function UVn(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 b0t(){var e=LVn,t=FVn,n=UVn,r=zVn,s=BVn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=KF,u=TV("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",U9e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,V,H,L){var z=D.selection?D.selection():D;z.property("__zoom",U9e),D!==z?_(D,V,H,L):z.interrupt().each(function(){C(this,arguments).event(L).start().zoom(null,typeof V=="function"?V.apply(this,arguments):V).end()})},b.scaleBy=function(D,V,H,L){b.scaleTo(D,function(){var z=this.__zoom.k,B=typeof V=="function"?V.apply(this,arguments):V;return z*B},H,L)},b.scaleTo=function(D,V,H,L){b.transform(D,function(){var z=t.apply(this,arguments),B=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=B.invert(M),q=typeof V=="function"?V.apply(this,arguments):V;return n(w(S(B,q),M,G),z,i)},H,L)},b.translateBy=function(D,V,H,L){b.transform(D,function(){return n(this.__zoom.translate(typeof V=="function"?V.apply(this,arguments):V,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,L)},b.translateTo=function(D,V,H,L,z){b.transform(D,function(){var B=t.apply(this,arguments),M=this.__zoom,G=L==null?k(B):typeof L=="function"?L.apply(this,arguments):L;return n(RV.translate(G[0],G[1]).scale(M.k).translate(typeof V=="function"?-V.apply(this,arguments):-V,typeof H=="function"?-H.apply(this,arguments):-H),B,i)},L,z)};function S(D,V){return V=Math.max(a[0],Math.min(a[1],V)),V===D.k?D:new Wb(V,D.x,D.y)}function w(D,V,H){var L=V[0]-H[0]*D.k,z=V[1]-H[1]*D.k;return L===D.x&&z===D.y?D:new Wb(D.k,L,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,V,H,L){D.on("start.zoom",function(){C(this,arguments).event(L).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(L).end()}).tween("zoom",function(){var z=this,B=arguments,M=C(z,B).event(L),G=t.apply(z,B),q=H==null?k(G):typeof H=="function"?H.apply(z,B):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof V=="function"?V.apply(z,B):V,X=c(U.invert(q).concat($/U.k),Z.invert(q).concat($/Z.k));return function(te){if(te===1)te=Z;else{var J=X(te),ee=$/J[2];te=new Wb(ee,q[0]-J[0]*ee,q[1]-J[1]*ee)}M.zoom(null,te)}})}function C(D,V,H){return!H&&D.__zooming||new j(D,V)}function j(D,V){this.that=D,this.args=V,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,V),this.taps=0}j.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,V){return this.mouse&&D!=="mouse"&&(this.mouse[1]=V.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=V.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=V.invert(this.touch1[0])),this.that.__zoom=V,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var V=gp(this.that).datum();u.call(D,this.that,new DVn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),V)}};function E(D,...V){if(!e.apply(this,arguments))return;var H=C(this,V).event(D),L=this.__zoom,z=Math.max(a[0],Math.min(a[1],L.k*Math.pow(2,r.apply(this,arguments)))),B=eg(D);if(H.wheel)(H.mouse[0][0]!==B[0]||H.mouse[0][1]!==B[1])&&(H.mouse[1]=L.invert(H.mouse[0]=B)),clearTimeout(H.wheel);else{if(L.k===z)return;H.mouse=[B,L.invert(B)],t8(this),H.start()}GA(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(S(L,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...V){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,L=C(this,V,!0).event(D),z=gp(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),B=eg(D,H),M=D.clientX,G=D.clientY;n0t(D.view),XJ(D),L.mouse=[B,this.__zoom.invert(B)],t8(this),L.start();function q(U){if(GA(U),!L.moved){var Z=U.clientX-M,X=U.clientY-G;L.moved=Z*Z+X*X>v}L.event(U).zoom("mouse",n(w(L.that.__zoom,L.mouse[0]=eg(U,H),L.mouse[1]),L.extent,i))}function $(U){z.on("mousemove.zoom mouseup.zoom",null),r0t(U.view,L.moved),GA(U),L.event(U).end()}}function I(D,...V){if(e.apply(this,arguments)){var H=this.__zoom,L=eg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(L),B=H.k*(D.shiftKey?.5:2),M=n(w(S(H,B),L,z),t.apply(this,V),i);GA(D),l>0?gp(this).transition().duration(l).call(_,M,L,D):gp(this).call(b.transform,M,L,D)}}function A(D,...V){if(e.apply(this,arguments)){var H=D.touches,L=H.length,z=C(this,V,D.changedTouches.length===L).event(D),B,M,G,q;for(XJ(D),M=0;M<L;++M)G=H[M],q=eg(G,this),q=[q,this.__zoom.invert(q),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==q[2]&&(z.touch1=q,z.taps=0):(z.touch0=q,B=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),B&&(z.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),t8(this),z.start())}}function P(D,...V){if(this.__zooming){var H=C(this,V).event(D),L=D.changedTouches,z=L.length,B,M,G,q;for(GA(D),B=0;B<z;++B)M=L[B],G=eg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],X=H.touch1[1],te=(te=Z[0]-$[0])*te+(te=Z[1]-$[1])*te,J=(J=X[0]-U[0])*J+(J=X[1]-U[1])*J;M=S(M,Math.sqrt(te/J)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(U[0]+X[0])/2,(U[1]+X[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(w(M,G,q),H.extent,i))}}function F(D,...V){if(this.__zooming){var H=C(this,V).event(D),L=D.changedTouches,z=L.length,B,M;for(XJ(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),B=0;B<z;++B)M=L[B],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=eg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=gp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:C6(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:C6(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:C6(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:C6([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const my={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."},nM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],x0t=["Enter"," ","Escape"],w0t={"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 ST;(function(e){e.Strict="strict",e.Loose="loose"})(ST||(ST={}));var Wk;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Wk||(Wk={}));var rM;(function(e){e.Partial="partial",e.Full="full"})(rM||(rM={}));const S0t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var aw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(aw||(aw={}));var sM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(sM||(sM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const q9e={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function k0t(e){return e===null?null:e?"valid":"invalid"}const O0t=e=>"id"in e&&"source"in e&&"target"in e,qVn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),k1e=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),h3=(e,t=[0,0])=>{const{width:n,height:r}=Zx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},VVn=(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):k1e(s)?s:t.nodeLookup.get(s.id));const l=i?D7(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return PV(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $V(n)},m3=(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=PV(n,D7(s)),r=!0)}),r?$V(n):{x:0,y:0,width:0,height:0}},O1e=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...v3(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:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=aM(l,OT(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},HVn=(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 WVn(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 ZVn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=WVn(e,i),c=m3(l),u=_1e(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 _0t({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",my.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&_T(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=_T(f)?$O(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",my.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function GVn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=HVn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);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 kT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),$O=(e={x:0,y:0},t,n)=>({x:kT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:kT(e.y,t[0][1],t[1][1]-(n?.height??0))});function C0t(e,t,n){const{width:r,height:s}=Zx(n),{x:a,y:i}=n.internals.positionAbsolute;return $O(e,[[a,i],[a+r,i+s]],t)}const V9e=(e,t,n)=>e<t?kT(Math.abs(e-t),1,t)/t:e>n?-kT(Math.abs(e-n),1,t)/t:0,E0t=(e,t,n=15,r=40)=>{const s=V9e(e.x,r,t.width-r)*n,a=V9e(e.y,r,t.height-r)*n;return[s,a]},PV=(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)}),Mhe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),$V=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),OT=(e,t=[0,0])=>{const{x:n,y:r}=k1e(e)?e.internals.positionAbsolute:h3(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}},D7=(e,t=[0,0])=>{const{x:n,y:r}=k1e(e)?e.internals.positionAbsolute:h3(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)}},j0t=(e,t)=>$V(PV(Mhe(e),Mhe(t))),aM=(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)},H9e=e=>fg(e.width)&&fg(e.height)&&fg(e.x)&&fg(e.y),fg=e=>!isNaN(e)&&isFinite(e),QVn=(e,t)=>{},g3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),v3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?g3(l,i):l},L7=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function zC(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 YVn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=zC(e,n),s=zC(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=zC(e.top??e.y??0,n),s=zC(e.bottom??e.y??0,n),a=zC(e.left??e.x??0,t),i=zC(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 XVn(e,t,n,r,s,a){const{x:i,y:l}=L7(e,[t,n,r]),{x:c,y:u}=L7({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 _1e=(e,t,n,r,s,a)=>{const i=YVn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=kT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=XVn(e,h,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:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},iM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function _T(e){return e!=null&&e!=="parent"}function Zx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function T0t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function N0t(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 W9e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function KVn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function JVn(e){return{...w0t,...e||{}}}function U2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=pg(e),l=v3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?g3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const C1e=e=>({width:e.offsetWidth,height:e.offsetHeight}),I0t=e=>e?.getRootNode?.()||window?.document,eHn=["INPUT","SELECT","TEXTAREA"];function A0t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:eHn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const R0t=e=>"clientX"in e,pg=(e,t)=>{const n=R0t(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)}},Z9e=(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,...C1e(i)}})};function P0t({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 E6(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function G9e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-E6(t-r,a),n];case nr.Right:return[t+E6(r-t,a),n];case nr.Top:return[t,n-E6(n-s,a)];case nr.Bottom:return[t,n+E6(s-n,a)]}}function E1e({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=G9e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=G9e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=P0t({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,p,h,m]}function $0t({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 tHn({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 nHn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=PV(D7(e),D7(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 aM(i,$V(a))>0}const rHn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,sHn=(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)),aHn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||rHn;let s;return O0t(e)?s={...e}:s={...e,id:r(e)},sHn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function M0t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=$0t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const Q9e={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},iHn=({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},Y9e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function oHn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=Q9e[t],c=Q9e[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=iHn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},S={x:0,y:0},[,,w,k]=$0t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const V=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*V:S[p]=(d[p]>n[p]?-1:1)*V}}if(t!==r){const D=p==="x"?"y":"x",V=l[p]===c[D],H=u[D]>d[D],L=u[D]<d[D];(l[p]===1&&(!V&&H||V&&L)||l[p]!==1&&(!V&&L||V&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+S.x,y:d.y+S.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),F=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=F?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+S.x,y:d.y+S.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,w,k]}function lHn(e,t,n,r){const s=Math.min(Y9e(e,t)/2,Y9e(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 Dhe({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,p,h,m,v]=oHn({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+=lHn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function X9e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function cHn(e){const{sourceNode:t,targetNode:n}=e;if(!X9e(t)||!X9e(n))return null;const r=t.internals.handleBounds||K9e(t.handles),s=n.internals.handleBounds||K9e(n.handles),a=J9e(r?.source??[],e.sourceHandle),i=J9e(e.connectionMode===ST.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",my.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=MO(t,a,l),d=MO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function K9e(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 MO(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??Zx(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 J9e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Lhe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function uHn(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=Lhe(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 D0t=1e3,dHn=10,j1e={nodeOrigin:[0,0],nodeExtent:nM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},fHn={...j1e,checkEquality:!0};function T1e(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function pHn(e,t,n){const r=T1e(j1e,n);for(const s of e.values())if(s.parentId)I1e(s,e,t,r);else{const a=h3(s,r.nodeOrigin),i=_T(s.extent)?s.extent:r.nodeExtent,l=$O(a,i,Zx(s));s.internals.positionAbsolute=l}}function hHn(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 N1e(e){return e==="manual"}function Fhe(e,t,n,r={}){const s=T1e(fHn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!N1e(s.zIndexMode)?D0t: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 p=h3(d,s.nodeOrigin),h=_T(d.extent)?d.extent:s.nodeExtent,m=$O(p,h,Zx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:hHn(d,f),z:L0t(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&&I1e(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function mHn(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 I1e(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=T1e(j1e,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}mHn(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*dHn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!N1e(c)?D0t:0,{x:p,y:h,z:m}=gHn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function L0t(e,t,n){const r=fg(e.zIndex)?e.zIndex:0;return N1e(n)?r:r+(e.selected?t:0)}function gHn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Zx(e),u=h3(e,n),d=_T(e.extent)?$O(u,e.extent,c):u;let f=$O({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=C0t(f,c,t));const p=L0t(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function A1e(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??OT(l),u=j0t(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=Zx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=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];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(S=>{e.some(w=>w.id===S.id)||s.push({id:S.id,type:"position",position:{x:S.position.x+p,y:S.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function vHn(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),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=C1e(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const S=h.nodeElement.getBoundingClientRect(),w=_T(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=C0t(k,v,t.get(m.parentId)):w&&(k=$O(k,w,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:Z9e("source",h.nodeElement,S,f,m.id),target:Z9e("target",h.nodeElement,S,f,m.id)}}};t.set(m.id,_),m.parentId&&I1e(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:OT(_,s)}))}}if(p.length>0){const h=A1e(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function yHn({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 eFe(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 F0t(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}`;eFe("source",c,d,e,s,i),eFe("target",c,u,e,a,l),t.set(r.id,r)}}function z0t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:z0t(n,t):!1}function tFe(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 bHn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!z0t(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 KJ({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 xHn({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=g3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function wHn({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,p=null,h=!1,m=!1,v=null;function y({noDragClassName:S,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:j=0}){p=gp(k);function E({x:P,y:F}){const{nodeLookup:D,nodeExtent:V,snapGrid:H,snapToGrid:L,nodeOrigin:z,onNodeDrag:B,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:P,y:F};let $=!1;const U=l.size>1,Z=U&&V?Mhe(m3(l)):null,X=U&&L?xHn({dragItems:l,snapGrid:H,x:P,y:F}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:P-J.distance.x,y:F-J.distance.y};L&&(ee=X?{x:Math.round(ee.x+X.x),y:Math.round(ee.y+X.y)}:g3(ee,H));let ae=null;if(U&&V&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,ue=ne.x-Z.x+V[0][0],pe=ne.x+J.measured.width-Z.x2+V[1][0],oe=ne.y-Z.y+V[0][1],ve=ne.y+J.measured.height-Z.y2+V[1][1];ae=[[ue,oe],[pe,ve]]}const{position:ce,positionAbsolute:Y}=_0t({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:ae||V,nodeOrigin:z,onError:G});$=$||J.position.x!==ce.x||J.position.y!==ce.y,J.position=ce,J.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||B||!C&&M))){const[te,J]=KJ({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,te,J),B?.(v,te,J),C||M?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:F,autoPanSpeed:D,autoPanOnNodeDrag:V}=t();if(!V){c=!1,cancelAnimationFrame(i);return}const[H,L]=E0t(u,d,D);(H!==0||L!==0)&&(a.x=(a.x??0)-H/P[2],a.y=(a.y??0)-L/P[2],await F({x:H,y:L})&&E(a)),i=requestAnimationFrame(N)}function I(P){const{nodeLookup:F,multiSelectionActive:D,nodesDraggable:V,transform:H,snapGrid:L,snapToGrid:z,selectNodesOnDrag:B,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!B||!_)&&!D&&C&&(F.get(C)?.selected||q()),_&&B&&C&&e?.(C);const $=U2(P.sourceEvent,{transform:H,snapGrid:L,snapToGrid:z,containerBounds:d});if(a=$,l=bHn(F,V,$,C),l.size>0&&(n||M||!C&&G)){const[U,Z]=KJ({nodeId:C,dragItems:l,nodeLookup:F});n?.(P.sourceEvent,l,U,Z),M?.(P.sourceEvent,U,Z),C||G?.(P.sourceEvent,Z)}}const A=s0t().clickDistance(j).on("start",P=>{const{domNode:F,nodeDragThreshold:D,transform:V,snapGrid:H,snapToGrid:L}=t();d=F?.getBoundingClientRect()||null,h=!1,m=!1,v=P.sourceEvent,D===0&&I(P),a=U2(P.sourceEvent,{transform:V,snapGrid:H,snapToGrid:L,containerBounds:d}),u=pg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:F,transform:D,snapGrid:V,snapToGrid:H,nodeDragThreshold:L,nodeLookup:z}=t(),B=U2(P.sourceEvent,{transform:D,snapGrid:V,snapToGrid:H,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&F&&f&&(c=!0,N()),!f){const M=pg(P.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>L&&I(P)}(a.x!==B.xSnapped||a.y!==B.ySnapped)&&l&&f&&(u=pg(P.sourceEvent,d),E(B))}}).on("end",P=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:F,updateNodePositions:D,onNodeDragStop:V,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||V||!C&&H){const[L,z]=KJ({nodeId:C,dragItems:l,nodeLookup:F,dragging:!1});s?.(P.sourceEvent,l,L,z),V?.(P.sourceEvent,L,z),C||H?.(P.sourceEvent,z)}}}).filter(P=>{const F=P.target;return!P.button&&(!S||!tFe(F,`.${S}`,k))&&(!w||tFe(F,w,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function SHn(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())aM(s,OT(a))>0&&r.push(a);return r}const kHn=250;function OHn(e,t,n,r){let s=[],a=1/0;const i=SHn(e,n,t+kHn);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}=MO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===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 B0t(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,...MO(i,c,c.position,!0)}:c}function U0t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function _Hn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const q0t=()=>!0;function CHn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=q0t,onReconnectEnd:S,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:j=1,handleDomNode:E}){const N=I0t(e.target);let I=0,A;const{x:P,y:F}=pg(e),D=U0t(a,E),V=l?.getBoundingClientRect();let H=!1;if(!V||!D)return;const L=B0t(s,D,r,c,t);if(!L)return;let z=pg(e,V),B=!1,M=null,G=!1,q=null;function $(){if(!d||!V)return;const[ce,Y]=E0t(z,V,C);p({x:ce,y:Y}),I=requestAnimationFrame($)}const U={...L,nodeId:s,type:D,position:L.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:MO(Z,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:q9e[U.position],toNode:null,pointer:z};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}j===0&&J();function ee(ce){if(!H){const{x:ve,y:ye}=pg(ce),Se=ve-P,Ne=ye-F;if(!(Se*Se+Ne*Ne>j*j))return;J()}if(!_()||!U){ae(ce);return}const Y=k();z=pg(ce,V),A=OHn(v3(z,Y,!1,[1,1]),n,c,U),B||($(),B=!0);const ne=V0t(ce,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=ne.handleDomNode,M=ne.connection,G=_Hn(!!A,ne.isValid);const ue=c.get(s),pe=ue?MO(ue,U,nr.Left,!0):te.from,oe={...te,from:pe,isValid:G,to:ne.toHandle&&G?L7({x:ne.toHandle.x,y:ne.toHandle.y},Y):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:q9e[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};w(oe),te=oe}function ae(ce){if(!("touches"in ce&&ce.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...ne}=te,ue={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ce,ue),a&&S?.(ce,ue)}h(),cancelAnimationFrame(I),B=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",ee),N.addEventListener("touchend",ae)}function V0t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=q0t,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=pg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const S=U0t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!w||!S)return b;const j={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=j;const N=_&&C&&(n===ST.Strict?f&&S==="source"||!f&&S==="target":w!==r||k!==s);b.isValid=N&&u(j),b.toHandle=B0t(w,S,k,d,n,!0)}return b}const zhe={onPointerDown:CHn,isValid:V0t};function EHn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=gp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&iM()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,j=k[2]*Math.pow(2,C*_);t.scaleTo(j)};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 _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const j=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*j,y:k[1]-C[1]*j},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},S=b0t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(S,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:eg}}const MV=e=>({x:e.x,y:e.y,zoom:e.k}),JJ=({x:e,y:t,zoom:n})=>RV.translate(e,t).scale(n),qE=(e,t)=>e.target.closest(`.${t}`),H0t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),jHn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,eee=(e,t=0,n=jHn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},W0t=e=>{const t=e.ctrlKey&&iM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function THn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(qE(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=eg(d),b=W0t(d),S=f*Math.pow(2,b);r.scaleTo(n,S,y,d);return}const p=d.deltaMode===1?20:1;let h=s===Wk.Vertical?0:d.deltaX*p,m=s===Wk.Horizontal?0:d.deltaY*p;!iM()&&d.shiftKey&&s!==Wk.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=MV(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 NHn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=qE(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function IHn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=MV(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 AHn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&H0t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,MV(a.transform))}}function RHn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&H0t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=MV(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function PHn({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 p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(qE(f,`${u}-flow__node`)||qE(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||qE(f,l)&&m||qE(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(!p&&!s&&!h&&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 $Hn({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=b0t().scaleExtent([t,n]).translateExtent(r),p=gp(e).call(f);S({x:s.x,y:s.y,zoom:kT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(W0t);function v(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).transform(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:F,userSelectionActive:D,panOnScroll:V,panOnDrag:H,panOnScrollMode:L,panOnScrollSpeed:z,preventScrolling:B,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:X,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=V&&!$&&!D;f.clickDistance(J?1/0:!fg(te)||te<0?0:te);const ae=ee?THn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:L,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):NHn({noWheelClassName:A,preventScrolling:B,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=IHn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ne=AHn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!F,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const ue=RHn({zoomPanValues:u,panOnDrag:H,panOnScroll:V,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const ce=PHn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:V,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:U,connectionInProgress:X});f.filter(ce),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function S(A,P,F){const D=JJ(A),V=f?.constrain()(D,P,F);return V&&await v(V),new Promise(H=>H(V))}async function w(A,P){const F=JJ(A);return await v(F,P),new Promise(D=>D(F))}function k(A){if(p){const P=JJ(A),F=p.property("__zoom");(F.k!==A.zoom||F.x!==A.x||F.y!==A.y)&&f?.transform(p,P,null,{sync:!0})}}function _(){const A=p?y0t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).scaleTo(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function j(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).scaleBy(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!fg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:S,getViewport:_,scaleTo:C,scaleBy:j,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var CT;(function(e){e.Line="line",e.Handle="handle"})(CT||(CT={}));function MHn({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 nFe(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 L0(e,t){return Math.max(0,t-e)}function F0(e,t){return Math.max(0,e-t)}function j6(e,t,n){return Math.max(0,t-e,e-n)}function rFe(e,t){return e?!t:t}function DHn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:S}=r,{x:w,y:k,width:_,height:C,aspectRatio:j}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),P=-a[0]*_,F=-a[1]*C;let D=j6(I,v,y),V=j6(A,b,S);if(i){let z=0,B=0;c&&E<0?z=L0(w+E+P,i[0][0]):!c&&E>0&&(z=F0(w+I+P,i[1][0])),u&&N<0?B=L0(k+N+F,i[0][1]):!u&&N>0&&(B=F0(k+A+F,i[1][1])),D=Math.max(D,z),V=Math.max(V,B)}if(l){let z=0,B=0;c&&E>0?z=F0(w+E,l[0][0]):!c&&E<0&&(z=L0(w+I,l[1][0])),u&&N>0?B=F0(k+N,l[0][1]):!u&&N<0&&(B=L0(k+A,l[1][1])),D=Math.max(D,z),V=Math.max(V,B)}if(s){if(d){const z=j6(I/j,b,S)*j;if(D=Math.max(D,z),i){let B=0;!c&&!u||c&&!u&&p?B=F0(k+F+I/j,i[1][1])*j:B=L0(k+F+(c?E:-E)/j,i[0][1])*j,D=Math.max(D,B)}if(l){let B=0;!c&&!u||c&&!u&&p?B=L0(k+I/j,l[1][1])*j:B=F0(k+(c?E:-E)/j,l[0][1])*j,D=Math.max(D,B)}}if(f){const z=j6(A*j,v,y)/j;if(V=Math.max(V,z),i){let B=0;!c&&!u||u&&!c&&p?B=F0(w+A*j+P,i[1][0])/j:B=L0(w+(u?N:-N)*j+P,i[0][0])/j,V=Math.max(V,B)}if(l){let B=0;!c&&!u||u&&!c&&p?B=L0(w+A*j,l[1][0])/j:B=F0(w+(u?N:-N)*j,l[0][0])/j,V=Math.max(V,B)}}}N=N+(N<0?V:-V),E=E+(E<0?D:-D),s&&(p?I>A*j?N=(rFe(c,u)?-E:E)/j:E=(rFe(c,u)?-N:N)*j:d?(N=E/j,u=c):(E=N*j,c=u));const H=c?w+E:w,L=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+L}}const Z0t={width:0,height:0,x:0,y:0},LHn={...Z0t,pointerX:0,pointerY:0,aspectRatio:1};function FHn(e){return[[0,0],[e.measured.width,e.measured.height]]}function zHn(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 BHn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=gp(e);let i={controlDirection:nFe("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:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...Z0t},S={...LHn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:nFe(u)};let w,k=null,_=[],C,j,E,N=!1;const I=s0t().on("start",A=>{const{nodeLookup:P,transform:F,snapGrid:D,snapToGrid:V,nodeOrigin:H,paneDomNode:L}=n();if(w=P.get(t),!w)return;k=L?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:B}=U2(A.sourceEvent,{transform:F,snapGrid:D,snapToGrid:V,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},S={...b,pointerX:z,pointerY:B,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),j=C&&w.extent==="parent"?FHn(C):void 0),_=[],E=void 0;for(const[M,G]of P)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=zHn(G,w,G.origin??H);E?E=[[Math.min(q[0][0],E[0][0]),Math.min(q[0][1],E[0][1])],[Math.max(q[1][0],E[1][0]),Math.max(q[1][1],E[1][1])]]:E=q}h?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:F,snapToGrid:D,nodeOrigin:V}=n(),H=U2(A.sourceEvent,{transform:P,snapGrid:F,snapToGrid:D,containerBounds:k}),L=[];if(!w)return;const{x:z,y:B,width:M,height:G}=b,q={},$=w.origin??V,{width:U,height:Z,x:X,y:te}=DHn(S,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,j,E),J=U!==M,ee=Z!==G,ae=X!==z&&J,ce=te!==B&ⅇif(!ae&&!ce&&!J&&!ee)return;if((ae||ce||$[0]===1||$[1]===1)&&(q.x=ae?X:b.x,q.y=ce?te:b.y,b.x=q.x,b.y=q.y,_.length>0)){const pe=X-z,oe=te-B;for(const ve of _)ve.position={x:ve.position.x-pe+$[0]*(U-M),y:ve.position.y-oe+$[1]*(Z-G)},L.push(ve)}if((J||ee)&&(q.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,q.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),C&&w.expandParent){const pe=$[0]*(q.width??0);q.x&&q.x<pe&&(b.x=pe,S.x=S.x-(q.x-pe));const oe=$[1]*(q.height??0);q.y&&q.y<oe&&(b.y=oe,S.y=S.y-(q.y-oe))}const Y=MHn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:Y};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(q,L))}).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 UHn={},sFe=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(UHn?"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},qHn=e=>e?sFe(e):sFe,{useDebugValue:VHn}=Le,{useSyncExternalStoreWithSelector:HHn}=f1n,WHn=e=>e;function G0t(e,t=WHn,n){const r=HHn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return VHn(r),r}const aFe=(e,t)=>{const n=qHn(e),r=(s,a=t)=>G0t(n,s,a);return Object.assign(r,n),r},ZHn=(e,t)=>e?aFe(e,t):aFe;function no(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 DV=g.createContext(null),GHn=DV.Provider,Q0t=my.error001();function Us(e,t){const n=g.useContext(DV);if(n===null)throw new Error(Q0t);return G0t(n,e,t)}function So(){const e=g.useContext(DV);if(e===null)throw new Error(Q0t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const iFe={display:"none"},QHn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Y0t="react-flow__node-desc",X0t="react-flow__edge-desc",YHn="react-flow__aria-live",XHn=e=>e.ariaLiveMessage,KHn=e=>e.ariaLabelConfig;function JHn({rfId:e}){const t=Us(XHn);return o.jsx("div",{id:`${YHn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:QHn,children:t})}function eWn({rfId:e,disableKeyboardA11y:t}){const n=Us(KHn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${Y0t}-${e}`,style:iFe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${X0t}-${e}`,style:iFe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(JHn,{rfId:e})]})}const y3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ml(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});y3.displayName="Panel";function tWn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(y3,{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 nWn=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}},T6=e=>e.id;function rWn(e,t){return no(e.selectedNodes.map(T6),t.selectedNodes.map(T6))&&no(e.selectedEdges.map(T6),t.selectedEdges.map(T6))}function sWn({onSelectionChange:e}){const t=So(),{selectedNodes:n,selectedEdges:r}=Us(nWn,rWn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const aWn=e=>!!e.onSelectionChangeHandlers;function iWn({onSelectionChange:e}){const t=Us(aWn);return e||t?o.jsx(sWn,{onSelectionChange:e}):null}const Bhe=typeof window<"u"?g.useLayoutEffect:g.useEffect,K0t=[0,0],oWn={x:0,y:0,zoom:1},lWn=["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"],oFe=[...lWn,"rfId"],cWn=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}),lFe={translateExtent:nM,nodeOrigin:K0t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function uWn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(cWn,no),u=So();Bhe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=lFe,l()}),[]);const d=g.useRef(lFe);return Bhe(()=>{for(const f of oFe){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:JVn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},oFe.map(f=>e[f])),null}function cFe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function dWn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=cFe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:cFe()?.matches?"dark":"light"}const uFe=typeof document<"u"?document:null;function oM(e=null,t={target:uFe,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("+",`
|
|
336
|
+
`: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 pzn(this):new uzn(this)}getCursor(t,n=0,r){let s=t.doc?t:os.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?wE(this,s,n,r):xE(this,s,n,r)}}class Ext{constructor(t){this.spec=t}}function lzn(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 xE(e,t,n,r){let s;return e.wholeWord&&(s=czn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=lzn(e.test,t,s)),new kx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function czn(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(_7(s,n-a))!=po.Word||t(C7(s,n-a))!=po.Word)&&(t(C7(s,r-a))!=po.Word||t(_7(s,r-a))!=po.Word))}class uzn extends Ext{constructor(t){super(t)}nextMatch(t,n,r){let s=xE(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=xE(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=xE(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=xE(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=xE(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 dzn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function wE(e,t,n,r){let s;return e.wholeWord&&(s=fzn(t.charCategorizer(t.selection.main.head))),e.test&&(s=dzn(e.test,t,s)),new Oxt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function _7(e,t){return e.slice(bc(e,t,!1),t)}function C7(e,t){return e.slice(t,bc(e,t))}function fzn(e){return(t,n,r)=>!r[0].length||(e(_7(r.input,r.index))!=po.Word||e(C7(r.input,r.index))!=po.Word)&&(e(C7(r.input,r.index+r[0].length))!=po.Word||e(_7(r.input,r.index+r[0].length))!=po.Word)}class pzn extends Ext{nextMatch(t,n,r){let s=wE(this.spec,t,r,t.doc.length).next();return s.done&&(s=wE(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=wE(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=wE(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=wE(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 Q$=vr.define(),u1e=vr.define(),Pw=gl.define({create(e){return new XK(Che(e).create(),null)},update(e,t){for(let n of t.effects)n.is(Q$)?e=new XK(n.value.create(),e.panel):n.is(u1e)&&(e=new XK(e.query,n.value?d1e:null));return e},provide:e=>F$.from(e,t=>t.panel)});class XK{constructor(t,n){this.query=t,this.panel=n}}const hzn=Cn.mark({class:"cm-searchMatch"}),mzn=Cn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),gzn=bo.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Pw))}update(e){let t=e.state.field(Pw);(t!=e.startState.field(Pw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Cn.none;let{view:n}=this,r=new kd;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(p=>p.from==u&&p.to==d);r.add(u,d,f?mzn:hzn)})}return r.finish()}},{decorations:e=>e.decorations});function d3(e){return t=>{let n=t.state.field(Pw,!1);return n&&n.query.spec.valid?e(t,n):Nxt(t)}}const E7=d3((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=bt.single(r.from,r.to),a=e.state.facet(qN);return e.dispatch({selection:s,effects:[f1e(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),Txt(e),!0}),j7=d3((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=bt.single(s.from,s.to),i=e.state.facet(qN);return e.dispatch({selection:a,effects:[f1e(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),Txt(e),!0}),vzn=d3((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:bt.create(n.map(r=>bt.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),yzn=({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 kx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(bt.range(l.value.from,l.value.to))}return t(e.update({selection:bt.create(a,i),userEvent:"select.search.matches"})),!0},y6e=d3((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}),d.push(Nt.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=bt.single(i.from,i.to).map(f),d.push(f1e(e,i)),d.push(n.facet(qN).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),bzn=d3((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:Nt.announce.of(r),userEvent:"input.replace.all"}),!0});function d1e(e){return e.state.facet(qN).createPanel(e)}function Che(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(qN);return new Cxt({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 jxt(e){let t=Ewe(e,d1e);return t&&t.dom.querySelector("[main-field]")}function Txt(e){let t=jxt(e);t&&t==e.root.activeElement&&t.select()}const Nxt=e=>{let t=e.state.field(Pw,!1);if(t&&t.panel){let n=jxt(e);if(n&&n!=e.root.activeElement){let r=Che(e.state,t.query.spec);r.valid&&e.dispatch({effects:Q$.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[u1e.of(!0),t?Q$.of(Che(e.state,t.query.spec)):vr.appendConfig.of(kzn)]});return!0},Ixt=e=>{let t=e.state.field(Pw,!1);if(!t||!t.panel)return!1;let n=Ewe(e,d1e);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:u1e.of(!1)}),!0},xzn=[{key:"Mod-f",run:Nxt,scope:"editor search-panel"},{key:"F3",run:E7,shift:j7,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:E7,shift:j7,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Ixt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:yzn},{key:"Mod-Alt-g",run:Y8n},{key:"Mod-d",run:ozn,preventDefault:!0}];class wzn{constructor(t){this.view=t;let n=this.query=t.state.field(Pw).query.spec;this.commit=this.commit.bind(this),this.searchField=ci("input",{value:n.search,placeholder:Qf(t,"Find"),"aria-label":Qf(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=ci("input",{value:n.replace,placeholder:Qf(t,"Replace"),"aria-label":Qf(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=ci("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=ci("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=ci("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return ci("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=ci("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>E7(t),[Qf(t,"next")]),r("prev",()=>j7(t),[Qf(t,"previous")]),r("select",()=>vzn(t),[Qf(t,"all")]),ci("label",null,[this.caseField,Qf(t,"match case")]),ci("label",null,[this.reField,Qf(t,"regexp")]),ci("label",null,[this.wordField,Qf(t,"by word")]),...t.state.readOnly?[]:[ci("br"),this.replaceField,r("replace",()=>y6e(t),[Qf(t,"replace")]),r("replaceAll",()=>bzn(t),[Qf(t,"replace all")])],ci("button",{name:"close",onclick:()=>Ixt(t),"aria-label":Qf(t,"close"),type:"button"},["×"])])}commit(){let t=new Cxt({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:Q$.of(t)}))}keydown(t){B3n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?j7:E7)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),y6e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(Q$)&&!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(qN).top}}function Qf(e,t){return e.state.phrase(t)}const b6=30,x6=/[\s\.,:;?!]/;function f1e(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-b6),i=Math.min(s,n+b6),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<b6;c++)if(!x6.test(l[c+1])&&x6.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-b6;c--)if(!x6.test(l[c-1])&&x6.test(l[c])){l=l.slice(0,c);break}}return Nt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const Szn=Nt.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"}}),kzn=[Pw,Xp.low(gzn),Szn];class b6e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class pk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(Y$).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new kd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let p,h;for(l.length?(p=c,h=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>p?f.from:1e8)):(p=f.from,h=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==p&&(v.to>v.from||v.to==p))l.push(v),d++,h=Math.min(v.to,h);else{h=Math.min(v.from,h);break}}let m=Mzn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(p,p,Cn.widget({widget:new Azn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(p,h,Cn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>h)}))}c=h;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new pk(u,n,bT(u))}}function bT(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 b6e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new b6e(r.from,a,r.diagnostic)}}),r}function Ozn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(Y$).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(Axt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function _zn(e,t){return e.field(xp,!1)?t:t.concat(vr.appendConfig.of(Dzn))}const Axt=vr.define(),p1e=vr.define(),Rxt=vr.define(),xp=gl.define({create(){return new pk(Cn.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=bT(n,e.selected.diagnostic,a)||bT(n,null,a)}!n.size&&s&&t.state.facet(Y$).autoPanel&&(s=null),e=new pk(n,s,r)}for(let n of t.effects)if(n.is(Axt)){let r=t.state.facet(Y$).autoPanel?n.value.length?X$.open:null:e.panel;e=pk.init(n.value,r,t.state)}else n.is(p1e)?e=new pk(e.diagnostics,n.value?X$.open:null,e.selected):n.is(Rxt)&&(e=new pk(e.diagnostics,e.panel,n.value));return e},provide:e=>[F$.from(e,t=>t.panel),Nt.decorations.from(e,t=>t.diagnostics)]}),Czn=Cn.mark({class:"cm-lintRange cm-lintRange-active"});function Ezn(e,t,n){let{diagnostics:r}=e.state.field(xp),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(Y$).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:jzn(e,s)}}}:null}function jzn(e,t){return ci("ul",{class:"cm-tooltip-lint"},t.map(n=>$xt(e,n,!1)))}const Tzn=e=>{let t=e.state.field(xp,!1);(!t||!t.panel)&&e.dispatch({effects:_zn(e.state,[p1e.of(!0)])});let n=Ewe(e,X$.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},x6e=e=>{let t=e.state.field(xp,!1);return!t||!t.panel?!1:(e.dispatch({effects:p1e.of(!1)}),!0)},Nzn=e=>{let t=e.state.field(xp,!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)},Izn=[{key:"Mod-Shift-m",run:Tzn,preventDefault:!0},{key:"F8",run:Nzn}],Y$=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...$y(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:w6e,tooltipFilter:w6e,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 w6e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function Pxt(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 $xt(e,t,n){var r;let s=n?Pxt(t.actions):[];return ci("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},ci("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=h=>{if(h.preventDefault(),l)return;l=!0;let m=bT(e.state.field(xp).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),ci("u",u.slice(d,d+1)),u.slice(d+1)],p=a.markClass?" "+a.markClass:"";return ci("button",{type:"button",class:"cm-diagnosticAction"+p,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&ci("div",{class:"cm-diagnosticSource"},t.source))}class Azn extends Kp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return ci("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class S6e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=$xt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class X${constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)x6e(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=Pxt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=bT(this.view.state.field(xp).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=ci("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=ci("div",{class:"cm-panel-lint"},this.list,ci("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>x6e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(xp).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(xp),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,p;for(let h=r;h<this.items.length;h++)if(this.items[h].diagnostic==d){f=h;break}f<0?(p=new S6e(this.view,d),this.items.splice(r,0,p),s=!0):(p=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&p.diagnostic==n.diagnostic?p.dom.hasAttribute("aria-selected")||(p.dom.setAttribute("aria-selected","true"),a=p):p.dom.hasAttribute("aria-selected")&&p.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 S6e(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(xp),r=bT(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:Rxt.of(r)})}static open(t){return new X$(t)}}function Rzn(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 w6(e){return Rzn(`<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 Pzn=Nt.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:w6("#d11")},".cm-lintRange-warning":{backgroundImage:w6("orange")},".cm-lintRange-info":{backgroundImage:w6("#999")},".cm-lintRange-hint":{backgroundImage:w6("#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 $zn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function Mzn(e){let t="hint",n=1;for(let r of e){let s=$zn(r.severity);s>n&&(n=s,t=r.severity)}return t}const Dzn=[xp,Nt.decorations.compute([xp],e=>{let{selected:t,panel:n}=e.field(xp);return!t||!n||t.from==t.to?Cn.none:Cn.set([Czn.range(t.from,t.to)])}),T4n(Ezn,{hideOn:Ozn}),Pzn];var k6e=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(CLn)),t.defaultKeymap!==!1&&(a=a.concat(Z8n)),t.searchKeymap!==!1&&(a=a.concat(xzn)),t.historyKeymap!==!1&&(a=a.concat(e8n)),t.foldKeymap!==!1&&(a=a.concat(d5n)),t.completionKeymap!==!1&&(a=a.concat(Tyt)),t.lintKeymap!==!1&&(a=a.concat(Izn));var i=[];return t.lineNumbers!==!1&&i.push(B4n()),t.highlightActiveLineGutter!==!1&&i.push(V4n()),t.highlightSpecialChars!==!1&&i.push(r4n()),t.history!==!1&&i.push(HFn()),t.foldGutter!==!1&&i.push(m5n()),t.drawSelection!==!1&&i.push(Z3n()),t.dropCursor!==!1&&i.push(K3n()),t.allowMultipleSelections!==!1&&i.push(os.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(r5n()),t.syntaxHighlighting!==!1&&i.push(z1(b5n,{fallback:!0})),t.bracketMatching!==!1&&i.push(C5n()),t.closeBrackets!==!1&&i.push(SLn()),t.autocompletion!==!1&&i.push(jyt()),t.rectangularSelection!==!1&&i.push(v4n()),s!==!1&&i.push(x4n()),t.highlightActiveLine!==!1&&i.push(c4n()),t.highlightSelectionMatches!==!1&&i.push(J8n()),t.tabSize&&typeof t.tabSize=="number"&&i.push(FN.of(" ".repeat(t.tabSize))),i.concat([LN.of(a.flat())]).filter(Boolean)};const Lzn="#e5c07b",O6e="#e06c75",Fzn="#56b6c2",zzn="#ffffff",YF="#abb2bf",Ehe="#7d8799",Bzn="#61afef",Uzn="#98c379",_6e="#d19a66",qzn="#c678dd",Vzn="#21252b",C6e="#2c313a",E6e="#282c34",KK="#353a42",Hzn="#3E4451",j6e="#528bff",Wzn=Nt.theme({"&":{color:YF,backgroundColor:E6e},".cm-content":{caretColor:j6e},".cm-cursor, .cm-dropCursor":{borderLeftColor:j6e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:Hzn},".cm-panels":{backgroundColor:Vzn,color:YF},".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:E6e,color:Ehe,border:"none"},".cm-activeLineGutter":{backgroundColor:C6e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:KK},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:KK,borderBottomColor:KK},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:C6e,color:YF}}},{dark:!0}),Zzn=Lg.define([{tag:fe.keyword,color:qzn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:O6e},{tag:[fe.function(fe.variableName),fe.labelName],color:Bzn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:_6e},{tag:[fe.definition(fe.name),fe.separator],color:YF},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:Lzn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:Fzn},{tag:[fe.meta,fe.comment],color:Ehe},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Ehe,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:O6e},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:_6e},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:Uzn},{tag:fe.invalid,color:zzn}]),Gzn=[Wzn,z1(Zzn)];var Qzn=Nt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),Yzn=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,p=f===void 0?"":f,h=n.basicSetup,m=h===void 0?!0:h,v=[];switch(s&&v.unshift(LN.of([G8n])),m&&(typeof m=="boolean"?v.unshift(k6e()):v.unshift(k6e(m))),p&&v.unshift(p4n(p)),d){case"light":v.push(Qzn);break;case"dark":v.push(Gzn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Nt.editable.of(!1)),c&&v.push(os.readOnly.of(!0)),[...v]},Xzn=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 Kzn{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 T6e{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 JK=null,Jzn=()=>typeof window>"u"?new T6e:(JK||(JK=new T6e),JK),N6e=Py.define(),e7n=200,t7n=[];function n7n(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?t7n:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,p=e.height,h=p===void 0?null:p,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,S=e.width,w=S===void 0?null:S,k=e.minWidth,_=k===void 0?null:k,C=e.maxWidth,j=C===void 0?null:C,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,P=e.readOnly,F=P===void 0?!1:P,D=e.indentWithTab,V=D===void 0?!0:D,H=e.basicSetup,L=H===void 0?!0:H,z=e.root,B=e.initialState,M=g.useState(),G=M[0],q=M[1],$=g.useState(),U=$[0],Z=$[1],X=g.useState(),te=X[0],J=X[1],ee=g.useState(()=>({current:null}))[0],ae=g.useState(()=>({current:null}))[0],ce=Nt.theme({"&":{height:h,minHeight:v,maxHeight:b,width:w,minWidth:_,maxWidth:j},"& .cm-scroller":{height:"100% !important"}}),Y=Nt.updateListener.of(pe=>{if(pe.docChanged&&typeof r=="function"&&!pe.transactions.some(ye=>ye.annotation(N6e))){ee.current?ee.current.reset():(ee.current=new Kzn(()=>{if(ae.current){var ye=ae.current;ae.current=null,ye()}ee.current=null},e7n),Jzn().add(ee.current));var oe=pe.state.doc,ve=oe.toString();r(ve,pe)}s&&s(Xzn(pe))}),ne=Yzn({theme:f,editable:A,readOnly:F,placeholder:N,indentWithTab:V,basicSetup:L}),ue=[Y,ce,...ne];return i&&typeof i=="function"&&ue.push(Nt.updateListener.of(i)),ue=ue.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var pe={doc:t,selection:n,extensions:ue},oe=B?os.fromJSON(B.json,pe,B.fields):os.create(pe);if(J(oe),!U){var ve=new Nt({state:oe,parent:G,root:z});Z(ve),a&&a(ve,oe)}}return()=>{U&&(J(void 0),Z(void 0))}},[G,te]),g.useEffect(()=>{e.container&&q(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),Z(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:vr.reconfigure.of(ue)})},[f,c,h,v,b,w,_,j,N,A,F,V,L,r,i]),g.useEffect(()=>{if(t!==void 0){var pe=U?U.state.doc.toString():"";if(U&&t!==pe){var oe=ee.current&&!ee.current.isDone,ve=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[N6e.of(!0)]})};oe?ae.current=ve:ve()}}},[t,U]),{state:te,setState:J,view:U,setView:Z,container:G,setContainer:q}}var r7n=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],au=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,p=e.autoFocus,h=e.theme,m=h===void 0?"light":h,v=e.height,y=e.minHeight,b=e.maxHeight,S=e.width,w=e.minWidth,k=e.maxWidth,_=e.basicSetup,C=e.placeholder,j=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,P=qbt(e,r7n),F=g.useRef(null),D=n7n({root:I,value:s,autoFocus:p,theme:m,height:v,minHeight:y,maxHeight:b,width:S,minWidth:w,maxWidth:k,basicSetup:_,placeholder:C,indentWithTab:j,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),V=D.state,H=D.view,L=D.container,z=D.setContainer;g.useImperativeHandle(t,()=>({editor:F.current,state:V,view:H}),[F,L,V,H]);var B=g.useCallback(G=>{F.current=G,z(G)},[z]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var M=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",AO({ref:B,className:""+M+(n?" "+n:"")},P))});au.displayName="CodeMirror";const s7n={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"};let eJ=null;function a7n(){return eJ||(eJ=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([lo(()=>import("./core-DBaVdGg0.js"),__vite__mapDeps([0,1,2]),import.meta.url),lo(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[lo(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),lo(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[lo(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),lo(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),lo(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),lo(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),lo(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),lo(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),lo(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),lo(()=>import("./python-DhUJRlN_.js"),[],import.meta.url)],engine:t()})})()),eJ}async function i7n(e,t){const n=s7n[t?.toLowerCase()];if(!n)return null;const r=await a7n(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function o7n(e){return new jO(Awe.define(e))}const Mxt=[Jm.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript())}}),Jm.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return lo(()=>Promise.resolve().then(()=>L5n),void 0,import.meta.url).then(e=>e.json())}}),Jm.of({name:"JSX",extensions:["jsx"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),Jm.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return lo(()=>Promise.resolve().then(()=>AFn),void 0,import.meta.url).then(e=>e.markdown())}}),Jm.of({name:"TSX",extensions:["tsx"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),Jm.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return lo(()=>Promise.resolve().then(()=>v6),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),Jm.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return lo(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>o7n(e.shell))}})];function l7n(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 c7n(e){const t=l7n(e);return jyt({override:[u7n(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function u7n(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,p)=>{const v=u.state.sliceDoc(p,p+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:p,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const d7n=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,f7n=Cn.mark({class:"cm-variable-highlight"}),I6e=new Uvt({regexp:d7n,decoration:()=>f7n}),p7n=bo.fromClass(class{decorations;constructor(e){this.decorations=I6e.createDeco(e)}update(e){this.decorations=I6e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),h7n=p7n;function m7n(){const e=BN({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=Nt.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 g7n(){const e=Nt.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=Lg.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,z1(t)]}const My=()=>{const e=RN().resolvedTheme==="dark";return g.useMemo(()=>e?m7n():g7n(),[e])},v7n=Fo(K("font-mono relative overflow-hidden outline-hidden focus:outline-hidden focus-within:outline-hidden","transition-colors duration-normal ease-out-custom"),{variants:{variant:{default:"rounded-md bg-surface3 border border-border1 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),y7n=Xp.highest(Nt.editorAttributes.of({style:"outline: none"})),b7n=Xp.highest(Nt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),x7n=[y7n,b7n],Yr=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:p,variant:h,...m},v)=>{const y=My(),b=e?JSON.stringify(e,null,2):t??"",S=g.useMemo(()=>{const w=[...x7n];return f&&w.push(Nt.lineWrapping),a==="json"?w.push(ff):a==="markdown"&&w.push(a1e({base:IO,codeLanguages:Mxt})),i&&a==="markdown"&&w.push(h7n),c&&a==="markdown"&&w.push(c7n(c)),p===!1&&w.push(os.readOnly.of(!0)),w},[a,i,c,p,f]);return o.jsxs("div",{className:K(v7n({variant:h}),s),...m,children:[r&&o.jsx(ka,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(au,{ref:v,value:b,theme:y,extensions:S,onChange:n,editable:p,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),w7n=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},S7n=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=My(),{settings:r,setSettings:s}=tV(),a=r?.tracingOptions,i=g.useMemo(()=>w7n(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=p=>{u.current=!0,c(p)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const p=JSON.parse(l);typeof p=="object"&&p!==null&&s({...r,tracingOptions:p})}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(au,{value:l,onChange:d,theme:n,extensions:[ff],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(de,{type:"button",onClick:f,children:"Save"})})]})},k7n=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(de,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Ue,{children:o.jsx(hq,{})})})}),o.jsx(Ln,{children:"Run Options"})]}),o.jsx(br,{open:e,onOpenChange:t,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Options"}),o.jsx(Qs,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Pr,{children:o.jsx(S7n,{onSaved:()=>t(!1)})})]})})]})};function O7n({status:e}){switch(e){case"running":return o.jsx(Gt,{});case"failed":return o.jsx(vs,{className:"text-accent2"});case"canceled":return o.jsx(Of,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(Gj,{className:"text-neutral3"});case"suspended":return o.jsx(lq,{className:"text-accent3"});case"success":return o.jsx(ea,{className:"text-accent1"});default:return o.jsx(Gj,{className:"text-neutral3"})}}function Dxt({status:e}){return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(Ue,{"aria-label":e,className:"shrink-0",children:o.jsx(O7n,{status:e})})}),o.jsx(Ln,{children:e})]})}var tJ,A6e;function h1e(){if(A6e)return tJ;A6e=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 p=arguments,h=this;return d.forEach(function(m){p.length>1?h.setNode(m,f):h.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 p=h=>f.removeEdge(f._edgeObjs[h]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(h){f.setParent(h)}),delete this._children[d]),Object.keys(this._in[d]).forEach(p),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(p),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 p=f;p!==void 0;p=this.parent(p))if(p===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 h=new Set(f);for(var p of this.successors(d))h.add(p);return Array.from(h.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 p=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,p.edge(v))});var h={};function m(v){var y=p.parent(v);return y===void 0||f.hasNode(y)?(h[v]=y,y):y in h?h[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 p=this,h=arguments;return d.reduce(function(m,v){return h.length>1?p.setEdge(m,v,f):p.setEdge(m,v),v}),this}setEdge(){var d,f,p,h,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,p=v.name,arguments.length===2&&(h=arguments[1],m=!0)):(d=v,f=arguments[1],p=arguments[3],arguments.length>2&&(h=arguments[2],m=!0)),d=""+d,f=""+f,p!==void 0&&(p=""+p);var y=i(this._isDirected,d,f,p);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=h),this;if(p!==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?h:this._defaultEdgeLabelFn(d,f,p);var b=l(this._isDirected,d,f,p);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,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return this._edgeLabels[h]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p);return Object.hasOwn(this._edgeLabels,h)}removeEdge(d,f,p){var h=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,p),m=this._edgeObjs[h];return m&&(d=m.v,f=m.w,delete this._edgeLabels[h],delete this._edgeObjs[h],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][h],delete this._out[d][h],this._edgeCount--),this}inEdges(d,f){var p=this._in[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.v===f):h}}outEdges(d,f){var p=this._out[d];if(p){var h=Object.values(p);return f?h.filter(m=>m.w===f):h}}nodeEdges(d,f){var p=this.inEdges(d,f);if(p)return p.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,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}return h+n+m+n+(p===void 0?e:p)}function l(u,d,f,p){var h=""+d,m=""+f;if(!u&&h>m){var v=h;h=m,m=v}var y={v:h,w:m};return p&&(y.name=p),y}function c(u,d){return i(u,d.v,d.w,d.name)}return tJ=r,tJ}var nJ,R6e;function _7n(){return R6e||(R6e=1,nJ="2.2.4"),nJ}var rJ,P6e;function C7n(){return P6e||(P6e=1,rJ={Graph:h1e(),version:_7n()}),rJ}var sJ,$6e;function E7n(){if($6e)return sJ;$6e=1;var e=h1e();sJ={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 sJ}var aJ,M6e;function j7n(){if(M6e)return aJ;M6e=1,aJ=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 aJ}var iJ,D6e;function Lxt(){if(D6e)return iJ;D6e=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 iJ=e,iJ}var oJ,L6e;function Fxt(){if(L6e)return oJ;L6e=1;var e=Lxt();oJ=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,p=function(h){var m=h.v!==d?h.v:h.w,v=c[m],y=i(h),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+h+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(h){var m=h===a?0:Number.POSITIVE_INFINITY;c[h]={distance:m},u.add(h,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(p);return c}return oJ}var lJ,F6e;function T7n(){if(F6e)return lJ;F6e=1;var e=Fxt();lJ=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return lJ}var cJ,z6e;function zxt(){if(z6e)return cJ;z6e=1,cJ=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 cJ}var uJ,B6e;function N7n(){if(B6e)return uJ;B6e=1;var e=zxt();uJ=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return uJ}var dJ,U6e;function I7n(){if(U6e)return dJ;U6e=1,dJ=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(p){var h=f[c],m=u[p],v=f[p],y=h.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return dJ}var fJ,q6e;function Bxt(){if(q6e)return fJ;q6e=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 fJ=e,e.CycleException=t,fJ}var pJ,V6e;function A7n(){if(V6e)return pJ;V6e=1;var e=Bxt();pJ=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return pJ}var hJ,H6e;function Uxt(){if(H6e)return hJ;H6e=1,hJ=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 hJ}var mJ,W6e;function R7n(){if(W6e)return mJ;W6e=1;var e=Uxt();mJ=t;function t(n,r){return e(n,r,"post")}return mJ}var gJ,Z6e;function P7n(){if(Z6e)return gJ;Z6e=1;var e=Uxt();gJ=t;function t(n,r){return e(n,r,"pre")}return gJ}var vJ,G6e;function $7n(){if(G6e)return vJ;G6e=1;var e=h1e(),t=Lxt();vJ=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var p=f.v===c?f.w:f.v,h=l.priority(p);if(h!==void 0){var m=s(f);m<h&&(i[p]=c,l.decrease(p,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 vJ}var yJ,Q6e;function M7n(){return Q6e||(Q6e=1,yJ={components:j7n(),dijkstra:Fxt(),dijkstraAll:T7n(),findCycles:N7n(),floydWarshall:I7n(),isAcyclic:A7n(),postorder:R7n(),preorder:P7n(),prim:$7n(),tarjan:zxt(),topsort:Bxt()}),yJ}var bJ,Y6e;function Ig(){if(Y6e)return bJ;Y6e=1;var e=C7n();return bJ={Graph:e.Graph,json:E7n(),alg:M7n(),version:e.version},bJ}var xJ,X6e;function D7n(){if(X6e)return xJ;X6e=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 xJ=e,xJ}var wJ,K6e;function L7n(){if(K6e)return wJ;K6e=1;let e=Ig().Graph,t=D7n();wJ=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(h=>u.outEdges(h.v,h.w))}function s(u,d,f){let p=[],h=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=h.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){p=p.concat(a(u,d,f,v,!0));break}}}return p}function a(u,d,f,p,h){let m=h?[]:void 0;return u.inEdges(p.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);h&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(p.v).forEach(v=>{let y=u.edge(v),b=v.w,S=u.node(b);S.in-=y,l(d,f,S)}),u.removeNode(p.v),m}function i(u,d){let f=new e,p=0,h=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,S=d(y),w=b+S;f.setEdge(y.v,y.w,w),h=Math.max(h,f.node(y.v).out+=S),p=Math.max(p,f.node(y.w).in+=S)});let m=c(h+p+3).map(()=>new t),v=p+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 wJ}var SJ,J6e;function Nl(){if(J6e)return SJ;J6e=1;let e=Ig().Graph;SJ={addBorderNode:d,addDummyNode:t,applyWithChunking:h,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:C,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:_,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:j};function t(E,N,I,A){for(var P=A;E.hasNode(P);)P=w(A);return I.dummy=N,E.setNode(P,I),P}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},P=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+P.weight,minlen:Math.max(A.minlen,P.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach(P=>{A[P.w]=(A[P.w]||0)+E.edge(P).weight}),A});return j(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach(P=>{A[P.v]=(A[P.v]||0)+E.edge(P).weight}),A});return j(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,P=N.x-I,F=N.y-A,D=E.width/2,V=E.height/2;if(!P&&!F)throw new Error("Not possible to find intersection inside of the rectangle");let H,L;return Math.abs(F)*D>Math.abs(P)*V?(F<0&&(V=-V),H=V*P/F,L=V):(P<0&&(D=-D),H=D,L=D*F/P),{x:I+H,y:A+L}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),P=A.rank;P!==void 0&&(N[P][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MAX_VALUE:P}),I=h(Math.min,N);E.nodes().forEach(A=>{let P=E.node(A);Object.hasOwn(P,"rank")&&(P.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=h(Math.min,N),A=[];E.nodes().forEach(D=>{let V=E.node(D).rank-I;A[V]||(A[V]=[]),A[V].push(D)});let P=0,F=E.graph().nodeRankFactor;Array.from(A).forEach((D,V)=>{D===void 0&&V%F!==0?--P:D!==void 0&&P&&D.forEach(H=>E.node(H).rank+=P)})}function d(E,N,I,A){let P={width:0,height:0};return arguments.length>=4&&(P.rank=I,P.order=A),t(E,"border",P,N)}function f(E,N=p){const I=[];for(let A=0;A<E.length;A+=N){const P=E.slice(A,A+N);I.push(P)}return I}const p=65535;function h(E,N){if(N.length>p){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let P=E.node(A).rank;return P===void 0?Number.MIN_VALUE:P});return h(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let S=0;function w(E){var N=++S;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=F=>F<N;I<0&&(A=F=>N<F);const P=[];for(let F=E;A(F);F+=I)P.push(F);return P}function _(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function C(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[P,F])=>(A[P]=I(F,P),A),{})}function j(E,N){return E.reduce((I,A,P)=>(I[A]=N[P],I),{})}return SJ}var kJ,e9e;function F7n(){if(e9e)return kJ;e9e=1;let e=L7n(),t=Nl().uniqueId;kJ={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 kJ}var OJ,t9e;function z7n(){if(t9e)return OJ;t9e=1;let e=Nl();OJ={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),p=f.labelRank;if(u===l+1)return;s.removeEdge(a);let h,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},h=e.addDummyNode(s,"edge",m,"_d"),l===p&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,h,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(h),i=h;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 OJ}var _J,n9e;function T7(){if(n9e)return _J;n9e=1;const{applyWithChunking:e}=Nl();_J={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 _J}var CJ,r9e;function qxt(){if(r9e)return CJ;r9e=1;var e=Ig().Graph,t=T7().slack;CJ=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,p=u===f?d.w:f;!i.hasNode(p)&&!t(l,d)&&(i.setNode(p,{}),i.setEdge(u,p,{}),c(p))})}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 CJ}var EJ,s9e;function B7n(){if(s9e)return EJ;s9e=1;var e=qxt(),t=T7().slack,n=T7().longestPath,r=Ig().alg.preorder,s=Ig().alg.postorder,a=Nl().simplify;EJ=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=p,i.enterEdge=h,i.exchangeEdges=m;function i(S){S=a(S),n(S);var w=e(S);d(w),l(w,S);for(var k,_;k=p(w);)_=h(w,S,k),m(w,S,k,_)}function l(S,w){var k=s(S,S.nodes());k=k.slice(0,k.length-1),k.forEach(_=>c(S,w,_))}function c(S,w,k){var _=S.node(k),C=_.parent;S.edge(k,C).cutvalue=u(S,w,k)}function u(S,w,k){var _=S.node(k),C=_.parent,j=!0,E=w.edge(k,C),N=0;return E||(j=!1,E=w.edge(C,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,P=A?I.w:I.v;if(P!==C){var F=A===j,D=w.edge(I).weight;if(N+=F?D:-D,y(S,k,P)){var V=S.edge(k,P).cutvalue;N+=F?-V:V}}}),N}function d(S,w){arguments.length<2&&(w=S.nodes()[0]),f(S,{},1,w)}function f(S,w,k,_,C){var j=k,E=S.node(_);return w[_]=!0,S.neighbors(_).forEach(N=>{Object.hasOwn(w,N)||(k=f(S,w,k,N,_))}),E.low=j,E.lim=k++,C?E.parent=C:delete E.parent,k}function p(S){return S.edges().find(w=>S.edge(w).cutvalue<0)}function h(S,w,k){var _=k.v,C=k.w;w.hasEdge(_,C)||(_=k.w,C=k.v);var j=S.node(_),E=S.node(C),N=j,I=!1;j.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter(P=>I===b(S,S.node(P.v),N)&&I!==b(S,S.node(P.w),N));return A.reduce((P,F)=>t(w,F)<t(w,P)?F:P)}function m(S,w,k,_){var C=k.v,j=k.w;S.removeEdge(C,j),S.setEdge(_.v,_.w,{}),d(S),l(S,w),v(S,w)}function v(S,w){var k=S.nodes().find(C=>!w.node(C).parent),_=r(S,k);_=_.slice(1),_.forEach(C=>{var j=S.node(C).parent,E=w.edge(C,j),N=!1;E||(E=w.edge(j,C),N=!0),w.node(C).rank=w.node(j).rank+(N?E.minlen:-E.minlen)})}function y(S,w,k){return S.hasEdge(w,k)}function b(S,w,k){return k.low<=w.lim&&w.lim<=k.lim}return EJ}var jJ,a9e;function U7n(){if(a9e)return jJ;a9e=1;var e=T7(),t=e.longestPath,n=qxt(),r=B7n();jJ=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 jJ}var TJ,i9e;function q7n(){if(i9e)return TJ;i9e=1,TJ=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,p=u[f],h=!0;for(;a!==l.w;){if(i=r.node(a),h){for(;(p=u[f])!==d&&r.node(p).maxRank<i.rank;)f++;p===d&&(h=!1)}if(!h){for(;f<u.length-1&&r.node(p=u[f+1]).minRank<=i.rank;)f++;p=u[f]}r.setParent(a,p),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,p;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(p=f,f=i;(f=r.parent(f))!==p;)c.push(f);return{path:l.concat(c.reverse()),lca:p}}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 TJ}var NJ,o9e;function V7n(){if(o9e)return NJ;o9e=1;let e=Nl();NJ={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(h=>i.edge(h).minlen*=f);let p=s(i)+1;i.children().forEach(h=>n(i,l,f,p,d,c,h)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,p){let h=i.children(p);if(!h.length){p!==l&&i.setEdge(l,p,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(p);i.setParent(m,p),y.borderTop=m,i.setParent(v,p),y.borderBottom=v,h.forEach(b=>{n(i,l,c,u,d,f,b);let S=i.node(b),w=S.borderTop?S.borderTop:b,k=S.borderBottom?S.borderBottom:b,_=S.borderTop?u:2*u,C=w!==k?1:d-f[p]+1;i.setEdge(m,w,{weight:_,minlen:C,nestingEdge:!0}),i.setEdge(k,v,{weight:_,minlen:C,nestingEdge:!0})}),i.parent(p)||i.setEdge(l,m,{weight:0,minlen:d+f[p]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(p=>c(p,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 NJ}var IJ,l9e;function H7n(){if(l9e)return IJ;l9e=1;let e=Nl();IJ=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 IJ}var AJ,c9e;function W7n(){if(c9e)return AJ;c9e=1,AJ={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 AJ}var RJ,u9e;function Z7n(){if(u9e)return RJ;u9e=1;let e=Nl();RJ=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 RJ}var PJ,d9e;function G7n(){if(d9e)return PJ;d9e=1;let e=Nl().zipObject;PJ=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((p,h)=>h)),l=s.flatMap(p=>r.outEdges(p).map(h=>({pos:i[h.w],weight:r.edge(h).weight})).sort((h,m)=>h.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(p=>{let h=p.pos+c;d[h]+=p.weight;let m=0;for(;h>0;)h%2&&(m+=d[h+1]),h=h-1>>1,d[h]+=p.weight;f+=p.weight*m}),f}return PJ}var $J,f9e;function Q7n(){if(f9e)return $J;f9e=1,$J=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 $J}var MJ,p9e;function Y7n(){if(p9e)return MJ;p9e=1;let e=Nl();MJ=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 MJ}var DJ,h9e;function X7n(){if(h9e)return DJ;h9e=1;let e=Nl();DJ=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,p=0;l.sort(r(!!a)),p=n(u,c,p),l.forEach(m=>{p+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,p=n(u,c,p)});let h={vs:u.flat(!0)};return f&&(h.barycenter=d/f,h.weight=f),h}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 DJ}var LJ,m9e;function K7n(){if(m9e)return LJ;m9e=1;let e=Q7n(),t=Y7n(),n=X7n();LJ=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),p=f?f.borderLeft:void 0,h=f?f.borderRight:void 0,m={};p&&(d=d.filter(S=>S!==p&&S!==h));let v=e(i,d);v.forEach(S=>{if(i.children(S.v).length){let w=r(i,S.v,c,u);m[S.v]=w,Object.hasOwn(w,"barycenter")&&a(S,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(p&&(b.vs=[p,b.vs,h].flat(!0),i.predecessors(p).length)){let S=i.node(i.predecessors(p)[0]),w=i.node(i.predecessors(h)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+S.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 LJ}var FJ,g9e;function J7n(){if(g9e)return FJ;g9e=1;let e=Ig().Graph,t=Nl();FJ=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),p=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,p||c),s[i](d).forEach(h=>{let m=h.v===d?h.w:h.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(h).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 FJ}var zJ,v9e;function eBn(){if(v9e)return zJ;v9e=1,zJ=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 zJ}var BJ,y9e;function tBn(){if(y9e)return BJ;y9e=1;let e=Z7n(),t=G7n(),n=K7n(),r=J7n(),s=eBn(),a=Ig().Graph,i=Nl();BJ=l;function l(f,p){if(p&&typeof p.customOrder=="function"){p.customOrder(f,l);return}let h=i.maxRank(f),m=c(f,i.range(1,h+1),"inEdges"),v=c(f,i.range(h-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),p&&p.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,S;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let _=t(f,y);_<b&&(k=0,S=Object.assign({},y),b=_)}d(f,S)}function c(f,p,h){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 S=b.minRank;S<=b.maxRank;S++)S!==b.rank&&v(S,y)}return p.map(function(y){return r(f,y,h,m.get(y)||[])})}function u(f,p){let h=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,h,p);y.vs.forEach((b,S)=>m.node(b).order=S),s(m,h,y.vs)})}function d(f,p){Object.values(p).forEach(h=>h.forEach((m,v)=>f.node(m).order=v))}return BJ}var UJ,b9e;function nBn(){if(b9e)return UJ;b9e=1;let e=Ig().Graph,t=Nl();UJ={positionX:h,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:p};function n(y,b){let S={};function w(k,_){let C=0,j=0,E=k.length,N=_[_.length-1];return _.forEach((I,A)=>{let P=s(y,I),F=P?y.node(P).order:E;(P||I===N)&&(_.slice(j,A+1).forEach(D=>{y.predecessors(D).forEach(V=>{let H=y.node(V),L=H.order;(L<C||F<L)&&!(H.dummy&&y.node(D).dummy)&&a(S,V,D)})}),j=A+1,C=F)}),_}return b.length&&b.reduce(w),S}function r(y,b){let S={};function w(_,C,j,E,N){let I;t.range(C,j).forEach(A=>{I=_[A],y.node(I).dummy&&y.predecessors(I).forEach(P=>{let F=y.node(P);F.dummy&&(F.order<E||F.order>N)&&a(S,P,I)})})}function k(_,C){let j=-1,E,N=0;return C.forEach((I,A)=>{if(y.node(I).dummy==="border"){let P=y.predecessors(I);P.length&&(E=y.node(P[0]).order,w(C,N,A,j,E),N=A,j=E)}w(C,N,C.length,E,_.length)}),C}return b.length&&b.reduce(k),S}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(S=>y.node(S).dummy)}function a(y,b,S){if(b>S){let k=b;b=S,S=k}let w=y[b];w||(y[b]=w={}),w[S]=!0}function i(y,b,S){if(b>S){let w=b;b=S,S=w}return!!y[b]&&Object.hasOwn(y[b],S)}function l(y,b,S,w){let k={},_={},C={};return b.forEach(j=>{j.forEach((E,N)=>{k[E]=E,_[E]=E,C[E]=N})}),b.forEach(j=>{let E=-1;j.forEach(N=>{let I=w(N);if(I.length){I=I.sort((P,F)=>C[P]-C[F]);let A=(I.length-1)/2;for(let P=Math.floor(A),F=Math.ceil(A);P<=F;++P){let D=I[P];_[N]===N&&E<C[D]&&!i(S,N,D)&&(_[D]=N,_[N]=k[N]=k[D],E=C[D])}}})}),{root:k,align:_}}function c(y,b,S,w,k){let _={},C=u(y,b,S,k),j=k?"borderLeft":"borderRight";function E(A,P){let F=C.nodes(),D=F.pop(),V={};for(;D;)V[D]?A(D):(V[D]=!0,F.push(D),F=F.concat(P(D))),D=F.pop()}function N(A){_[A]=C.inEdges(A).reduce((P,F)=>Math.max(P,_[F.v]+C.edge(F)),0)}function I(A){let P=C.outEdges(A).reduce((D,V)=>Math.min(D,_[V.w]-C.edge(V)),Number.POSITIVE_INFINITY),F=y.node(A);P!==Number.POSITIVE_INFINITY&&F.borderType!==j&&(_[A]=Math.max(_[A],P))}return E(N,C.predecessors.bind(C)),E(I,C.successors.bind(C)),Object.keys(w).forEach(A=>_[A]=_[S[A]]),_}function u(y,b,S,w){let k=new e,_=y.graph(),C=m(_.nodesep,_.edgesep,w);return b.forEach(j=>{let E;j.forEach(N=>{let I=S[N];if(k.setNode(I),E){var A=S[E],P=k.edge(A,I);k.setEdge(A,I,Math.max(C(y,N,E),P||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((S,w)=>{let k=Number.NEGATIVE_INFINITY,_=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([j,E])=>{let N=v(y,j)/2;k=Math.max(E+N,k),_=Math.min(E-N,_)});const C=k-_;return C<S[0]&&(S=[C,w]),S},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let S=Object.values(b),w=t.applyWithChunking(Math.min,S),k=t.applyWithChunking(Math.max,S);["u","d"].forEach(_=>{["l","r"].forEach(C=>{let j=_+C,E=y[j];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);C!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[j]=t.mapValues(E,A=>A+I))})})}function p(y,b){return t.mapValues(y.ul,(S,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(_=>_[w]).sort((_,C)=>_-C);return(k[1]+k[2])/2}})}function h(y){let b=t.buildLayerMatrix(y),S=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(C=>{k=C==="u"?b:Object.values(b).reverse(),["l","r"].forEach(j=>{j==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(C==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,S,E),I=c(y,k,N.root,N.align,j==="r");j==="r"&&(I=t.mapValues(I,A=>-A)),w[C+j]=I})});let _=d(y,w);return f(w,_),p(w,y.graph().align)}function m(y,b,S){return(w,k,_)=>{let C=w.node(k),j=w.node(_),E=0,N;if(E+=C.width/2,Object.hasOwn(C,"labelpos"))switch(C.labelpos.toLowerCase()){case"l":N=-C.width/2;break;case"r":N=C.width/2;break}if(N&&(E+=S?N:-N),N=0,E+=(C.dummy?b:y)/2,E+=(j.dummy?b:y)/2,E+=j.width/2,Object.hasOwn(j,"labelpos"))switch(j.labelpos.toLowerCase()){case"l":N=j.width/2;break;case"r":N=-j.width/2;break}return N&&(E+=S?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return UJ}var qJ,x9e;function rBn(){if(x9e)return qJ;x9e=1;let e=Nl(),t=nBn().positionX;qJ=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 p=s.node(f).height;return d>p?d:p},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return qJ}var VJ,w9e;function sBn(){if(w9e)return VJ;w9e=1;let e=F7n(),t=z7n(),n=U7n(),r=Nl().normalizeRanks,s=q7n(),a=Nl().removeEmptyRanks,i=V7n(),l=H7n(),c=W7n(),u=tBn(),d=rBn(),f=Nl(),p=Ig().Graph;VJ=h;function h($,U){let Z=U&&U.debugTiming?f.time:f.notime;Z("layout",()=>{let X=Z(" buildLayoutGraph",()=>E($));Z(" runLayout",()=>m(X,Z,U)),Z(" updateInputGraph",()=>v($,X))})}function m($,U,Z){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>z($)),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",()=>P($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,Z)),U(" insertSelfEdges",()=>B($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>M($)),U(" removeBorderNodes",()=>L($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>V($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>F($)),U(" assignNodeIntersects",()=>D($)),U(" reversePoints",()=>H($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(Z=>{let X=$.node(Z),te=U.node(Z);X&&(X.x=te.x,X.y=te.y,X.rank=te.rank,U.children(Z).length&&(X.width=te.width,X.height=te.height))}),$.edges().forEach(Z=>{let X=$.edge(Z),te=U.edge(Z);X.points=te.points,Object.hasOwn(te,"x")&&(X.x=te.x,X.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"},S=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},_=["minlen","weight","width","height","labeloffset"],C={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},j=["labelpos"];function E($){let U=new p({multigraph:!0,compound:!0}),Z=q($.graph());return U.setGraph(Object.assign({},b,G(Z,y),f.pick(Z,S))),$.nodes().forEach(X=>{let te=q($.node(X));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),U.setNode(X,J),U.setParent(X,$.parent(X))}),$.edges().forEach(X=>{let te=q($.edge(X));U.setEdge(X,Object.assign({},C,G(te,_),f.pick(te,j)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(Z=>{let X=$.edge(Z);X.minlen*=2,X.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?X.width+=X.labeloffset:X.height+=X.labeloffset)})}function I($){$.edges().forEach(U=>{let Z=$.edge(U);if(Z.width&&Z.height){let X=$.node(U.v),J={rank:($.node(U.w).rank-X.rank)/2+X.rank,e:U};f.addDummyNode($,"edge-proxy",J,"_ep")}})}function A($){let U=0;$.nodes().forEach(Z=>{let X=$.node(Z);X.borderTop&&(X.minRank=$.node(X.borderTop).rank,X.maxRank=$.node(X.borderBottom).rank,U=Math.max(U,X.maxRank))}),$.graph().maxRank=U}function P($){$.nodes().forEach(U=>{let Z=$.node(U);Z.dummy==="edge-proxy"&&($.edge(Z.e).labelRank=Z.rank,$.removeNode(U))})}function F($){let U=Number.POSITIVE_INFINITY,Z=0,X=Number.POSITIVE_INFINITY,te=0,J=$.graph(),ee=J.marginx||0,ae=J.marginy||0;function ce(Y){let ne=Y.x,ue=Y.y,pe=Y.width,oe=Y.height;U=Math.min(U,ne-pe/2),Z=Math.max(Z,ne+pe/2),X=Math.min(X,ue-oe/2),te=Math.max(te,ue+oe/2)}$.nodes().forEach(Y=>ce($.node(Y))),$.edges().forEach(Y=>{let ne=$.edge(Y);Object.hasOwn(ne,"x")&&ce(ne)}),U-=ee,X-=ae,$.nodes().forEach(Y=>{let ne=$.node(Y);ne.x-=U,ne.y-=X}),$.edges().forEach(Y=>{let ne=$.edge(Y);ne.points.forEach(ue=>{ue.x-=U,ue.y-=X}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=X)}),J.width=Z-U+ee,J.height=te-X+ae}function D($){$.edges().forEach(U=>{let Z=$.edge(U),X=$.node(U.v),te=$.node(U.w),J,ee;Z.points?(J=Z.points[0],ee=Z.points[Z.points.length-1]):(Z.points=[],J=te,ee=X),Z.points.unshift(f.intersectRect(X,J)),Z.points.push(f.intersectRect(te,ee))})}function V($){$.edges().forEach(U=>{let Z=$.edge(U);if(Object.hasOwn(Z,"x"))switch((Z.labelpos==="l"||Z.labelpos==="r")&&(Z.width-=Z.labeloffset),Z.labelpos){case"l":Z.x-=Z.width/2+Z.labeloffset;break;case"r":Z.x+=Z.width/2+Z.labeloffset;break}})}function H($){$.edges().forEach(U=>{let Z=$.edge(U);Z.reversed&&Z.points.reverse()})}function L($){$.nodes().forEach(U=>{if($.children(U).length){let Z=$.node(U),X=$.node(Z.borderTop),te=$.node(Z.borderBottom),J=$.node(Z.borderLeft[Z.borderLeft.length-1]),ee=$.node(Z.borderRight[Z.borderRight.length-1]);Z.width=Math.abs(ee.x-J.x),Z.height=Math.abs(te.y-X.y),Z.x=J.x+Z.width/2,Z.y=X.y+Z.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function z($){$.edges().forEach(U=>{if(U.v===U.w){var Z=$.node(U.v);Z.selfEdges||(Z.selfEdges=[]),Z.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function B($){var U=f.buildLayerMatrix($);U.forEach(Z=>{var X=0;Z.forEach((te,J)=>{var ee=$.node(te);ee.order=J+X,(ee.selfEdges||[]).forEach(ae=>{f.addDummyNode($,"selfedge",{width:ae.label.width,height:ae.label.height,rank:ee.rank,order:J+ ++X,e:ae.e,label:ae.label},"_se")}),delete ee.selfEdges})})}function M($){$.nodes().forEach(U=>{var Z=$.node(U);if(Z.dummy==="selfedge"){var X=$.node(Z.e.v),te=X.x+X.width/2,J=X.y,ee=Z.x-te,ae=X.height/2;$.setEdge(Z.e,Z.label),$.removeNode(U),Z.label.points=[{x:te+2*ee/3,y:J-ae},{x:te+5*ee/6,y:J-ae},{x:te+ee,y:J},{x:te+5*ee/6,y:J+ae},{x:te+2*ee/3,y:J+ae}],Z.label.x=Z.x,Z.label.y=Z.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function q($){var U={};return $&&Object.entries($).forEach(([Z,X])=>{typeof Z=="string"&&(Z=Z.toLowerCase()),U[Z]=X}),U}return VJ}var HJ,S9e;function aBn(){if(S9e)return HJ;S9e=1;let e=Nl(),t=Ig().Graph;HJ={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 HJ}var WJ,k9e;function iBn(){return k9e||(k9e=1,WJ="1.1.8"),WJ}var ZJ,O9e;function oBn(){return O9e||(O9e=1,ZJ={graphlib:Ig(),layout:sBn(),debug:aBn(),util:{time:Nl().time,notime:Nl().notime},version:iBn()}),ZJ}var lBn=oBn();const _9e=jc(lBn);function Ml(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=Ml(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var cBn={value:()=>{}};function TV(){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 XF(n)}function XF(e){this._=e}function uBn(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}})}XF.prototype=TV.prototype={constructor:XF,on:function(e,t){var n=this._,r=uBn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=dBn(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]=C9e(n[s],e.name,t);else if(t==null)for(s in n)n[s]=C9e(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 XF(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 dBn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function C9e(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=cBn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var jhe="http://www.w3.org/1999/xhtml";const E9e={svg:"http://www.w3.org/2000/svg",xhtml:jhe,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function NV(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),E9e.hasOwnProperty(t)?{space:E9e[t],local:e}:e}function fBn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===jhe&&t.documentElement.namespaceURI===jhe?t.createElement(e):t.createElementNS(n,e)}}function pBn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function Vxt(e){var t=NV(e);return(t.local?pBn:fBn)(t)}function hBn(){}function m1e(e){return e==null?hBn:function(){return this.querySelector(e)}}function mBn(e){typeof e!="function"&&(e=m1e(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 Up(r,this._parents)}function gBn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function vBn(){return[]}function Hxt(e){return e==null?vBn:function(){return this.querySelectorAll(e)}}function yBn(e){return function(){return gBn(e.apply(this,arguments))}}function bBn(e){typeof e=="function"?e=yBn(e):e=Hxt(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 Up(r,s)}function Wxt(e){return function(){return this.matches(e)}}function Zxt(e){return function(t){return t.matches(e)}}var xBn=Array.prototype.find;function wBn(e){return function(){return xBn.call(this.children,e)}}function SBn(){return this.firstElementChild}function kBn(e){return this.select(e==null?SBn:wBn(typeof e=="function"?e:Zxt(e)))}var OBn=Array.prototype.filter;function _Bn(){return Array.from(this.children)}function CBn(e){return function(){return OBn.call(this.children,e)}}function EBn(e){return this.selectAll(e==null?_Bn:CBn(typeof e=="function"?e:Zxt(e)))}function jBn(e){typeof e!="function"&&(e=Wxt(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 Up(r,this._parents)}function Gxt(e){return new Array(e.length)}function TBn(){return new Up(this._enter||this._groups.map(Gxt),this._parents)}function N7(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}N7.prototype={constructor:N7,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 NBn(e){return function(){return e}}function IBn(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 N7(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function ABn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,p=new Array(d),h;for(l=0;l<d;++l)(c=t[l])&&(p[l]=h=i.call(c,c.__data__,l,t)+"",u.has(h)?s[l]=c:u.set(h,c));for(l=0;l<f;++l)h=i.call(e,a[l],l,a)+"",(c=u.get(h))?(r[l]=c,c.__data__=a[l],u.delete(h)):n[l]=new N7(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(p[l])===c&&(s[l]=c)}function RBn(e){return e.__data__}function PBn(e,t){if(!arguments.length)return Array.from(this,RBn);var n=t?ABn:IBn,r=this._parents,s=this._groups;typeof e!="function"&&(e=NBn(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],p=f.length,h=$Bn(e.call(d,d&&d.__data__,u,r)),m=h.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(p);n(d,f,v,y,b,h,t);for(var S=0,w=0,k,_;S<m;++S)if(k=v[S]){for(S>=w&&(w=S+1);!(_=y[w])&&++w<m;);k._next=_||null}}return i=new Up(i,r),i._enter=l,i._exit=c,i}function $Bn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function MBn(){return new Up(this._exit||this._groups.map(Gxt),this._parents)}function DBn(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 LBn(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,p=l[c]=new Array(f),h,m=0;m<f;++m)(h=u[m]||d[m])&&(p[m]=h);for(;c<s;++c)l[c]=n[c];return new Up(l,this._parents)}function FBn(){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 zBn(e){e||(e=BBn);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}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 Up(s,this._parents).order()}function BBn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function UBn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function qBn(){return Array.from(this)}function VBn(){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 HBn(){let e=0;for(const t of this)++e;return e}function WBn(){return!this.node()}function ZBn(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 GBn(e){return function(){this.removeAttribute(e)}}function QBn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function YBn(e,t){return function(){this.setAttribute(e,t)}}function XBn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function KBn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function JBn(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 eUn(e,t){var n=NV(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?QBn:GBn:typeof t=="function"?n.local?JBn:KBn:n.local?XBn:YBn)(n,t))}function Qxt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function tUn(e){return function(){this.style.removeProperty(e)}}function nUn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function rUn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function sUn(e,t,n){return arguments.length>1?this.each((t==null?tUn:typeof t=="function"?rUn:nUn)(e,t,n??"")):xT(this.node(),e)}function xT(e,t){return e.style.getPropertyValue(t)||Qxt(e).getComputedStyle(e,null).getPropertyValue(t)}function aUn(e){return function(){delete this[e]}}function iUn(e,t){return function(){this[e]=t}}function oUn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function lUn(e,t){return arguments.length>1?this.each((t==null?aUn:typeof t=="function"?oUn:iUn)(e,t)):this.node()[e]}function Yxt(e){return e.trim().split(/^|\s+/)}function g1e(e){return e.classList||new Xxt(e)}function Xxt(e){this._node=e,this._names=Yxt(e.getAttribute("class")||"")}Xxt.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 Kxt(e,t){for(var n=g1e(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function Jxt(e,t){for(var n=g1e(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function cUn(e){return function(){Kxt(this,e)}}function uUn(e){return function(){Jxt(this,e)}}function dUn(e,t){return function(){(t.apply(this,arguments)?Kxt:Jxt)(this,e)}}function fUn(e,t){var n=Yxt(e+"");if(arguments.length<2){for(var r=g1e(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?dUn:t?cUn:uUn)(n,t))}function pUn(){this.textContent=""}function hUn(e){return function(){this.textContent=e}}function mUn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function gUn(e){return arguments.length?this.each(e==null?pUn:(typeof e=="function"?mUn:hUn)(e)):this.node().textContent}function vUn(){this.innerHTML=""}function yUn(e){return function(){this.innerHTML=e}}function bUn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function xUn(e){return arguments.length?this.each(e==null?vUn:(typeof e=="function"?bUn:yUn)(e)):this.node().innerHTML}function wUn(){this.nextSibling&&this.parentNode.appendChild(this)}function SUn(){return this.each(wUn)}function kUn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function OUn(){return this.each(kUn)}function _Un(e){var t=typeof e=="function"?e:Vxt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function CUn(){return null}function EUn(e,t){var n=typeof e=="function"?e:Vxt(e),r=t==null?CUn:typeof t=="function"?t:m1e(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function jUn(){var e=this.parentNode;e&&e.removeChild(this)}function TUn(){return this.each(jUn)}function NUn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function IUn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function AUn(e){return this.select(e?IUn:NUn)}function RUn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function PUn(e){return function(t){e.call(this,t,this.__data__)}}function $Un(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 MUn(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 DUn(e,t,n){return function(){var r=this.__on,s,a=PUn(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 LUn(e,t,n){var r=$Un(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?DUn:MUn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function e0t(e,t,n){var r=Qxt(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 FUn(e,t){return function(){return e0t(this,e,t)}}function zUn(e,t){return function(){return e0t(this,e,t.apply(this,arguments))}}function BUn(e,t){return this.each((typeof t=="function"?zUn:FUn)(e,t))}function*UUn(){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 t0t=[null];function Up(e,t){this._groups=e,this._parents=t}function f3(){return new Up([[document.documentElement]],t0t)}function qUn(){return this}Up.prototype=f3.prototype={constructor:Up,select:mBn,selectAll:bBn,selectChild:kBn,selectChildren:EBn,filter:jBn,data:PBn,enter:TBn,exit:MBn,join:DBn,merge:LBn,selection:qUn,order:FBn,sort:zBn,call:UBn,nodes:qBn,node:VBn,size:HBn,empty:WBn,each:ZBn,attr:eUn,style:sUn,property:lUn,classed:fUn,text:gUn,html:xUn,raise:SUn,lower:OUn,append:_Un,insert:EUn,remove:TUn,clone:AUn,datum:RUn,on:LUn,dispatch:BUn,[Symbol.iterator]:UUn};function gp(e){return typeof e=="string"?new Up([[document.querySelector(e)]],[document.documentElement]):new Up([[e]],t0t)}function VUn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function eg(e,t){if(e=VUn(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 HUn={passive:!1},K$={capture:!0,passive:!1};function GJ(e){e.stopImmediatePropagation()}function kj(e){e.preventDefault(),e.stopImmediatePropagation()}function n0t(e){var t=e.document.documentElement,n=gp(e).on("dragstart.drag",kj,K$);"onselectstart"in t?n.on("selectstart.drag",kj,K$):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function r0t(e,t){var n=e.document.documentElement,r=gp(e).on("dragstart.drag",null);t&&(r.on("click.drag",kj,K$),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 S6=e=>()=>e;function The(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}})}The.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function WUn(e){return!e.ctrlKey&&!e.button}function ZUn(){return this.parentNode}function GUn(e,t){return t??{x:e.x,y:e.y}}function QUn(){return navigator.maxTouchPoints||"ontouchstart"in this}function s0t(){var e=WUn,t=ZUn,n=GUn,r=QUn,s={},a=TV("start","drag","end"),i=0,l,c,u,d,f=0;function p(k){k.on("mousedown.drag",h).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,HUn).on("touchend.drag touchcancel.drag",S).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function h(k,_){if(!(d||!e.call(this,k,_))){var C=w(this,t.call(this,k,_),k,_,"mouse");C&&(gp(k.view).on("mousemove.drag",m,K$).on("mouseup.drag",v,K$),n0t(k.view),GJ(k),u=!1,l=k.clientX,c=k.clientY,C("start",k))}}function m(k){if(kj(k),!u){var _=k.clientX-l,C=k.clientY-c;u=_*_+C*C>f}s.mouse("drag",k)}function v(k){gp(k.view).on("mousemove.drag mouseup.drag",null),r0t(k.view,u),kj(k),s.mouse("end",k)}function y(k,_){if(e.call(this,k,_)){var C=k.changedTouches,j=t.call(this,k,_),E=C.length,N,I;for(N=0;N<E;++N)(I=w(this,j,k,_,C[N].identifier,C[N]))&&(GJ(k),I("start",k,C[N]))}}function b(k){var _=k.changedTouches,C=_.length,j,E;for(j=0;j<C;++j)(E=s[_[j].identifier])&&(kj(k),E("drag",k,_[j]))}function S(k){var _=k.changedTouches,C=_.length,j,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),j=0;j<C;++j)(E=s[_[j].identifier])&&(GJ(k),E("end",k,_[j]))}function w(k,_,C,j,E,N){var I=a.copy(),A=eg(N||C,_),P,F,D;if((D=n.call(k,new The("beforestart",{sourceEvent:C,target:p,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),j))!=null)return P=D.x-A[0]||0,F=D.y-A[1]||0,function V(H,L,z){var B=A,M;switch(H){case"start":s[E]=V,M=i++;break;case"end":delete s[E],--i;case"drag":A=eg(z||L,_),M=i;break}I.call(H,k,new The(H,{sourceEvent:L,subject:D,target:p,identifier:E,active:M,x:A[0]+P,y:A[1]+F,dx:A[0]-B[0],dy:A[1]-B[1],dispatch:I}),j)}}return p.filter=function(k){return arguments.length?(e=typeof k=="function"?k:S6(!!k),p):e},p.container=function(k){return arguments.length?(t=typeof k=="function"?k:S6(k),p):t},p.subject=function(k){return arguments.length?(n=typeof k=="function"?k:S6(k),p):n},p.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:S6(!!k),p):r},p.on=function(){var k=a.on.apply(a,arguments);return k===a?p:k},p.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,p):Math.sqrt(f)},p}function v1e(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function a0t(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function p3(){}var J$=.7,I7=1/J$,Oj="\\s*([+-]?\\d+)\\s*",eM="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ey="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",YUn=/^#([0-9a-f]{3,8})$/,XUn=new RegExp(`^rgb\\(${Oj},${Oj},${Oj}\\)$`),KUn=new RegExp(`^rgb\\(${ey},${ey},${ey}\\)$`),JUn=new RegExp(`^rgba\\(${Oj},${Oj},${Oj},${eM}\\)$`),eqn=new RegExp(`^rgba\\(${ey},${ey},${ey},${eM}\\)$`),tqn=new RegExp(`^hsl\\(${eM},${ey},${ey}\\)$`),nqn=new RegExp(`^hsla\\(${eM},${ey},${ey},${eM}\\)$`),j9e={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};v1e(p3,RO,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:T9e,formatHex:T9e,formatHex8:rqn,formatHsl:sqn,formatRgb:N9e,toString:N9e});function T9e(){return this.rgb().formatHex()}function rqn(){return this.rgb().formatHex8()}function sqn(){return i0t(this).formatHsl()}function N9e(){return this.rgb().formatRgb()}function RO(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=YUn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?I9e(t):n===3?new nf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?k6(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?k6(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=XUn.exec(e))?new nf(t[1],t[2],t[3],1):(t=KUn.exec(e))?new nf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=JUn.exec(e))?k6(t[1],t[2],t[3],t[4]):(t=eqn.exec(e))?k6(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=tqn.exec(e))?P9e(t[1],t[2]/100,t[3]/100,1):(t=nqn.exec(e))?P9e(t[1],t[2]/100,t[3]/100,t[4]):j9e.hasOwnProperty(e)?I9e(j9e[e]):e==="transparent"?new nf(NaN,NaN,NaN,0):null}function I9e(e){return new nf(e>>16&255,e>>8&255,e&255,1)}function k6(e,t,n,r){return r<=0&&(e=t=n=NaN),new nf(e,t,n,r)}function aqn(e){return e instanceof p3||(e=RO(e)),e?(e=e.rgb(),new nf(e.r,e.g,e.b,e.opacity)):new nf}function Nhe(e,t,n,r){return arguments.length===1?aqn(e):new nf(e,t,n,r??1)}function nf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}v1e(nf,Nhe,a0t(p3,{brighter(e){return e=e==null?I7:Math.pow(I7,e),new nf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?J$:Math.pow(J$,e),new nf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new nf(Hk(this.r),Hk(this.g),Hk(this.b),A7(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:A9e,formatHex:A9e,formatHex8:iqn,formatRgb:R9e,toString:R9e}));function A9e(){return`#${Tk(this.r)}${Tk(this.g)}${Tk(this.b)}`}function iqn(){return`#${Tk(this.r)}${Tk(this.g)}${Tk(this.b)}${Tk((isNaN(this.opacity)?1:this.opacity)*255)}`}function R9e(){const e=A7(this.opacity);return`${e===1?"rgb(":"rgba("}${Hk(this.r)}, ${Hk(this.g)}, ${Hk(this.b)}${e===1?")":`, ${e})`}`}function A7(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Hk(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Tk(e){return e=Hk(e),(e<16?"0":"")+e.toString(16)}function P9e(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new ig(e,t,n,r)}function i0t(e){if(e instanceof ig)return new ig(e.h,e.s,e.l,e.opacity);if(e instanceof p3||(e=RO(e)),!e)return new ig;if(e instanceof ig)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 ig(i,l,c,e.opacity)}function oqn(e,t,n,r){return arguments.length===1?i0t(e):new ig(e,t,n,r??1)}function ig(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}v1e(ig,oqn,a0t(p3,{brighter(e){return e=e==null?I7:Math.pow(I7,e),new ig(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?J$:Math.pow(J$,e),new ig(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new nf(QJ(e>=240?e-240:e+120,s,r),QJ(e,s,r),QJ(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new ig($9e(this.h),O6(this.s),O6(this.l),A7(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=A7(this.opacity);return`${e===1?"hsl(":"hsla("}${$9e(this.h)}, ${O6(this.s)*100}%, ${O6(this.l)*100}%${e===1?")":`, ${e})`}`}}));function $9e(e){return e=(e||0)%360,e<0?e+360:e}function O6(e){return Math.max(0,Math.min(1,e||0))}function QJ(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 y1e=e=>()=>e;function lqn(e,t){return function(n){return e+n*t}}function cqn(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 uqn(e){return(e=+e)==1?o0t:function(t,n){return n-t?cqn(t,n,e):y1e(isNaN(t)?n:t)}}function o0t(e,t){var n=t-e;return n?lqn(e,n):y1e(isNaN(e)?t:e)}const R7=(function e(t){var n=uqn(t);function r(s,a){var i=n((s=Nhe(s)).r,(a=Nhe(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=o0t(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 dqn(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 fqn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function pqn(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]=sx(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 hqn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function ng(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function mqn(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]=sx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Ihe=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,YJ=new RegExp(Ihe.source,"g");function gqn(e){return function(){return e}}function vqn(e){return function(t){return e(t)+""}}function l0t(e,t){var n=Ihe.lastIndex=YJ.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Ihe.exec(e))&&(s=YJ.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:ng(r,s)})),n=YJ.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?vqn(c[0].x):gqn(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 sx(e,t){var n=typeof t,r;return t==null||n==="boolean"?y1e(t):(n==="number"?ng:n==="string"?(r=RO(t))?(t=r,R7):l0t:t instanceof RO?R7:t instanceof Date?hqn:fqn(t)?dqn:Array.isArray(t)?pqn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?mqn:ng)(e,t)}function b1e(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var M9e=180/Math.PI,Ahe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function c0t(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)*M9e,skewX:Math.atan(c)*M9e,scaleX:i,scaleY:l}}var _6;function yqn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Ahe:c0t(t.a,t.b,t.c,t.d,t.e,t.f)}function bqn(e){return e==null||(_6||(_6=document.createElementNS("http://www.w3.org/2000/svg","g")),_6.setAttribute("transform",e),!(e=_6.transform.baseVal.consolidate()))?Ahe:(e=e.matrix,c0t(e.a,e.b,e.c,e.d,e.e,e.f))}function u0t(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push("translate(",null,t,null,n);m.push({i:v-4,x:ng(u,f)},{i:v-2,x:ng(d,p)})}else(f||p)&&h.push("translate("+f+t+p+n)}function i(u,d,f,p){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),p.push({i:f.push(s(f)+"rotate(",null,r)-2,x:ng(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,p){u!==d?p.push({i:f.push(s(f)+"skewX(",null,r)-2,x:ng(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,p,h,m){if(u!==f||d!==p){var v=h.push(s(h)+"scale(",null,",",null,")");m.push({i:v-4,x:ng(u,f)},{i:v-2,x:ng(d,p)})}else(f!==1||p!==1)&&h.push(s(h)+"scale("+f+","+p+")")}return function(u,d){var f=[],p=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,p),i(u.rotate,d.rotate,f,p),l(u.skewX,d.skewX,f,p),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,p),u=d=null,function(h){for(var m=-1,v=p.length,y;++m<v;)f[(y=p[m]).i]=y.x(h);return f.join("")}}}var xqn=u0t(yqn,"px, ","px)","deg)"),wqn=u0t(bqn,", ",")",")"),Sqn=1e-12;function D9e(e){return((e=Math.exp(e))+1/e)/2}function kqn(e){return((e=Math.exp(e))-1/e)/2}function Oqn(e){return((e=Math.exp(2*e))-1)/(e+1)}const KF=(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],p=i[2],h=d-l,m=f-c,v=h*h+m*m,y,b;if(v<Sqn)b=Math.log(p/u)/t,y=function(j){return[l+j*h,c+j*m,u*Math.exp(t*j*b)]};else{var S=Math.sqrt(v),w=(p*p-u*u+r*v)/(2*u*n*S),k=(p*p-u*u-r*v)/(2*p*n*S),_=Math.log(Math.sqrt(w*w+1)-w),C=Math.log(Math.sqrt(k*k+1)-k);b=(C-_)/t,y=function(j){var E=j*b,N=D9e(_),I=u/(n*S)*(N*Oqn(t*E+_)-kqn(_));return[l+I*h,c+I*m,u*N/D9e(t*E+_)]}}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 _qn(e,t){t===void 0&&(t=e,e=sx);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 wT=0,o2=0,ZA=0,d0t=1e3,P7,l2,$7=0,PO=0,IV=0,tM=typeof performance=="object"&&performance.now?performance:Date,f0t=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function x1e(){return PO||(f0t(Cqn),PO=tM.now()+IV)}function Cqn(){PO=0}function M7(){this._call=this._time=this._next=null}M7.prototype=p0t.prototype={constructor:M7,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?x1e():+n)+(t==null?0:+t),!this._next&&l2!==this&&(l2?l2._next=this:P7=this,l2=this),this._call=e,this._time=n,Rhe()},stop:function(){this._call&&(this._call=null,this._time=1/0,Rhe())}};function p0t(e,t,n){var r=new M7;return r.restart(e,t,n),r}function Eqn(){x1e(),++wT;for(var e=P7,t;e;)(t=PO-e._time)>=0&&e._call.call(void 0,t),e=e._next;--wT}function L9e(){PO=($7=tM.now())+IV,wT=o2=0;try{Eqn()}finally{wT=0,Tqn(),PO=0}}function jqn(){var e=tM.now(),t=e-$7;t>d0t&&(IV-=t,$7=e)}function Tqn(){for(var e,t=P7,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:P7=n);l2=e,Rhe(r)}function Rhe(e){if(!wT){o2&&(o2=clearTimeout(o2));var t=e-PO;t>24?(e<1/0&&(o2=setTimeout(L9e,e-tM.now()-IV)),ZA&&(ZA=clearInterval(ZA))):(ZA||($7=tM.now(),ZA=setInterval(jqn,d0t)),wT=1,f0t(L9e))}}function F9e(e,t,n){var r=new M7;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var Nqn=TV("start","end","cancel","interrupt"),Iqn=[],h0t=0,z9e=1,Phe=2,JF=3,B9e=4,$he=5,e8=6;function AV(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;Aqn(e,n,{name:t,index:r,group:s,on:Nqn,tween:Iqn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:h0t})}function w1e(e,t){var n=Bg(e,t);if(n.state>h0t)throw new Error("too late; already scheduled");return n}function Dy(e,t){var n=Bg(e,t);if(n.state>JF)throw new Error("too late; already running");return n}function Bg(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function Aqn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=p0t(a,0,n.time);function a(u){n.state=z9e,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,p,h;if(n.state!==z9e)return c();for(d in r)if(h=r[d],h.name===n.name){if(h.state===JF)return F9e(i);h.state===B9e?(h.state=e8,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[d]):+d<t&&(h.state=e8,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[d])}if(F9e(function(){n.state===JF&&(n.state=B9e,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Phe,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Phe){for(n.state=JF,s=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(h=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=h);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=$he,1),f=-1,p=s.length;++f<p;)s[f].call(e,d);n.state===$he&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=e8,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function t8(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>Phe&&r.state<$he,r.state=e8,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function Rqn(e){return this.each(function(){t8(this,e)})}function Pqn(e,t){var n,r;return function(){var s=Dy(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 $qn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Dy(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 Mqn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Bg(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?Pqn:$qn)(n,e,t))}function S1e(e,t,n){var r=e._id;return e.each(function(){var s=Dy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return Bg(s,r).value[t]}}function m0t(e,t){var n;return(typeof t=="number"?ng:t instanceof RO?R7:(n=RO(t))?(t=n,R7):l0t)(e,t)}function Dqn(e){return function(){this.removeAttribute(e)}}function Lqn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function Fqn(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 zqn(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 Bqn(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 Uqn(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 qqn(e,t){var n=NV(e),r=n==="transform"?wqn:m0t;return this.attrTween(e,typeof t=="function"?(n.local?Uqn:Bqn)(n,r,S1e(this,"attr."+e,t)):t==null?(n.local?Lqn:Dqn)(n):(n.local?zqn:Fqn)(n,r,t))}function Vqn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function Hqn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function Wqn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&Hqn(e,a)),n}return s._value=t,s}function Zqn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&Vqn(e,a)),n}return s._value=t,s}function Gqn(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=NV(e);return this.tween(n,(r.local?Wqn:Zqn)(r,t))}function Qqn(e,t){return function(){w1e(this,e).delay=+t.apply(this,arguments)}}function Yqn(e,t){return t=+t,function(){w1e(this,e).delay=t}}function Xqn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Qqn:Yqn)(t,e)):Bg(this.node(),t).delay}function Kqn(e,t){return function(){Dy(this,e).duration=+t.apply(this,arguments)}}function Jqn(e,t){return t=+t,function(){Dy(this,e).duration=t}}function eVn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?Kqn:Jqn)(t,e)):Bg(this.node(),t).duration}function tVn(e,t){if(typeof t!="function")throw new Error;return function(){Dy(this,e).ease=t}}function nVn(e){var t=this._id;return arguments.length?this.each(tVn(t,e)):Bg(this.node(),t).ease}function rVn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Dy(this,e).ease=n}}function sVn(e){if(typeof e!="function")throw new Error;return this.each(rVn(this._id,e))}function aVn(e){typeof e!="function"&&(e=Wxt(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 Ox(r,this._parents,this._name,this._id)}function iVn(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),p,h=0;h<d;++h)(p=c[h]||u[h])&&(f[h]=p);for(;l<r;++l)i[l]=t[l];return new Ox(i,this._parents,this._name,this._id)}function oVn(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 lVn(e,t,n){var r,s,a=oVn(t)?w1e:Dy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function cVn(e,t){var n=this._id;return arguments.length<2?Bg(this.node(),n).on.on(e):this.each(lVn(n,e,t))}function uVn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function dVn(){return this.on("end.remove",uVn(this._id))}function fVn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=m1e(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,p=0;p<c;++p)(d=l[p])&&(f=e.call(d,d.__data__,p,l))&&("__data__"in d&&(f.__data__=d.__data__),u[p]=f,AV(u[p],t,n,p,u,Bg(d,n)));return new Ox(a,this._parents,t,n)}function pVn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=Hxt(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 p=e.call(d,d.__data__,f,c),h,m=Bg(d,n),v=0,y=p.length;v<y;++v)(h=p[v])&&AV(h,t,n,v,p,m);a.push(p),i.push(d)}return new Ox(a,i,t,n)}var hVn=f3.prototype.constructor;function mVn(){return new hVn(this._groups,this._parents)}function gVn(e,t){var n,r,s;return function(){var a=xT(this,e),i=(this.style.removeProperty(e),xT(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function g0t(e){return function(){this.style.removeProperty(e)}}function vVn(e,t,n){var r,s=n+"",a;return function(){var i=xT(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function yVn(e,t,n){var r,s,a;return function(){var i=xT(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),xT(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function bVn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Dy(this,e),u=c.on,d=c.value[a]==null?l||(l=g0t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function xVn(e,t,n){var r=(e+="")=="transform"?xqn:m0t;return t==null?this.styleTween(e,gVn(e,r)).on("end.style."+e,g0t(e)):typeof t=="function"?this.styleTween(e,yVn(e,r,S1e(this,"style."+e,t))).each(bVn(this._id,e)):this.styleTween(e,vVn(e,r,t),n).on("end.style."+e,null)}function wVn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function SVn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&wVn(e,i,n)),r}return a._value=t,a}function kVn(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,SVn(e,t,n??""))}function OVn(e){return function(){this.textContent=e}}function _Vn(e){return function(){var t=e(this);this.textContent=t??""}}function CVn(e){return this.tween("text",typeof e=="function"?_Vn(S1e(this,"text",e)):OVn(e==null?"":e+""))}function EVn(e){return function(t){this.textContent=e.call(this,t)}}function jVn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&EVn(s)),t}return r._value=e,r}function TVn(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,jVn(e))}function NVn(){for(var e=this._name,t=this._id,n=v0t(),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=Bg(c,t);AV(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Ox(r,this._parents,e,n)}function IVn(){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=Dy(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 AVn=0;function Ox(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function v0t(){return++AVn}var gb=f3.prototype;Ox.prototype={constructor:Ox,select:fVn,selectAll:pVn,selectChild:gb.selectChild,selectChildren:gb.selectChildren,filter:aVn,merge:iVn,selection:mVn,transition:NVn,call:gb.call,nodes:gb.nodes,node:gb.node,size:gb.size,empty:gb.empty,each:gb.each,on:cVn,attr:qqn,attrTween:Gqn,style:xVn,styleTween:kVn,text:CVn,textTween:TVn,remove:dVn,tween:Mqn,delay:Xqn,duration:eVn,ease:nVn,easeVarying:sVn,end:IVn,[Symbol.iterator]:gb[Symbol.iterator]};function RVn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var PVn={time:null,delay:0,duration:250,ease:RVn};function $Vn(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 MVn(e){var t,n;e instanceof Ox?(t=e._id,e=e._name):(t=v0t(),(n=PVn).time=x1e(),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])&&AV(c,e,t,u,i,n||$Vn(c,t));return new Ox(r,this._parents,e,t)}f3.prototype.interrupt=Rqn;f3.prototype.transition=MVn;const C6=e=>()=>e;function DVn(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 Wb(e,t,n){this.k=e,this.x=t,this.y=n}Wb.prototype={constructor:Wb,scale:function(e){return e===1?this:new Wb(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Wb(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 RV=new Wb(1,0,0);y0t.prototype=Wb.prototype;function y0t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return RV;return e.__zoom}function XJ(e){e.stopImmediatePropagation()}function GA(e){e.preventDefault(),e.stopImmediatePropagation()}function LVn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function FVn(){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 U9e(){return this.__zoom||RV}function zVn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function BVn(){return navigator.maxTouchPoints||"ontouchstart"in this}function UVn(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 b0t(){var e=LVn,t=FVn,n=UVn,r=zVn,s=BVn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=KF,u=TV("start","zoom","end"),d,f,p,h=500,m=150,v=0,y=10;function b(D){D.property("__zoom",U9e).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",P).on("touchend.zoom touchcancel.zoom",F).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,V,H,L){var z=D.selection?D.selection():D;z.property("__zoom",U9e),D!==z?_(D,V,H,L):z.interrupt().each(function(){C(this,arguments).event(L).start().zoom(null,typeof V=="function"?V.apply(this,arguments):V).end()})},b.scaleBy=function(D,V,H,L){b.scaleTo(D,function(){var z=this.__zoom.k,B=typeof V=="function"?V.apply(this,arguments):V;return z*B},H,L)},b.scaleTo=function(D,V,H,L){b.transform(D,function(){var z=t.apply(this,arguments),B=this.__zoom,M=H==null?k(z):typeof H=="function"?H.apply(this,arguments):H,G=B.invert(M),q=typeof V=="function"?V.apply(this,arguments):V;return n(w(S(B,q),M,G),z,i)},H,L)},b.translateBy=function(D,V,H,L){b.transform(D,function(){return n(this.__zoom.translate(typeof V=="function"?V.apply(this,arguments):V,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,L)},b.translateTo=function(D,V,H,L,z){b.transform(D,function(){var B=t.apply(this,arguments),M=this.__zoom,G=L==null?k(B):typeof L=="function"?L.apply(this,arguments):L;return n(RV.translate(G[0],G[1]).scale(M.k).translate(typeof V=="function"?-V.apply(this,arguments):-V,typeof H=="function"?-H.apply(this,arguments):-H),B,i)},L,z)};function S(D,V){return V=Math.max(a[0],Math.min(a[1],V)),V===D.k?D:new Wb(V,D.x,D.y)}function w(D,V,H){var L=V[0]-H[0]*D.k,z=V[1]-H[1]*D.k;return L===D.x&&z===D.y?D:new Wb(D.k,L,z)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function _(D,V,H,L){D.on("start.zoom",function(){C(this,arguments).event(L).start()}).on("interrupt.zoom end.zoom",function(){C(this,arguments).event(L).end()}).tween("zoom",function(){var z=this,B=arguments,M=C(z,B).event(L),G=t.apply(z,B),q=H==null?k(G):typeof H=="function"?H.apply(z,B):H,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=z.__zoom,Z=typeof V=="function"?V.apply(z,B):V,X=c(U.invert(q).concat($/U.k),Z.invert(q).concat($/Z.k));return function(te){if(te===1)te=Z;else{var J=X(te),ee=$/J[2];te=new Wb(ee,q[0]-J[0]*ee,q[1]-J[1]*ee)}M.zoom(null,te)}})}function C(D,V,H){return!H&&D.__zooming||new j(D,V)}function j(D,V){this.that=D,this.args=V,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,V),this.taps=0}j.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,V){return this.mouse&&D!=="mouse"&&(this.mouse[1]=V.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=V.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=V.invert(this.touch1[0])),this.that.__zoom=V,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var V=gp(this.that).datum();u.call(D,this.that,new DVn(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),V)}};function E(D,...V){if(!e.apply(this,arguments))return;var H=C(this,V).event(D),L=this.__zoom,z=Math.max(a[0],Math.min(a[1],L.k*Math.pow(2,r.apply(this,arguments)))),B=eg(D);if(H.wheel)(H.mouse[0][0]!==B[0]||H.mouse[0][1]!==B[1])&&(H.mouse[1]=L.invert(H.mouse[0]=B)),clearTimeout(H.wheel);else{if(L.k===z)return;H.mouse=[B,L.invert(B)],t8(this),H.start()}GA(D),H.wheel=setTimeout(M,m),H.zoom("mouse",n(w(S(L,z),H.mouse[0],H.mouse[1]),H.extent,i));function M(){H.wheel=null,H.end()}}function N(D,...V){if(p||!e.apply(this,arguments))return;var H=D.currentTarget,L=C(this,V,!0).event(D),z=gp(D.view).on("mousemove.zoom",q,!0).on("mouseup.zoom",$,!0),B=eg(D,H),M=D.clientX,G=D.clientY;n0t(D.view),XJ(D),L.mouse=[B,this.__zoom.invert(B)],t8(this),L.start();function q(U){if(GA(U),!L.moved){var Z=U.clientX-M,X=U.clientY-G;L.moved=Z*Z+X*X>v}L.event(U).zoom("mouse",n(w(L.that.__zoom,L.mouse[0]=eg(U,H),L.mouse[1]),L.extent,i))}function $(U){z.on("mousemove.zoom mouseup.zoom",null),r0t(U.view,L.moved),GA(U),L.event(U).end()}}function I(D,...V){if(e.apply(this,arguments)){var H=this.__zoom,L=eg(D.changedTouches?D.changedTouches[0]:D,this),z=H.invert(L),B=H.k*(D.shiftKey?.5:2),M=n(w(S(H,B),L,z),t.apply(this,V),i);GA(D),l>0?gp(this).transition().duration(l).call(_,M,L,D):gp(this).call(b.transform,M,L,D)}}function A(D,...V){if(e.apply(this,arguments)){var H=D.touches,L=H.length,z=C(this,V,D.changedTouches.length===L).event(D),B,M,G,q;for(XJ(D),M=0;M<L;++M)G=H[M],q=eg(G,this),q=[q,this.__zoom.invert(q),G.identifier],z.touch0?!z.touch1&&z.touch0[2]!==q[2]&&(z.touch1=q,z.taps=0):(z.touch0=q,B=!0,z.taps=1+!!d);d&&(d=clearTimeout(d)),B&&(z.taps<2&&(f=q[0],d=setTimeout(function(){d=null},h)),t8(this),z.start())}}function P(D,...V){if(this.__zooming){var H=C(this,V).event(D),L=D.changedTouches,z=L.length,B,M,G,q;for(GA(D),B=0;B<z;++B)M=L[B],G=eg(M,this),H.touch0&&H.touch0[2]===M.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===M.identifier&&(H.touch1[0]=G);if(M=H.that.__zoom,H.touch1){var $=H.touch0[0],U=H.touch0[1],Z=H.touch1[0],X=H.touch1[1],te=(te=Z[0]-$[0])*te+(te=Z[1]-$[1])*te,J=(J=X[0]-U[0])*J+(J=X[1]-U[1])*J;M=S(M,Math.sqrt(te/J)),G=[($[0]+Z[0])/2,($[1]+Z[1])/2],q=[(U[0]+X[0])/2,(U[1]+X[1])/2]}else if(H.touch0)G=H.touch0[0],q=H.touch0[1];else return;H.zoom("touch",n(w(M,G,q),H.extent,i))}}function F(D,...V){if(this.__zooming){var H=C(this,V).event(D),L=D.changedTouches,z=L.length,B,M;for(XJ(D),p&&clearTimeout(p),p=setTimeout(function(){p=null},h),B=0;B<z;++B)M=L[B],H.touch0&&H.touch0[2]===M.identifier?delete H.touch0:H.touch1&&H.touch1[2]===M.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(M=eg(M,this),Math.hypot(f[0]-M[0],f[1]-M[1])<y)){var G=gp(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:C6(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:C6(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:C6(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:C6([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const my={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."},nM=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],x0t=["Enter"," ","Escape"],w0t={"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 ST;(function(e){e.Strict="strict",e.Loose="loose"})(ST||(ST={}));var Wk;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Wk||(Wk={}));var rM;(function(e){e.Partial="partial",e.Full="full"})(rM||(rM={}));const S0t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var aw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(aw||(aw={}));var sM;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(sM||(sM={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const q9e={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function k0t(e){return e===null?null:e?"valid":"invalid"}const O0t=e=>"id"in e&&"source"in e&&"target"in e,qVn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),k1e=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),h3=(e,t=[0,0])=>{const{width:n,height:r}=Zx(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},VVn=(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):k1e(s)?s:t.nodeLookup.get(s.id));const l=i?D7(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return PV(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return $V(n)},m3=(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=PV(n,D7(s)),r=!0)}),r?$V(n):{x:0,y:0,width:0,height:0}},O1e=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...v3(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:p=!1}=u;if(i&&!f||p)continue;const h=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=aM(l,OT(u)),y=(h??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},HVn=(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 WVn(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 ZVn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=WVn(e,i),c=m3(l),u=_1e(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 _0t({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",my.error005());else{const h=l.measured.width,m=l.measured.height;h&&m&&(f=[[c,u],[c+h,u+m]])}else l&&_T(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const p=_T(f)?$O(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",my.error015()),{position:{x:p.x-c+(i.measured.width??0)*d[0],y:p.y-u+(i.measured.height??0)*d[1]},positionAbsolute:p}}async function GVn({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(p=>p.id)),i=[];for(const p of n){if(p.deletable===!1)continue;const h=a.has(p.id),m=!h&&p.parentId&&i.find(v=>v.id===p.parentId);(h||m)&&i.push(p)}const l=new Set(t.map(p=>p.id)),c=r.filter(p=>p.deletable!==!1),d=HVn(i,c);for(const p of c)l.has(p.id)&&!d.find(m=>m.id===p.id)&&d.push(p);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 kT=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),$O=(e={x:0,y:0},t,n)=>({x:kT(e.x,t[0][0],t[1][0]-(n?.width??0)),y:kT(e.y,t[0][1],t[1][1]-(n?.height??0))});function C0t(e,t,n){const{width:r,height:s}=Zx(n),{x:a,y:i}=n.internals.positionAbsolute;return $O(e,[[a,i],[a+r,i+s]],t)}const V9e=(e,t,n)=>e<t?kT(Math.abs(e-t),1,t)/t:e>n?-kT(Math.abs(e-n),1,t)/t:0,E0t=(e,t,n=15,r=40)=>{const s=V9e(e.x,r,t.width-r)*n,a=V9e(e.y,r,t.height-r)*n;return[s,a]},PV=(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)}),Mhe=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),$V=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),OT=(e,t=[0,0])=>{const{x:n,y:r}=k1e(e)?e.internals.positionAbsolute:h3(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}},D7=(e,t=[0,0])=>{const{x:n,y:r}=k1e(e)?e.internals.positionAbsolute:h3(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)}},j0t=(e,t)=>$V(PV(Mhe(e),Mhe(t))),aM=(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)},H9e=e=>fg(e.width)&&fg(e.height)&&fg(e.x)&&fg(e.y),fg=e=>!isNaN(e)&&isFinite(e),QVn=(e,t)=>{},g3=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),v3=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?g3(l,i):l},L7=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function zC(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 YVn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=zC(e,n),s=zC(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=zC(e.top??e.y??0,n),s=zC(e.bottom??e.y??0,n),a=zC(e.left??e.x??0,t),i=zC(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 XVn(e,t,n,r,s,a){const{x:i,y:l}=L7(e,[t,n,r]),{x:c,y:u}=L7({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 _1e=(e,t,n,r,s,a)=>{const i=YVn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=kT(u,r,s),f=e.x+e.width/2,p=e.y+e.height/2,h=t/2-f*d,m=n/2-p*d,v=XVn(e,h,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:h-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},iM=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function _T(e){return e!=null&&e!=="parent"}function Zx(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function T0t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function N0t(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 W9e(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function KVn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function JVn(e){return{...w0t,...e||{}}}function U2(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=pg(e),l=v3({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?g3(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const C1e=e=>({width:e.offsetWidth,height:e.offsetHeight}),I0t=e=>e?.getRootNode?.()||window?.document,eHn=["INPUT","SELECT","TEXTAREA"];function A0t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:eHn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const R0t=e=>"clientX"in e,pg=(e,t)=>{const n=R0t(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)}},Z9e=(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,...C1e(i)}})};function P0t({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 E6(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function G9e({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-E6(t-r,a),n];case nr.Right:return[t+E6(r-t,a),n];case nr.Top:return[t,n-E6(n-s,a)];case nr.Bottom:return[t,n+E6(s-n,a)]}}function E1e({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=G9e({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=G9e({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,p,h,m]=P0t({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,p,h,m]}function $0t({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 tHn({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 nHn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=PV(D7(e),D7(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 aM(i,$V(a))>0}const rHn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,sHn=(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)),aHn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||rHn;let s;return O0t(e)?s={...e}:s={...e,id:r(e)},sHn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function M0t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=$0t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const Q9e={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},iHn=({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},Y9e=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function oHn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=Q9e[t],c=Q9e[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=iHn({source:u,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",h=f[p];let m=[],v,y;const b={x:0,y:0},S={x:0,y:0},[,,w,k]=$0t({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[p]*c[p]===-1){p==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[p]===h?m=p==="x"?E:N:m=p==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(p==="x"?m=l.x===h?N:E:m=l.y===h?E:N,t===r){const D=Math.abs(e[p]-n[p]);if(D<=a){const V=Math.min(a-1,a-D);l[p]===h?b[p]=(u[p]>e[p]?-1:1)*V:S[p]=(d[p]>n[p]?-1:1)*V}}if(t!==r){const D=p==="x"?"y":"x",V=l[p]===c[D],H=u[D]>d[D],L=u[D]<d[D];(l[p]===1&&(!V&&H||V&&L)||l[p]!==1&&(!V&&L||V&&H))&&(m=p==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+S.x,y:d.y+S.y},P=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),F=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));P>=F?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const _={x:u.x+b.x,y:u.y+b.y},C={x:d.x+S.x,y:d.y+S.y};return[[e,..._.x!==m[0].x||_.y!==m[0].y?[_]:[],...m,...C.x!==m[m.length-1].x||C.y!==m[m.length-1].y?[C]:[],n],v,y,w,k]}function lHn(e,t,n,r){const s=Math.min(Y9e(e,t)/2,Y9e(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 Dhe({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,p,h,m,v]=oHn({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+=lHn(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,p,h,m,v]}function X9e(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function cHn(e){const{sourceNode:t,targetNode:n}=e;if(!X9e(t)||!X9e(n))return null;const r=t.internals.handleBounds||K9e(t.handles),s=n.internals.handleBounds||K9e(n.handles),a=J9e(r?.source??[],e.sourceHandle),i=J9e(e.connectionMode===ST.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",my.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=MO(t,a,l),d=MO(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function K9e(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 MO(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??Zx(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 J9e(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Lhe(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function uHn(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=Lhe(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 D0t=1e3,dHn=10,j1e={nodeOrigin:[0,0],nodeExtent:nM,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},fHn={...j1e,checkEquality:!0};function T1e(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function pHn(e,t,n){const r=T1e(j1e,n);for(const s of e.values())if(s.parentId)I1e(s,e,t,r);else{const a=h3(s,r.nodeOrigin),i=_T(s.extent)?s.extent:r.nodeExtent,l=$O(a,i,Zx(s));s.internals.positionAbsolute=l}}function hHn(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 N1e(e){return e==="manual"}function Fhe(e,t,n,r={}){const s=T1e(fHn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!N1e(s.zIndexMode)?D0t: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 p=h3(d,s.nodeOrigin),h=_T(d.extent)?d.extent:s.nodeExtent,m=$O(p,h,Zx(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:hHn(d,f),z:L0t(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&&I1e(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function mHn(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 I1e(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=T1e(j1e,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}mHn(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*dHn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!N1e(c)?D0t:0,{x:p,y:h,z:m}=gHn(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=p!==v.x||h!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:p,y:h}:v,z:m}})}function L0t(e,t,n){const r=fg(e.zIndex)?e.zIndex:0;return N1e(n)?r:r+(e.selected?t:0)}function gHn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=Zx(e),u=h3(e,n),d=_T(e.extent)?$O(u,e.extent,c):u;let f=$O({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=C0t(f,c,t));const p=L0t(e,s,a),h=t.internals.z??0;return{x:f.x,y:f.y,z:h>=p?h+1:p}}function A1e(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??OT(l),u=j0t(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=Zx(l),f=l.origin??r,p=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,h=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];(p>0||h>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-p+y,y:l.position.y-h+b}}),n.get(c)?.forEach(S=>{e.some(w=>w.id===S.id)||s.push({id:S.id,type:"position",position:{x:S.position.x+p,y:S.position.y+h}})})),(d.width<i.width||d.height<i.height||p||h)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(p?f[0]*p-y:0),height:v+(h?f[1]*h-b:0)}})}),s}function vHn(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),p=[];for(const h of e.values()){const m=t.get(h.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=C1e(h.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||h.force))){const S=h.nodeElement.getBoundingClientRect(),w=_T(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=C0t(k,v,t.get(m.parentId)):w&&(k=$O(k,w,v));const _={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:Z9e("source",h.nodeElement,S,f,m.id),target:Z9e("target",h.nodeElement,S,f,m.id)}}};t.set(m.id,_),m.parentId&&I1e(_,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&p.push({id:m.id,parentId:m.parentId,rect:OT(_,s)}))}}if(p.length>0){const h=A1e(p,t,n,s);u.push(...h)}return{changes:u,updatedInternals:c}}async function yHn({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 eFe(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 F0t(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}`;eFe("source",c,d,e,s,i),eFe("target",c,u,e,a,l),t.set(r.id,r)}}function z0t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:z0t(n,t):!1}function tFe(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 bHn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!z0t(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 KJ({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 xHn({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=g3(a,t);return{x:i.x-a.x,y:i.y-a.y}}function wHn({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,p=null,h=!1,m=!1,v=null;function y({noDragClassName:S,handleSelector:w,domNode:k,isSelectable:_,nodeId:C,nodeClickDistance:j=0}){p=gp(k);function E({x:P,y:F}){const{nodeLookup:D,nodeExtent:V,snapGrid:H,snapToGrid:L,nodeOrigin:z,onNodeDrag:B,onSelectionDrag:M,onError:G,updateNodePositions:q}=t();a={x:P,y:F};let $=!1;const U=l.size>1,Z=U&&V?Mhe(m3(l)):null,X=U&&L?xHn({dragItems:l,snapGrid:H,x:P,y:F}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:P-J.distance.x,y:F-J.distance.y};L&&(ee=X?{x:Math.round(ee.x+X.x),y:Math.round(ee.y+X.y)}:g3(ee,H));let ae=null;if(U&&V&&!J.extent&&Z){const{positionAbsolute:ne}=J.internals,ue=ne.x-Z.x+V[0][0],pe=ne.x+J.measured.width-Z.x2+V[1][0],oe=ne.y-Z.y+V[0][1],ve=ne.y+J.measured.height-Z.y2+V[1][1];ae=[[ue,oe],[pe,ve]]}const{position:ce,positionAbsolute:Y}=_0t({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:ae||V,nodeOrigin:z,onError:G});$=$||J.position.x!==ce.x||J.position.y!==ce.y,J.position=ce,J.internals.positionAbsolute=Y}if(m=m||$,!!$&&(q(l,!0),v&&(r||B||!C&&M))){const[te,J]=KJ({nodeId:C,dragItems:l,nodeLookup:D});r?.(v,l,te,J),B?.(v,te,J),C||M?.(v,J)}}async function N(){if(!d)return;const{transform:P,panBy:F,autoPanSpeed:D,autoPanOnNodeDrag:V}=t();if(!V){c=!1,cancelAnimationFrame(i);return}const[H,L]=E0t(u,d,D);(H!==0||L!==0)&&(a.x=(a.x??0)-H/P[2],a.y=(a.y??0)-L/P[2],await F({x:H,y:L})&&E(a)),i=requestAnimationFrame(N)}function I(P){const{nodeLookup:F,multiSelectionActive:D,nodesDraggable:V,transform:H,snapGrid:L,snapToGrid:z,selectNodesOnDrag:B,onNodeDragStart:M,onSelectionDragStart:G,unselectNodesAndEdges:q}=t();f=!0,(!B||!_)&&!D&&C&&(F.get(C)?.selected||q()),_&&B&&C&&e?.(C);const $=U2(P.sourceEvent,{transform:H,snapGrid:L,snapToGrid:z,containerBounds:d});if(a=$,l=bHn(F,V,$,C),l.size>0&&(n||M||!C&&G)){const[U,Z]=KJ({nodeId:C,dragItems:l,nodeLookup:F});n?.(P.sourceEvent,l,U,Z),M?.(P.sourceEvent,U,Z),C||G?.(P.sourceEvent,Z)}}const A=s0t().clickDistance(j).on("start",P=>{const{domNode:F,nodeDragThreshold:D,transform:V,snapGrid:H,snapToGrid:L}=t();d=F?.getBoundingClientRect()||null,h=!1,m=!1,v=P.sourceEvent,D===0&&I(P),a=U2(P.sourceEvent,{transform:V,snapGrid:H,snapToGrid:L,containerBounds:d}),u=pg(P.sourceEvent,d)}).on("drag",P=>{const{autoPanOnNodeDrag:F,transform:D,snapGrid:V,snapToGrid:H,nodeDragThreshold:L,nodeLookup:z}=t(),B=U2(P.sourceEvent,{transform:D,snapGrid:V,snapToGrid:H,containerBounds:d});if(v=P.sourceEvent,(P.sourceEvent.type==="touchmove"&&P.sourceEvent.touches.length>1||C&&!z.has(C))&&(h=!0),!h){if(!c&&F&&f&&(c=!0,N()),!f){const M=pg(P.sourceEvent,d),G=M.x-u.x,q=M.y-u.y;Math.sqrt(G*G+q*q)>L&&I(P)}(a.x!==B.xSnapped||a.y!==B.ySnapped)&&l&&f&&(u=pg(P.sourceEvent,d),E(B))}}).on("end",P=>{if(!(!f||h)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:F,updateNodePositions:D,onNodeDragStop:V,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||V||!C&&H){const[L,z]=KJ({nodeId:C,dragItems:l,nodeLookup:F,dragging:!1});s?.(P.sourceEvent,l,L,z),V?.(P.sourceEvent,L,z),C||H?.(P.sourceEvent,z)}}}).filter(P=>{const F=P.target;return!P.button&&(!S||!tFe(F,`.${S}`,k))&&(!w||tFe(F,w,k))});p.call(A)}function b(){p?.on(".drag",null)}return{update:y,destroy:b}}function SHn(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())aM(s,OT(a))>0&&r.push(a);return r}const kHn=250;function OHn(e,t,n,r){let s=[],a=1/0;const i=SHn(e,n,t+kHn);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}=MO(l,u,u.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(s=[{...u,x:d,y:f}],a=p):p===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 B0t(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,...MO(i,c,c.position,!0)}:c}function U0t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function _Hn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const q0t=()=>!0;function CHn(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:h,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=q0t,onReconnectEnd:S,updateConnection:w,getTransform:k,getFromHandle:_,autoPanSpeed:C,dragThreshold:j=1,handleDomNode:E}){const N=I0t(e.target);let I=0,A;const{x:P,y:F}=pg(e),D=U0t(a,E),V=l?.getBoundingClientRect();let H=!1;if(!V||!D)return;const L=B0t(s,D,r,c,t);if(!L)return;let z=pg(e,V),B=!1,M=null,G=!1,q=null;function $(){if(!d||!V)return;const[ce,Y]=E0t(z,V,C);p({x:ce,y:Y}),I=requestAnimationFrame($)}const U={...L,nodeId:s,type:D,position:L.position},Z=c.get(s);let te={inProgress:!0,isValid:null,from:MO(Z,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:Z,to:z,toHandle:null,toPosition:q9e[U.position],toNode:null,pointer:z};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}j===0&&J();function ee(ce){if(!H){const{x:ve,y:ye}=pg(ce),Se=ve-P,Ne=ye-F;if(!(Se*Se+Ne*Ne>j*j))return;J()}if(!_()||!U){ae(ce);return}const Y=k();z=pg(ce,V),A=OHn(v3(z,Y,!1,[1,1]),n,c,U),B||($(),B=!0);const ne=V0t(ce,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});q=ne.handleDomNode,M=ne.connection,G=_Hn(!!A,ne.isValid);const ue=c.get(s),pe=ue?MO(ue,U,nr.Left,!0):te.from,oe={...te,from:pe,isValid:G,to:ne.toHandle&&G?L7({x:ne.toHandle.x,y:ne.toHandle.y},Y):z,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:q9e[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:z};w(oe),te=oe}function ae(ce){if(!("touches"in ce&&ce.touches.length>0)){if(H){(A||q)&&M&&G&&v?.(M);const{inProgress:Y,...ne}=te,ue={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ce,ue),a&&S?.(ce,ue)}h(),cancelAnimationFrame(I),B=!1,G=!1,M=null,q=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",ae),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",ae)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",ae),N.addEventListener("touchmove",ee),N.addEventListener("touchend",ae)}function V0t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=q0t,nodeLookup:d}){const f=a==="target",p=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:h,y:m}=pg(e),v=i.elementFromPoint(h,m),y=v?.classList.contains(`${l}-flow__handle`)?v:p,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const S=U0t(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),_=y.classList.contains("connectable"),C=y.classList.contains("connectableend");if(!w||!S)return b;const j={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=j;const N=_&&C&&(n===ST.Strict?f&&S==="source"||!f&&S==="target":w!==r||k!==s);b.isValid=N&&u(j),b.toHandle=B0t(w,S,k,d,n,!0)}return b}const zhe={onPointerDown:CHn,isValid:V0t};function EHn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=gp(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:h=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),_=w.sourceEvent.ctrlKey&&iM()?10:1,C=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,j=k[2]*Math.pow(2,C*_);t.scaleTo(j)};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 _=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],C=[_[0]-v[0],_[1]-v[1]];v=_;const j=r()*Math.max(k[2],Math.log(k[2]))*(h?-1:1),E={x:k[0]-C[0]*j,y:k[1]-C[1]*j},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},S=b0t().on("start",y).on("zoom",f?b:null).on("zoom.wheel",p?m:null);s.call(S,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:eg}}const MV=e=>({x:e.x,y:e.y,zoom:e.k}),JJ=({x:e,y:t,zoom:n})=>RV.translate(e,t).scale(n),qE=(e,t)=>e.target.closest(`.${t}`),H0t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),jHn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,eee=(e,t=0,n=jHn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},W0t=e=>{const t=e.ctrlKey&&iM()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function THn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(qE(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=eg(d),b=W0t(d),S=f*Math.pow(2,b);r.scaleTo(n,S,y,d);return}const p=d.deltaMode===1?20:1;let h=s===Wk.Vertical?0:d.deltaX*p,m=s===Wk.Horizontal?0:d.deltaY*p;!iM()&&d.shiftKey&&s!==Wk.Vertical&&(h=d.deltaY*p,m=0),r.translateBy(n,-(h/f)*a,-(m/f)*a,{internal:!0});const v=MV(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 NHn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=qE(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function IHn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=MV(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 AHn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&H0t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,MV(a.transform))}}function RHn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&H0t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=MV(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function PHn({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 p=e||t,h=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(qE(f,`${u}-flow__node`)||qE(f,`${u}-flow__edge`)))return!0;if(!r&&!p&&!s&&!a&&!n||i||d&&!m||qE(f,l)&&m||qE(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(!p&&!s&&!h&&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 $Hn({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=b0t().scaleExtent([t,n]).translateExtent(r),p=gp(e).call(f);S({x:s.x,y:s.y,zoom:kT(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const h=p.on("wheel.zoom"),m=p.on("dblclick.zoom");f.wheelDelta(W0t);function v(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).transform(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:P,onPaneContextMenu:F,userSelectionActive:D,panOnScroll:V,panOnDrag:H,panOnScrollMode:L,panOnScrollSpeed:z,preventScrolling:B,zoomOnPinch:M,zoomOnScroll:G,zoomOnDoubleClick:q,zoomActivationKeyPressed:$,lib:U,onTransformChange:Z,connectionInProgress:X,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=V&&!$&&!D;f.clickDistance(J?1/0:!fg(te)||te<0?0:te);const ae=ee?THn({zoomPanValues:u,noWheelClassName:A,d3Selection:p,d3Zoom:f,panOnScrollMode:L,panOnScrollSpeed:z,zoomOnPinch:M,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):NHn({noWheelClassName:A,preventScrolling:B,d3ZoomHandler:h});if(p.on("wheel.zoom",ae,{passive:!1}),!D){const Y=IHn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",Y);const ne=AHn({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!F,onPanZoom:a,onTransformChange:Z});f.on("zoom",ne);const ue=RHn({zoomPanValues:u,panOnDrag:H,panOnScroll:V,onPaneContextMenu:F,onPanZoomEnd:l,onDraggingChange:c});f.on("end",ue)}const ce=PHn({zoomActivationKeyPressed:$,panOnDrag:H,zoomOnScroll:G,panOnScroll:V,zoomOnDoubleClick:q,zoomOnPinch:M,userSelectionActive:D,noPanClassName:P,noWheelClassName:A,lib:U,connectionInProgress:X});f.filter(ce),q?p.on("dblclick.zoom",m):p.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function S(A,P,F){const D=JJ(A),V=f?.constrain()(D,P,F);return V&&await v(V),new Promise(H=>H(V))}async function w(A,P){const F=JJ(A);return await v(F,P),new Promise(D=>D(F))}function k(A){if(p){const P=JJ(A),F=p.property("__zoom");(F.k!==A.zoom||F.x!==A.x||F.y!==A.y)&&f?.transform(p,P,null,{sync:!0})}}function _(){const A=p?y0t(p.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function C(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).scaleTo(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function j(A,P){return p?new Promise(F=>{f?.interpolate(P?.interpolate==="linear"?sx:KF).scaleBy(eee(p,P?.duration,P?.ease,()=>F(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const P=!fg(A)||A<0?0:A;f?.clickDistance(P)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:S,getViewport:_,scaleTo:C,scaleBy:j,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var CT;(function(e){e.Line="line",e.Handle="handle"})(CT||(CT={}));function MHn({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 nFe(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 L0(e,t){return Math.max(0,t-e)}function F0(e,t){return Math.max(0,e-t)}function j6(e,t,n){return Math.max(0,t-e,e-n)}function rFe(e,t){return e?!t:t}function DHn(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:h,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:S}=r,{x:w,y:k,width:_,height:C,aspectRatio:j}=e;let E=Math.floor(d?h-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=_+(c?-E:E),A=C+(u?-N:N),P=-a[0]*_,F=-a[1]*C;let D=j6(I,v,y),V=j6(A,b,S);if(i){let z=0,B=0;c&&E<0?z=L0(w+E+P,i[0][0]):!c&&E>0&&(z=F0(w+I+P,i[1][0])),u&&N<0?B=L0(k+N+F,i[0][1]):!u&&N>0&&(B=F0(k+A+F,i[1][1])),D=Math.max(D,z),V=Math.max(V,B)}if(l){let z=0,B=0;c&&E>0?z=F0(w+E,l[0][0]):!c&&E<0&&(z=L0(w+I,l[1][0])),u&&N>0?B=F0(k+N,l[0][1]):!u&&N<0&&(B=L0(k+A,l[1][1])),D=Math.max(D,z),V=Math.max(V,B)}if(s){if(d){const z=j6(I/j,b,S)*j;if(D=Math.max(D,z),i){let B=0;!c&&!u||c&&!u&&p?B=F0(k+F+I/j,i[1][1])*j:B=L0(k+F+(c?E:-E)/j,i[0][1])*j,D=Math.max(D,B)}if(l){let B=0;!c&&!u||c&&!u&&p?B=L0(k+I/j,l[1][1])*j:B=F0(k+(c?E:-E)/j,l[0][1])*j,D=Math.max(D,B)}}if(f){const z=j6(A*j,v,y)/j;if(V=Math.max(V,z),i){let B=0;!c&&!u||u&&!c&&p?B=F0(w+A*j+P,i[1][0])/j:B=L0(w+(u?N:-N)*j+P,i[0][0])/j,V=Math.max(V,B)}if(l){let B=0;!c&&!u||u&&!c&&p?B=L0(w+A*j,l[1][0])/j:B=F0(w+(u?N:-N)*j,l[0][0])/j,V=Math.max(V,B)}}}N=N+(N<0?V:-V),E=E+(E<0?D:-D),s&&(p?I>A*j?N=(rFe(c,u)?-E:E)/j:E=(rFe(c,u)?-N:N)*j:d?(N=E/j,u=c):(E=N*j,c=u));const H=c?w+E:w,L=u?k+N:k;return{width:_+(c?-E:E),height:C+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+L}}const Z0t={width:0,height:0,x:0,y:0},LHn={...Z0t,pointerX:0,pointerY:0,aspectRatio:1};function FHn(e){return[[0,0],[e.measured.width,e.measured.height]]}function zHn(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 BHn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=gp(e);let i={controlDirection:nFe("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:p,onResizeStart:h,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...Z0t},S={...LHn};i={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:nFe(u)};let w,k=null,_=[],C,j,E,N=!1;const I=s0t().on("start",A=>{const{nodeLookup:P,transform:F,snapGrid:D,snapToGrid:V,nodeOrigin:H,paneDomNode:L}=n();if(w=P.get(t),!w)return;k=L?.getBoundingClientRect()??null;const{xSnapped:z,ySnapped:B}=U2(A.sourceEvent,{transform:F,snapGrid:D,snapToGrid:V,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},S={...b,pointerX:z,pointerY:B,aspectRatio:b.width/b.height},C=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(C=P.get(w.parentId),j=C&&w.extent==="parent"?FHn(C):void 0),_=[],E=void 0;for(const[M,G]of P)if(G.parentId===t&&(_.push({id:M,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const q=zHn(G,w,G.origin??H);E?E=[[Math.min(q[0][0],E[0][0]),Math.min(q[0][1],E[0][1])],[Math.max(q[1][0],E[1][0]),Math.max(q[1][1],E[1][1])]]:E=q}h?.(A,{...b})}).on("drag",A=>{const{transform:P,snapGrid:F,snapToGrid:D,nodeOrigin:V}=n(),H=U2(A.sourceEvent,{transform:P,snapGrid:F,snapToGrid:D,containerBounds:k}),L=[];if(!w)return;const{x:z,y:B,width:M,height:G}=b,q={},$=w.origin??V,{width:U,height:Z,x:X,y:te}=DHn(S,i.controlDirection,H,i.boundaries,i.keepAspectRatio,$,j,E),J=U!==M,ee=Z!==G,ae=X!==z&&J,ce=te!==B&ⅇif(!ae&&!ce&&!J&&!ee)return;if((ae||ce||$[0]===1||$[1]===1)&&(q.x=ae?X:b.x,q.y=ce?te:b.y,b.x=q.x,b.y=q.y,_.length>0)){const pe=X-z,oe=te-B;for(const ve of _)ve.position={x:ve.position.x-pe+$[0]*(U-M),y:ve.position.y-oe+$[1]*(Z-G)},L.push(ve)}if((J||ee)&&(q.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,q.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?Z:b.height,b.width=q.width,b.height=q.height),C&&w.expandParent){const pe=$[0]*(q.width??0);q.x&&q.x<pe&&(b.x=pe,S.x=S.x-(q.x-pe));const oe=$[1]*(q.height??0);q.y&&q.y<oe&&(b.y=oe,S.y=S.y-(q.y-oe))}const Y=MHn({width:b.width,prevWidth:M,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:Y};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(q,L))}).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 UHn={},sFe=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const h=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(m=>m(t,h))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(UHn?"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},qHn=e=>e?sFe(e):sFe,{useDebugValue:VHn}=Le,{useSyncExternalStoreWithSelector:HHn}=f1n,WHn=e=>e;function G0t(e,t=WHn,n){const r=HHn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return VHn(r),r}const aFe=(e,t)=>{const n=qHn(e),r=(s,a=t)=>G0t(n,s,a);return Object.assign(r,n),r},ZHn=(e,t)=>e?aFe(e,t):aFe;function no(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 DV=g.createContext(null),GHn=DV.Provider,Q0t=my.error001();function Us(e,t){const n=g.useContext(DV);if(n===null)throw new Error(Q0t);return G0t(n,e,t)}function So(){const e=g.useContext(DV);if(e===null)throw new Error(Q0t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const iFe={display:"none"},QHn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},Y0t="react-flow__node-desc",X0t="react-flow__edge-desc",YHn="react-flow__aria-live",XHn=e=>e.ariaLiveMessage,KHn=e=>e.ariaLabelConfig;function JHn({rfId:e}){const t=Us(XHn);return o.jsx("div",{id:`${YHn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:QHn,children:t})}function eWn({rfId:e,disableKeyboardA11y:t}){const n=Us(KHn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${Y0t}-${e}`,style:iFe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${X0t}-${e}`,style:iFe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(JHn,{rfId:e})]})}const y3=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Ml(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});y3.displayName="Panel";function tWn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(y3,{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 nWn=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}},T6=e=>e.id;function rWn(e,t){return no(e.selectedNodes.map(T6),t.selectedNodes.map(T6))&&no(e.selectedEdges.map(T6),t.selectedEdges.map(T6))}function sWn({onSelectionChange:e}){const t=So(),{selectedNodes:n,selectedEdges:r}=Us(nWn,rWn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const aWn=e=>!!e.onSelectionChangeHandlers;function iWn({onSelectionChange:e}){const t=Us(aWn);return e||t?o.jsx(sWn,{onSelectionChange:e}):null}const Bhe=typeof window<"u"?g.useLayoutEffect:g.useEffect,K0t=[0,0],oWn={x:0,y:0,zoom:1},lWn=["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"],oFe=[...lWn,"rfId"],cWn=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}),lFe={translateExtent:nM,nodeOrigin:K0t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function uWn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Us(cWn,no),u=So();Bhe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=lFe,l()}),[]);const d=g.useRef(lFe);return Bhe(()=>{for(const f of oFe){const p=e[f],h=d.current[f];p!==h&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?s(p):f==="translateExtent"?a(p):f==="nodeExtent"?i(p):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:JVn(p)}):f==="fitView"?u.setState({fitViewQueued:p}):f==="fitViewOptions"?u.setState({fitViewOptions:p}):u.setState({[f]:p})))}d.current=e},oFe.map(f=>e[f])),null}function cFe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function dWn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=cFe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:cFe()?.matches?"dark":"light"}const uFe=typeof document<"u"?document:null;function oM(e=null,t={target:uFe,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("+",`
|
|
337
337
|
`).replace(`
|
|
338
338
|
|
|
339
339
|
`,`
|
|
@@ -725,7 +725,7 @@ window.parent.postMessage({jsonrpc:'2.0',method:'ui/notifications/sandbox-proxy-
|
|
|
725
725
|
"groundTruth": "Expected result (optional)",
|
|
726
726
|
"metadata": { "key": "value" } // optional
|
|
727
727
|
}
|
|
728
|
-
]`})]})]})}function Tts({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border border-accent2/30 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-accent2 mb-2",children:[o.jsx(Ue,{children:o.jsx(Ep,{className:"w-4 h-4"})}),o.jsxs("span",{className:"font-medium text-sm",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-sm text-accent2/80 space-y-1",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-xs text-accent2/60 mt-2",children:["+",r," more error",r!==1?"s":""]})]})}function Nts({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=nes(),{batchInsertItems:b}=Ei(),S=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),w=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,j=()=>{switch(s){case"upload":return o.jsx(jts,{onFileSelect:S,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Tts,{errors:i.errors}),o.jsx("div",{className:"text-sm text-neutral4",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-neutral4",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(Ets,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Gt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Importing items..."}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Import Complete"}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(de,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(de,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(de,{variant:"primary",onClick:w,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(de,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:N[s]}),o.jsx(Qs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Pr,{className:"min-h-[200px] max-h-[50vh] overflow-y-auto",children:j()}),o.jsx(_c,{className:"px-6 pt-4 flex justify-end gap-2",children:E()})]})})}const CTe=e=>{const t=We(),{data:n}=JM(e),r=n?.experiments;return St({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Its=e=>{const t=We(),{data:n}=JM(e),r=n?.experiments;return St({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function Ats(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function aFt({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Vx(e),{data:a,isLoading:i}=CTe(e),{data:l,isLoading:c}=Its(e),u=g.useMemo(()=>t?(a??[]).filter(Ee=>Ee.experimentId===t):a,[a,t]),d=g.useMemo(()=>t?(l??[]).filter(Ee=>Ee.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ei(),[p,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,w]=g.useState(!1),[k,_]=g.useState(!1),[C,j]=g.useState(!1),[E,N]=g.useState(""),[I,A]=g.useState(""),[P,F]=g.useState(""),[D,V]=g.useState([]),[H,L]=g.useState(!1),[z,B]=g.useState(null),M=g.useMemo(()=>z??u??[],[z,u]);g.useEffect(()=>{B(null)},[e,t]),g.useEffect(()=>{u&&z===null&&B(u)},[u,z]);const G=g.useMemo(()=>{const Ee=new Set;if(s?.tags)for(const _e of s.tags)Ee.add(_e);for(const _e of M)for(const Ce of _e.tags)Ee.add(Ce);return[...Ee].sort()},[s,M]),q=g.useCallback(Ee=>{!s||!e||(s.tags??[]).includes(Ee)},[s,e]),$=g.useMemo(()=>m?m==="__untagged__"?M.filter(Ee=>Ee.tags.length===0):M.filter(Ee=>Ee.tags.includes(m)):M,[M,m]),U=g.useMemo(()=>{const Ee=new Map;for(const _e of M)for(const Ce of _e.tags)Ee.set(Ce,(Ee.get(Ce)??0)+1);return[...Ee.entries()].sort((_e,Ce)=>Ce[1]-_e[1])},[M]),Z=g.useMemo(()=>M.filter(Ee=>Ee.tags.length===0).length,[M]),X=g.useMemo(()=>{let Ee=0;return m&&Ee++,S&&Ee++,Ee},[m,S]),te=g.useCallback((Ee,_e)=>{B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,tags:_e}:Re));const Ce=M.find(Oe=>Oe.id===Ee);Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,tags:_e})},[M,f]),J=g.useCallback((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee);Ce?.traceId&&_e!==void 0&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:_e==="positive"?1:-1,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,rating:_e}:Re))},[M,r]),ee=g.useCallback((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee);Ce?.traceId&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:_e,comment:_e,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,comment:_e}:Re))},[M,r]),ae=g.useCallback(Ee=>{const _e=M.find(Ce=>Ce.id===Ee);B(Ce=>(Ce??[]).filter(Oe=>Oe.id!==Ee)),b(Ce=>{const Oe=new Set(Ce);return Oe.delete(Ee),Oe}),p===Ee&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:null})},[M,f,p]),ce=g.useCallback(Ee=>{const _e=M.find(Ce=>Ce.id===Ee);B(Ce=>(Ce??[]).filter(Oe=>Oe.id!==Ee)),b(Ce=>{const Oe=new Set(Ce);return Oe.delete(Ee),Oe}),p===Ee&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:"complete"})},[M,f,p]),Y=g.useMemo(()=>{const Ee=S?d??[]:$;return!S||!m?Ee:m==="__untagged__"?Ee.filter(_e=>_e.tags.length===0):Ee.filter(_e=>_e.tags.includes(m))},[S,d,$,m]),ne=S?c:!1,ue=g.useMemo(()=>new Set(Y.map(Ee=>Ee.id)),[Y]),pe=g.useMemo(()=>[...y].filter(Ee=>ue.has(Ee)).length,[y,ue]),oe=Y.length>0&&pe===Y.length,ve=pe>0&&!oe,ye=g.useCallback(Ee=>{b(_e=>{const Ce=new Set(_e);return Ce.has(Ee)?Ce.delete(Ee):Ce.add(Ee),Ce})},[]),Se=g.useCallback(()=>{b(oe?new Set:new Set(Y.map(Ee=>Ee.id)))},[oe,Y]),Ne=g.useCallback(Ee=>{for(const _e of y){const Ce=M.find(Oe=>Oe.id===_e);Ce&&!Ce.tags.includes(Ee)&&te(_e,[...Ce.tags,Ee])}},[M,y,te]),ke=g.useCallback(Ee=>{for(const _e of y){const Ce=M.find(Oe=>Oe.id===_e);Ce&&Ce.tags.includes(Ee)&&te(_e,Ce.tags.filter(Oe=>Oe!==Ee))}},[M,y,te]),Ie=g.useCallback(()=>{for(const Ee of y)ce(Ee);b(new Set)},[y,ce]),ze=g.useCallback(()=>{for(const Ee of y)ae(Ee);b(new Set)},[y,ae]),le=g.useCallback(()=>{N(""),j(!0)},[]),se=g.useCallback(async()=>{if(!(!I||!P)){_(!0),j(!1);try{const Ee=M.filter(Ce=>y.has(Ce.id));if(Ee.length===0){_(!1);return}const _e=await r.clusterFailures({modelId:`${I}/${P}`,items:Ee.map(Ce=>({id:Ce.id,input:Ce.input,output:Ce.output??void 0,error:typeof Ce.error=="string"?Ce.error:Ce.error?String(Ce.error):void 0,scores:Ce.scores,existingTags:Ce.tags.length>0?Ce.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:E||void 0});_e.proposedTags&&_e.proposedTags.length>0&&(V(_e.proposedTags.map(Ce=>({...Ce,accepted:!0}))),L(!0))}catch(Ee){console.error("Analysis failed:",Ee)}finally{_(!1)}}},[I,P,M,y,r,G,E]),re=g.useCallback(()=>{for(const Ee of D){if(!Ee.accepted)continue;const _e=M.find(Ce=>Ce.id===Ee.itemId);if(_e){const Ce=[...new Set([..._e.tags,...Ee.tags])];te(_e.id,Ce)}}L(!1)},[D,M,te]),he=g.useCallback(Ee=>{h(_e=>_e===Ee?null:Ee)},[]),xe=g.useMemo(()=>p?Y.find(Ee=>Ee.id===p)??null:null,[p,Y]),je=p?Y.findIndex(Ee=>Ee.id===p):-1,Pe=je>0?()=>h(Y[je-1].id):void 0,Ge=je>=0&&je<Y.length-1?()=>h(Y[je+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):o.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:j,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Qs,{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(Rt,{className:"text-xs mb-1 block",children:"Provider"}),o.jsx(Ly,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs mb-1 block",children:"Model"}),o.jsx(Fy,{llmId:I,value:P,onValueChange:F})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Kl,{value:E,onChange:Ee=>N(Ee.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-xs mt-1"})]})]}),o.jsxs(_c,{children:[o.jsx(de,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),o.jsxs(de,{onClick:se,disabled:!I||!P||k,children:[k?o.jsx(Gt,{className:"w-4 h-4 mr-1"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:H,onOpenChange:L,children:o.jsxs(xr,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Qs,{children:[D.filter(Ee=>Ee.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ee.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Mo,{checked:Ee.accepted,onCheckedChange:Oe=>V(Re=>Re.map((qe,Xe)=>Xe===_e?{...qe,accepted:!!Oe}:qe))}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate block",children:Ce?typeof Ce.input=="string"?Ce.input.slice(0,100):JSON.stringify(Ce.input).slice(0,100):Ee.itemId}),o.jsx("div",{className:"flex gap-1 flex-wrap mt-1.5",children:Ee.tags.map((Oe,Re)=>o.jsx(M9t,{tag:Oe,onRename:qe=>V(Xe=>Xe.map((tt,At)=>At===_e?{...tt,tags:tt.tags.map((ot,zt)=>zt===Re?qe:ot)}:tt)),onRemove:()=>V(qe=>qe.map((Xe,tt)=>tt===_e?{...Xe,tags:Xe.tags.filter((At,ot)=>ot!==Re)}:Xe))},`${Oe}-${Re}`))}),Ee.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ee.reason})]})]})},Ee.itemId)})}),o.jsxs(_c,{children:[o.jsx(de,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(de,{onClick:re,disabled:D.filter(Ee=>Ee.accepted).length===0,children:["Accept ",D.filter(Ee=>Ee.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between w-full flex-wrap gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsxs(de,{variant:"outline",size:"md",children:[o.jsx(Glt,{}),"Filter",X>0&&o.jsx("span",{className:K("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:X})]})}),o.jsxs(pt.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(pt.Sub,{children:[o.jsxs(pt.SubTrigger,{children:["Status",S&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(pt.SubContent,{children:[o.jsx(pt.CheckboxItem,{checked:!S,onCheckedChange:()=>{w(!1),h(null)},onSelect:Ee=>Ee.preventDefault(),children:"Review Queue"}),o.jsx(pt.CheckboxItem,{checked:S,onCheckedChange:()=>{w(!0),h(null)},onSelect:Ee=>Ee.preventDefault(),children:"Completed"})]})]}),o.jsxs(pt.Sub,{children:[o.jsxs(pt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(pt.SubContent,{children:[o.jsx(pt.CheckboxItem,{checked:!m,onCheckedChange:()=>v(null),onSelect:Ee=>Ee.preventDefault(),children:"All"}),Z>0&&o.jsx(pt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>v(m==="__untagged__"?null:"__untagged__"),onSelect:Ee=>Ee.preventDefault(),children:"Untagged"}),U.length>0&&o.jsx(pt.Separator,{}),U.map(([Ee])=>o.jsx(pt.CheckboxItem,{checked:m===Ee,onCheckedChange:()=>v(m===Ee?null:Ee),onSelect:_e=>_e.preventDefault(),children:Ee},Ee))]})]}),X>0&&o.jsxs(o.Fragment,{children:[o.jsx(pt.Separator,{}),o.jsxs(pt.Item,{onSelect:()=>{v(null),w(!1),h(null)},children:[o.jsx(vs,{}),"Clear all filters"]})]})]})]}),X>0&&o.jsxs(de,{variant:"outline",size:"md",onClick:()=>{v(null),w(!1),h(null)},children:[o.jsx(vs,{}),"Reset"]})]}),!S&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx($9t,{selectedCount:y.size,vocabulary:G,onApplyTag:Ne,onRemoveTag:ke,onNewTag:Ee=>Ne(Ee)}),o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsxs(de,{disabled:k,children:[k?o.jsx(Gt,{className:"w-4 h-4"}):o.jsx(Ue,{size:"sm",children:o.jsx(Aa,{})}),"Actions"]})}),o.jsxs(pt.Content,{align:"end",children:[o.jsxs(pt.Item,{onSelect:Ie,children:[o.jsx(Ue,{size:"sm",children:o.jsx(cO,{})}),"Complete"]}),o.jsxs(pt.Item,{onSelect:ze,children:[o.jsx(Ue,{size:"sm",children:o.jsx(ou,{})}),"Remove"]}),o.jsx(pt.Separator,{}),o.jsxs(pt.Item,{onSelect:le,children:[o.jsx(Ue,{size:"sm",children:o.jsx(kg,{})}),"Analyze"]})]})]})]})]}),ne?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):Y.length===0?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center px-8",children:[o.jsx(ge,{variant:"ui-sm",className:"text-neutral3 block",children:S?"No completed reviews yet":"No items to review"}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:S?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(me,{columns:Ze,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:!0,children:[S?o.jsx(me.TopCell,{children:" "}):o.jsx(me.TopSelectCell,{checked:oe?!0:ve?"indeterminate":!1,onToggle:()=>Se(),"aria-label":"Select all"}),o.jsxs(me.TopCells,{colStart:2,children:[o.jsx(me.TopCell,{children:"Input"}),o.jsx(me.TopCell,{children:"Comment"}),o.jsx(me.TopCell,{children:"Tags"}),o.jsx(me.TopCell,{children:"Rating"}),o.jsx(me.TopCell,{children:"Scores"})]})]}),Y.map(Ee=>{const _e=Ee.scores?Object.entries(Ee.scores):[],Ce=p===Ee.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",className:"min-w-0 text-neutral4",children:o.jsx("span",{className:"block truncate",children:Ats(Ee.input,200)})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ee.comment?o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ee.comment}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ee.tags.length>0?o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ee.tags.join(", ")}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(me.Cell,{height:"compact",children:[Ee.rating==="positive"&&o.jsx(Ue,{size:"sm",className:"text-positive1",children:o.jsx(ybe,{})}),Ee.rating==="negative"&&o.jsx(Ue,{size:"sm",className:"text-negative1",children:o.jsx(vbe,{})}),!Ee.rating&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(me.Cell,{height:"compact",children:_e.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ue,{size:"sm",className:"text-neutral3",children:o.jsx(rm,{})}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 font-mono",children:_e[0][1].toFixed(2)}),_e.length>1&&o.jsxs(dn,{variant:"default",children:["+",_e.length-1]})]}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(me.RowWrapper,{children:[S?o.jsx(me.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ee.error?"Error":"Success",title:Ee.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ee.error?"bg-red-700":"bg-green-600")})}):o.jsx(me.SelectCell,{checked:y.has(Ee.id),onToggle:()=>ye(Ee.id),"aria-label":`Select item ${Ee.id}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:Ce,onClick:()=>he(Ee.id),children:Oe})]},Ee.id)})]})]}),xe&&o.jsx(P9t,{item:xe,isCompleted:S,tagVocabulary:G,onRate:Ee=>J(xe.id,Ee),onSetTags:Ee=>{te(xe.id,Ee);for(const _e of Ee)G.includes(_e)||q(_e)},onComment:Ee=>ee(xe.id,Ee),onRemove:()=>ae(xe.id),onComplete:S?void 0:()=>ce(xe.id),onPrevious:Pe,onNext:Ge,onClose:()=>h(null)})]})]})}function Rts({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=yn(),[s,a]=ga(),{tab:i,activeVersion:l,handleTabChange:c}=OTe(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,S]=g.useState(!1),[w,k]=g.useState([]),[_,C]=g.useState(!1),[j,E]=g.useState([]),[N,I]=g.useState(0),[A,P]=g.useState(null),[F,D]=g.useState(""),[V]=D0e(F,300),{data:H}=Vx(e),{data:L=[],total:z,isLoading:B,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q}=C1(e,V||void 0,l),{total:$}=C1(e,void 0,l),[U,Z]=g.useState({}),{data:X,isLoading:te}=JM(e,void 0,U),{data:J}=JM(e),{deleteItems:ee}=Ei(),ae=X?.experiments??[],ce=J?.experiments??[],Y=Pes({hasSearchQuery:!!V,filteredItemsLength:L.length,unfilteredItemsTotal:$,itemsTotal:z}),{data:ne}=CTe(e),ue=ne?.length??0,pe=re=>{P(re)},oe=()=>{P(null)},ve=re=>{y(re),m(!0)},ye=re=>{k(re),S(!0)},Se=re=>{S(re),re||(k([]),I(he=>he+1))},Ne=re=>{r(`/datasets/${e}/items?items=${re.join(",")}`)},ke=re=>{r(`/datasets/${e}/versions?ids=${re.join(",")}`)},Ie=re=>{E(re),C(!0)},ze=async()=>{await ee.mutateAsync({datasetId:e,itemIds:j}),De.success(`Deleted ${j.length} items`),C(!1),E([]),I(re=>re+1)},le=re=>{m(!1),y([]),I(he=>he+1),n?.(re)},se=re=>{m(re),re||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(Ic,{defaultTab:"items",value:i,onValueChange:c,className:"grid grid-rows-[auto_1fr] h-full",children:[o.jsxs(Nc,{children:[o.jsxs(Ar,{value:"items",children:["Items ",o.jsx(Xs,{color:"gray",children:Y})]}),o.jsxs(Ar,{value:"experiments",children:["Experiments",o.jsx(Xs,{color:"gray",children:ae.length})]}),o.jsxs(Ar,{value:"review",children:["Review",ue>0&&o.jsx(Xs,{color:"orange",children:ue})]})]}),o.jsx(Xr,{value:"items",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(Cts,{datasetId:e,items:L,isLoading:B,featuredItemId:A,onItemSelect:pe,onItemClose:oe,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ie,onCreateDatasetClick:ve,onAddToDatasetClick:ye,onCompareItemsClick:Ne,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q,searchQuery:F,activeSearchQuery:V,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Xr,{value:"experiments",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(Xes,{experiments:ae,allExperiments:ce,isLoading:te,datasetId:e,filters:U,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"overflow-auto mt-2 pb-0",children:o.jsx(aFt,{datasetId:e})})]}),o.jsx(qes,{datasetId:e,open:u,onOpenChange:d}),o.jsx(Nts,{datasetId:e,open:f,onOpenChange:p}),o.jsx(bes,{open:h,onOpenChange:se,items:v,onSuccess:le}),o.jsx(xes,{open:b,onOpenChange:Se,items:w,currentDatasetId:e}),o.jsx(Tt,{open:_,onOpenChange:C,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",j.length," item",j.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ze,children:ee.isPending?"Deleting...":"Delete"})]})]})})]})}function Pts(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 sse({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-xs text-destructive",children:[o.jsxs("code",{className:"bg-destructive/10 px-1 rounded",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function $ts({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(""),[p,h]=g.useState(""),[m,v]=g.useState(null),{addItem:y}=Ei(),b=async C=>{C.preventDefault();let j;try{j=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let E;if(i.trim())try{E=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const P=JSON.parse(d);if(!Array.isArray(P)){De.error("Tool Mocks must be a JSON array");return}I=P}catch{De.error("Tool Mocks must be valid JSON");return}let A;if(p.trim())try{A=JSON.parse(p)}catch{De.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:j,groundTruth:E,expectedTrajectory:N,toolMocks:I,requestContext:A}),De.success("Item added successfully"),v(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch(P){const F=Pts(P);F?v(F):De.error(`Failed to add item: ${P instanceof Error?P.message:"Unknown error"}`)}},S=C=>{a(C),m?.field==="input"&&v(null)},w=C=>{l(C),m?.field==="groundTruth"&&v(null)},k=C=>{f(C),m?.field==="toolMocks"&&v(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),v(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx(Pr,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Yr,{value:s,onChange:S,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(sse,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Yr,{value:i,onChange:w,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(sse,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Yr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Yr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(sse,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Yr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(de,{type:"button",onClick:_,children:"Cancel"}),o.jsx(de,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function Mts({item:e}){return o.jsx(ua,{withMargins:!1,children:o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(vN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ka,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ua.Description,{children:[o.jsxs(Il,{children:[o.jsx(Flt,{})," Created ",er(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Il,{children:[o.jsx(d_,{})," Version v",e.datasetVersion]})]})]})})}function ETe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(Gje,{children:[o.jsx(Ps.CodeSection,{title:"Input",icon:o.jsx(uO,{}),codeStr:t}),o.jsx(Ps.CodeSection,{title:"Ground Truth",icon:o.jsx(yg,{}),codeStr:n}),s&&o.jsx(Ps.CodeSection,{title:"Expected Trajectory",icon:o.jsx(hbe,{}),codeStr:s}),o.jsx(Ps.CodeSection,{title:"Metadata",icon:o.jsx(xN,{}),codeStr:r})]})}function Dts({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=ih(),i=g.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Scorers (Optional)"}),o.jsx(Jl,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Lts=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Fts({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=km(),{data:l,isLoading:c}=zy(),{data:u,isLoading:d}=ih(),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})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Target Type"}),o.jsx(Jl,{options:Lts,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:m}),o.jsx(Jl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function zts({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return cm(om(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(Rt,{children:"Request Context"}),o.jsx(s3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-sm text-destructive",children:"Failed to parse request context schema"})}function Bts({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(""),[u,d]=g.useState(""),[f,p]=g.useState([]),[h,m]=g.useState({}),[v,y]=g.useState(""),{triggerExperiment:b}=Ei(),S=!!(n&&Object.keys(n).length>0),w=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(S){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(v.trim()){let N;try{N=JSON.parse(v)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},j=async()=>{if(!w)return;let N;try{N=C()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";ru.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});ru.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";ru.error(A)}},E=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:E,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Qs,{children:t?`Execute items from ${er(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Pr,{className:"grid gap-6",children:[o.jsx(Fts,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Dts,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),S?o.jsx(zts,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{children:"Request Context (JSON, optional)"}),o.jsx(Yr,{value:v,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(_c,{className:"px-6 pt-4",children:[o.jsx(de,{onClick:E,disabled:k,children:"Cancel"}),o.jsx(de,{variant:"primary",onClick:j,disabled:!w||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"w-4 h-4"}),"Running..."]}):"Run"})]})]})})}const Uts=e=>{const t=We();return St({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},jTe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function ase(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function qts({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(Fp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(In,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(In.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",ase(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>ase(i.args)).join(", ")]})]})}),o.jsx("div",{className:"rounded border border-border1 divide-y divide-border1 text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"font-mono text-neutral4",children:i.toolName}),o.jsx("span",{className:"ml-2 font-mono text-xs text-neutral3",children:ase(i.args)})]}),o.jsx("span",{className:`shrink-0 text-xs px-2 py-0.5 rounded ${Vts(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Vts(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Hts({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=g.useState(!1),m=d??p,v=f??h,y=!!e?.error,b=eF(e?.input),S=eF(e?.output),w=eF(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(bn,{collapsed:m,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[f&&o.jsx(de,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>v(!m),children:m?o.jsx(qlt,{}):o.jsx(Ult,{})}),o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(de,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(jTe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(bn.Content,{children:[o.jsxs("div",{className:"grid gap-4 mb-6",children:[o.jsxs(Bt,{children:[o.jsx(Bt.Key,{children:"Item Id"}),o.jsx(Bt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Bt.Key,{children:"Created"}),o.jsx(Bt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(In,{variant:"destructive",title:"Error",children:o.jsx(In.Message,{children:eF(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(me,{columns:"1fr 1fr",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Scorer"}),o.jsx(me.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(me.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(me.Cell,{height:"compact",children:C.scorerId}),o.jsx(me.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(qts,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(xN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.status&&o.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-surface4 text-neutral4",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(de,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(cq,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(de,{size:"sm",onClick:i,children:[o.jsx(Oa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:"Input",icon:o.jsx(vN,{}),codeStr:b}),o.jsx(bn.CodeSection,{title:"Output",icon:o.jsx(yg,{}),codeStr:S}),o.jsx(bn.CodeSection,{title:"Ground Truth",icon:o.jsx(gbe,{}),codeStr:w})]})]})]})}function eF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Wts({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(v=>v.size)].filter(Boolean).join(" "),m=s.some(v=>v.name==="input");return t?o.jsx(nl,{columns:h}):o.jsxs(me,{columns:h,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:p,children:[p&&o.jsx(me.TopCell,{children:" "}),p?o.jsx(me.TopCells,{colStart:2,children:s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))}):s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))]}),e.length===0?o.jsx(me.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(v=>{const y=!!v.error,b=v.id===n,S=o.jsxs(o.Fragment,{children:[o.jsx(me.IdCell,{id:v.itemId}),o.jsx(me.Cell,{height:"compact",children:o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("div",{className:"flex items-center justify-center w-10 relative bg-transparent h-full",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:K("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(Ln,{children:y?"Error":"Success"})]})}),m&&o.jsx(me.MonoCell,{children:Gts(Zts(v.input),200)}),i?.map(w=>{const _=a?.[v.itemId]?.find(C=>C.scorerId===w);return o.jsx(me.Cell,{height:"compact",className:"font-mono text-neutral3 text-ui-smd",children:_!=null?_.score.toFixed(3):"-"},w)})]});return p?o.jsxs(me.RowWrapper,{children:[o.jsx(me.SelectCell,{checked:d.has(v.id),onToggle:()=>f(v.id),"aria-label":`Select result ${v.itemId}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(v.id),children:S})]},v.id):o.jsx(me.RowButton,{featured:b,onClick:()=>r(v.id),children:S},v.id)}),o.jsx(me.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Zts(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Gts(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Qts(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Yts({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=g.useState(!1),u=a??l,d=i??c,f=Qts(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(bn,{collapsed:u,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[i&&o.jsx(de,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(qlt,{}):o.jsx(Ult,{})}),(n||t)&&o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(de,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(jTe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(bn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(rm,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(bn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Oh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Oh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Oh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Oh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const UQe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function Xts({scoresByItemId:e,experimentStatus:t}){const n=g.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Cr,{iconSlot:o.jsx(rm,{className:"w-8 h-8 text-neutral3"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:UQe,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{children:"Avg Score"}),o.jsx(gn.HeaderCol,{children:"Items Scored"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(gn.Row,{columns:UQe,children:[o.jsx(gn.TextCell,{children:r}),o.jsx(gn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(gn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function iFt({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=g.useState(null),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,w]=g.useState(!1),[k,_]=g.useState(!1),[C,j]=g.useState(!1),[E,N]=g.useState(!1),{updateExperimentResult:I}=Ei(),A=g.useCallback(se=>{b(re=>{const he=new Set(re);return he.has(se)?he.delete(se):he.add(se),he})},[]),P=g.useCallback(()=>b(new Set),[]),F=g.useCallback(()=>{const se=r.filter(re=>!!re.error).map(re=>re.id);b(new Set(se))},[r]),D=g.useCallback(async se=>{if(S||se.length===0)return;w(!0);let re=0;const he=new Set;try{for(const xe of se)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),re++,he.add(xe)}catch{}}finally{w(!1)}he.size>0&&b(xe=>{const je=new Set(xe);for(const Pe of he)je.delete(Pe);return je}),re>0&&De(`${re} result${re>1?"s":""} flagged for review`)},[t,e,S,I]),V=r.find(se=>se.id===c)??null,[H,L]=g.useState("summary"),[z,B]=g.useState(null),M=se=>{L(se),se!=="reviews"&&B(null)},{data:G}=CTe(t),q=(G??[]).filter(se=>se.experimentId===e).length,{data:$}=N9t(e,n),U=g.useMemo(()=>{if(!$)return[];const se=new Set;for(const re of Object.values($))for(const he of re)se.add(he.scorerId);return[...se].sort()},[$]),Z=se=>{u(se),f(null),h(void 0),v(null)},X=se=>{Z(se===c?null:se)},te=()=>{Z(null)},J=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>=0&&se<r.length-1)return()=>Z(r[se+1].id)},ee=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>0)return()=>Z(r[se-1].id)},ae=V?$?.[V.itemId]:void 0,ce=ae?.find(se=>se.id===m)??null,Y=se=>{v(se===m?null:se),f(null),h(void 0)},ne=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>=0&&se<ae.length-1)return()=>v(ae[se+1].id)},ue=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>0)return()=>v(ae[se-1].id)},{data:pe,isLoading:oe}=Uts(d),ve=pe?.spans,{data:ye,isLoading:Se}=HN(d,p),Ne=ye?.span,{handlePreviousSpan:ke,handleNextSpan:Ie}=aH(ve,p??null,h),ze=(()=>{const se=[],re=!!ce,he=!!d;return se.push(k?"auto":re||he?"2fr":"1fr"),re&&se.push(E?"auto":"3fr"),he&&se.push(C?"auto":"3fr"),he&&p&&se.push("3fr"),se.join(" ")})(),le=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...U.map(se=>({name:se,label:se,size:"12rem"}))],[U]);return o.jsxs(Ic,{defaultTab:"summary",value:H,onValueChange:M,className:"grid grid-rows-[auto_1fr] h-full overflow-hidden",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"summary",children:"Summary"}),o.jsx(Ar,{value:"results",children:"Results"}),o.jsxs(Ar,{value:"reviews",children:["Reviews",q>0&&o.jsx(Xs,{color:"orange",children:q})]})]}),o.jsx(Xr,{value:"summary",className:"overflow-y-auto mt-5",children:o.jsx(Xts,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"overflow-auto mt-2 pb-0",children:o.jsx(aFt,{datasetId:t,experimentId:e,featuredItemId:z})}),o.jsxs(Xr,{value:"results",className:"grid grid-rows-[auto_1fr] overflow-hidden mt-2",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-surface3",children:[o.jsxs(ge,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(de,{variant:"outline",size:"sm",disabled:S,onClick:()=>D([...y]),children:[o.jsx(Ue,{size:"sm",children:o.jsx(cq,{})}),"Flag for Review"]}),o.jsx(de,{variant:"ghost",size:"sm",onClick:P,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(de,{variant:"ghost",size:"sm",onClick:F,children:"Select loaded failures"})})]}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",V&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex overflow-y-auto w-full",children:o.jsx("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:o.jsx(Wts,{results:r,isLoading:s,featuredResultId:c,onResultClick:X,columns:le,scoresByItemId:$,scorerIds:U,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),V&&o.jsxs("div",{className:"grid gap-4 max-h-full min-h-0 overflow-auto content-start",style:{gridTemplateRows:ze},children:[o.jsx(Hts,{result:V,scores:ae,onPrevious:ee(),onNext:J(),onClose:te,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{V.traceId&&(f(V.traceId),h(void 0),v(null),_(!0),j(!1))},onOpenInReview:()=>{B(V.id),L("reviews")},onFlagForReview:se=>D([se]),collapsed:k,onCollapsedChange:_}),ce&&o.jsx(Yts,{score:ce,onNext:ne(),onPrevious:ue(),onClose:()=>v(null),onShowTrace:()=>{ce.traceId&&(f(ce.traceId),h(void 0),_(!0),N(!0),j(!1))},collapsed:E,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(gTe,{traceId:d,spans:ve,isLoading:oe,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:j,LinkComponent:FD,traceHref:`/traces/${d}`}),p&&o.jsx(rH,{traceId:d,spanId:p,span:Ne,isLoading:Se,onPrevious:ke,onNext:Ie,onClose:()=>h(void 0)})]})]})]})]})]})}const Kts={pending:o.jsx(Gj,{}),running:o.jsx(ife,{}),completed:o.jsx(ea,{}),failed:o.jsx(vs,{})};function Jts({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:K("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"flex p-1 px-3 text-ui-lg capitalize text-neutral4 gap-2 items-center bg-surface5 rounded-lg ",children:[o.jsx("span",{className:K("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Kts[n]}),e.status]}),o.jsxs("div",{className:K("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function ens({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Dr,{spacing:"close",children:[o.jsxs(de,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(Zq,{})," Prev"]}),o.jsxs(de,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(zD,{})]})]})}function TTe({delta:e}){const t=e>0?o.jsx(Xs,{size:"small",color:"green",intensity:"muted",children:o.jsx(dD,{})}):e<0?o.jsx(Xs,{size:"small",color:"red",intensity:"muted",children:o.jsx(Jln,{})}):null;return o.jsxs("span",{className:K("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"w-3 inline-block",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function tF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function tns({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Qr,{withLeftSeparator:!0,children:[o.jsxs(Qr.Toolbar,{children:[o.jsx(ens,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Dr,{children:o.jsx(de,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(vs,{})})})]}),o.jsxs(Qr.Content,{className:"pb-6",children:[o.jsx(ua,{withMargins:!1,children:o.jsx(ua.Column,{children:o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(vN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(Gje,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-sm font-medium text-neutral5",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,v=u?.scores[h]??null,y=m!=null&&v!=null?v-m:null;return o.jsxs("div",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-lg bg-surface2",children:[o.jsx("span",{className:"text-sm text-neutral5 font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-sm text-neutral3",children:[m!=null?m.toFixed(3):"-"," →"," ",v!=null?v.toFixed(3):"-"]}),y!=null&&o.jsx(TTe,{delta:y})]})]},h)})})]}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(yg,{}),codeStr:tF(c?.output)}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(yg,{}),codeStr:tF(u?.output)}),o.jsx(Ps.CodeSection,{title:"Item Input",icon:o.jsx(uO,{}),codeStr:tF(e.input)}),o.jsx(Ps.CodeSection,{title:"Item Ground Truth",icon:o.jsx(gbe,{}),codeStr:tF(e.groundTruth)})]})}):o.jsx(In,{variant:"warning",title:"Comparison not available",children:o.jsx(In.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function nns({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Qr,{children:o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:a,children:[o.jsx(gn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(gn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(gn.Row,{children:o.jsxs(gn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(gn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(gn.Cell,{className:"flex items-center gap-5 justify-center font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center text-neutral2 min-w-24",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(TTe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const rns={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function qQe({datasetId:e,experiment:t,type:n}){const{Link:r}=yn(),{label:s,color:a,customStyle:i}=rns[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null;return o.jsxs("div",{className:`grid border-2 border-border1 rounded-lg p-5 gap-3 ${i}`,children:[o.jsxs("div",{className:"flex items-center gap-3 w-full overflow-clip",children:[n==="contender"&&o.jsxs(Xs,{size:"small",color:a,children:[s,o.jsx(gm,{})]}),o.jsx(de,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"truncate min-w-0",children:t.id})}),n==="baseline"&&o.jsxs(Xs,{size:"small",color:a,children:[o.jsx(Tc,{})," ",s]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-ui-sm text-neutral3",children:[o.jsxs(Il,{children:[o.jsx(gbe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(Il,{children:[o.jsx(fq,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(Il,{children:[o.jsx(zlt,{})," ",er(l,"MMM d, yyyy HH:mm")]})]})]})}function sns({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=g.useState(null),{data:i,isLoading:l,error:c}=WJr(e,t,n),{data:u}=zU(e,t),{data:d}=zU(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=g.useMemo(()=>{if(!i)return[];const j=new Set;for(const E of i.items)for(const N of Object.values(E.results))if(N)for(const I of Object.keys(N.scores))j.add(I);return[...j].sort()},[i]),h=g.useMemo(()=>{if(!i||p.length===0)return[];const j=i.baselineId,E=t===j?n:t;return p.map(N=>{let I=0,A=0,P=0,F=0;for(const L of i.items){const z=L.results[j]?.scores[N],B=L.results[E]?.scores[N];z!=null&&(I+=z,P++),B!=null&&(A+=B,F++)}const D=P>0?I/P:null,V=F>0?A/F:null,H=D!=null&&V!=null?V-D:null;return{scorerId:N,avgA:D,avgB:V,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],v=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(j=>({name:j,label:j,size:"1fr"}))],[p,s]),y=i?.items.find(j=>j.itemId===s)??null,b=j=>{a(j===s?null:j)},S=()=>{a(null)},w=()=>{if(!i||!s)return;const j=i.items.findIndex(E=>E.itemId===s);if(j>=0&&j<i.items.length-1)return()=>a(i.items[j+1].itemId)},k=()=>{if(!i||!s)return;const j=i.items.findIndex(E=>E.itemId===s);if(j>0)return()=>a(i.items[j-1].itemId)};if(l)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx(Gt,{})});if(c)return o.jsx(In,{variant:"warning",title:"Error loading comparison",children:o.jsx(In.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 text-sm text-center py-8",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:K("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(qQe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:-translate-x-1/2 before:w-[2px] before:bg-border1",children:o.jsx("div",{className:"relative z-1 bg-surface2 rounded-lg p-2",children:o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(de,{onClick:r,children:"VS"})}),o.jsx(Ln,{children:"Switch the order"})]})})}),o.jsx(qQe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(In,{variant:"warning",title:"Version mismatch",children:o.jsxs(In.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:m,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(qGe,{children:[o.jsx(Xs,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(Xs,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(qGe,{children:[o.jsx(Xs,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(Xs,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:h.map(({scorerId:j,avgA:E,avgB:N,delta:I})=>o.jsxs(gn.Row,{columns:m,children:[o.jsx(gn.TextCell,{children:j}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:E!=null?E.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(TTe,{delta:I}):"-"})]},j))})})]}),o.jsxs(ay,{className:K({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(nns,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:v,onItemClick:b}),!!y&&o.jsx(tns,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:w(),onClose:S})]})]})}function ans({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=kTe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(S=>{const w=new Set(S);if(w.has(b))w.delete(b);else if(w.size>=2){const[k]=Array.from(w);return new Set([k,b])}else w.add(b);return w})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Qr,{className:"min-w-56",children:[l?o.jsx(Qr.Toolbar,{className:"grid justify-stretch gap-3 w-full",children:o.jsxs(Dr,{children:[o.jsx(de,{onClick:m,children:"Cancel"}),o.jsx(de,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Qr.Toolbar,{children:o.jsxs(de,{onClick:v,className:"w-full",children:[o.jsx(Yw,{})," Compare Ver."]})})}),i?o.jsx(ins,{}):o.jsxs(gn,{children:[o.jsx(gn.Header,{children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:a?.map(b=>{const S=String(b.datasetVersion),w=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gn.Row,{isSelected:l&&u.has(S),children:[l&&o.jsx(gn.LabelCell,{children:o.jsx(Mo,{checked:u.has(S),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(S)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(gn.VersionCell,{version:b.datasetVersion,date:w,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function ins(){return o.jsxs(gn,{children:[o.jsx(gn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gn.Row,{children:o.jsx(gn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ons(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${er(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function lns({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=lTe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ons(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Qr.Toolbar,{className:"grid grid-cols-[1fr_1fr_1fr_10rem] gap-4 w-full",children:[o.jsx("div",{}),o.jsx(wc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(wc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const cns=[{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"}],uns={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Hr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(act,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(Sun,{}),tooltip:"Same in both versions"}};function ise({red:e=!1,tooltip:t}){return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(ccn,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Ln,{children:t})]})}function GS({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=uns[e];return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"pr-3 text-ui-md text-neutral4 min-w-16 flex justify-end",children:["v. ",t]}),o.jsx(Xs,{color:n,size:"small",children:r})]})}),o.jsx(Ln,{children:s})]})}function dns(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function fns({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=yn(),l=t>n;return o.jsx(gn,{children:o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=dns(u,d);return o.jsxs(gn.Row,{columns:cns,children:[o.jsx(gn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(GS,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(GS,{variant:"changed",version:u.datasetVersion}):o.jsx(GS,{version:u.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ise,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(GS,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(GS,{variant:"changed",version:d.datasetVersion}):o.jsx(GS,{version:d.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ise,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(GS,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gn.Cell,{children:o.jsx(ise,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const VQe={needsReview:"#facc15",complete:"#22c55e"},pns=[{label:"Needs Review",color:VQe.needsReview},{label:"Reviewed",color:VQe.complete}];function hns({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,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,S=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:S,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ut.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ut.Loading,{}):s?o.jsx(Ut.Error,{message:"Failed to load review data"}):o.jsx(Ut.Content,{children:c?o.jsx(cN,{data:a,segments:pns,maxVal:i,fmt:u=>String(u)}):o.jsx(Ut.NoData,{message:"No items have been sent to review yet"})})]})}function NTe(){const e=We();return St({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function oFt(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 mns(e,t){const n=new Map,r=oFt(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function gns(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}}const vns=10;function yns(){const[e,t]=g.useState(!1),[n,r]=g.useState(""),[s,a]=g.useState("all"),[i,l]=g.useState("all"),[c,u]=g.useState("all"),[d,f]=g.useState(0),{data:p,isLoading:h,error:m}=Dg({page:d,perPage:vns}),{data:v,isLoading:y,error:b}=tG(),{data:S}=NTe(),w=g.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=g.useMemo(()=>v?.experiments??[],[v?.experiments]),C=g.useMemo(()=>ues(w),[w]),j=g.useMemo(()=>mns(S,_),[S,_]),E=h||y,N=m||b,I=()=>t(!0),A=g.useCallback(()=>f(B=>B+1),[]),P=g.useCallback(()=>f(B=>Math.max(0,B-1)),[]),F=g.useCallback(B=>{r(B),f(0)},[]),D=g.useCallback(B=>{a(B),f(0)},[]),V=g.useCallback(B=>{l(B),f(0)},[]),H=g.useCallback(B=>{u(B),f(0)},[]);if(N&&gs(N))return o.jsx(lr,{children:o.jsx(Vs,{})});if(N&&ys(N))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(N)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load datasets",message:N.message})});if(w.length===0&&!E&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(mes,{onCreateClick:I})}),o.jsx(Vve,{open:e,onOpenChange:t})]});const L=s!=="all"||i!=="all"||c!=="all"||n!=="",z=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(yes,{search:n,onSearchChange:F,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:V,tagFilter:c,onTagFilterChange:H,tagOptions:C,onReset:z,hasActiveFilters:L,onCreateClick:I})}),o.jsx(hes,{datasets:w,experiments:_,reviewByDataset:j,isLoading:E,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:P}),o.jsx(Vve,{open:e,onOpenChange:t})]})}function nF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function bns(){const{datasetId:e}=ur(),t=bs(),[n,r]=ga(),{activeVersion:s}=OTe(n,r),[a,i]=g.useState(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),{data:v,error:y,isLoading:b}=Vx(e),{data:S=[],isLoading:w}=C1(e,void 0,s),k=!w&&S.length===0;if(b)return null;if(y&&gs(y))return o.jsx(nF,{children:o.jsx(Vs,{})});if(y&&ys(y))return o.jsx(nF,{children:o.jsx(Ds,{resource:"datasets"})});if(y&&$Se(y)||!b&&!y&&!v)return o.jsx(nF,{children:o.jsx(Cr,{iconSlot:o.jsx(oy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(de,{as:Ma,to:"/datasets",children:[o.jsx(Tc,{}),"Back to Datasets"]})})});if(y)return o.jsx(nF,{children:o.jsx(zi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=j=>{t(`/datasets/${e}/experiments/${j}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsxs(Lt.Column,{children:[v?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:v.description}),o.jsxs(Bt,{numOfCol:2,children:[o.jsx(Bt.Key,{children:"Created at"}),o.jsx(Bt.Value,{children:v?.createdAt?er(new Date(v.createdAt),"MMM d, yyyy"):""}),o.jsx(Bt.Key,{children:"Latest version"}),o.jsxs(Bt.Value,{children:["v",v?.version??""]})]})]}),o.jsx(Lt.Column,{children:o.jsxs(Dr,{children:[k?o.jsxs(Un,{children:[o.jsx(Dn,{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(de,{variant:"primary",children:[o.jsx(Lp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Ln,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(de,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Lp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsx(de,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(pD,{})})}),o.jsxs(pt.Content,{align:"end",className:"w-48",children:[o.jsxs(pt.Item,{onSelect:()=>d(!0),children:[o.jsx(sm,{})," Edit Dataset"]}),o.jsxs(pt.Item,{onSelect:()=>m(!0),children:[o.jsx(Dp,{})," Duplicate Dataset"]}),o.jsxs(pt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ou,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Lt.MainArea,{children:o.jsx(Rts,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Bts,{datasetId:e,version:s??void 0,requestContextSchema:v?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx($ts,{datasetId:e,open:l,onOpenChange:c}),v&&o.jsx(Oes,{open:u,onOpenChange:d,dataset:{id:v.id,name:v.name,description:v?.description||"",targetType:v.targetType,inputSchema:v.inputSchema,groundTruthSchema:v.groundTruthSchema,requestContextSchema:v.requestContextSchema}}),v&&o.jsx(wes,{open:h,onOpenChange:m,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&o.jsx(Ces,{open:f,onOpenChange:p,datasetId:v.id,datasetName:v.name,onSuccess:C})]})}function lFt({experiment:e}){const{Link:t,paths:n}=yn(),{data:r}=km(),{data:s}=zy(),{data:a}=ih(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{children:o.jsxs(Bt,{numOfCol:2,children:[o.jsx(Bt.Key,{children:"Created at"}),o.jsx(Bt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Bt.Key,{children:"Completed at"}),o.jsx(Bt.Value,{children:er(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Bt.Key,{children:"Target"}),o.jsx(Bt.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Bt.Key,{children:"Version"}),c?o.jsx(Bt.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Bt.Value,{children:e.agentVersion})]})]})}),o.jsx(Lt.Column,{children:o.jsx(Jts,{experiment:e})})]})})}function rF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function xns(){const{datasetId:e,experimentId:t}=ur(),{data:n,isLoading:r,error:s}=zU(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=KZ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&gs(s)?o.jsx(rF,{children:o.jsx(Vs,{})}):s&&ys(s)?o.jsx(rF,{children:o.jsx(Ds,{resource:"datasets"})}):s&&$Se(s)||!r&&!s&&!n?o.jsx(rF,{children:o.jsx(Cr,{iconSlot:o.jsx(obe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(de,{as:Ma,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})}):s?o.jsx(rF,{children:o.jsx(zi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(lFt,{experiment:n}),o.jsx(Lt.MainArea,{children:o.jsx(iFt,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function wns(){const{datasetId:e}=ur(),[t,n]=ga(),{error:r}=Vx(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&gs(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):r&&ys(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!s||!a?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsxs("div",{className:"text-neutral4 text-center py-8",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-sm mt-2",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(cs,{children:o.jsx(Sy,{children:o.jsxs("div",{className:"max-w-[100rem] w-full px-12 mx-auto grid content-start ",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{})," Dataset Experiments Comparison"]}),o.jsxs(ua.Description,{children:["Comparing"," ",o.jsx(Ma,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(Ma,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ua.Column,{children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})]}),o.jsx(sns,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function Sns(){const{datasetId:e,itemId:t}=ur(),{Link:n}=yn(),r=bs(),{data:s,isLoading:a,error:i}=kTe(e??"",t??""),{updateItem:l,deleteItem:c}=Ei(),{data:u}=Vx(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=g.useState(null),m=g.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),v=d?.datasetVersion??0,[y,b]=g.useState(!1),[S,w]=g.useState(m.input),[k,_]=g.useState(m.groundTruth),[C,j]=g.useState(m.metadata),[E,N]=g.useState(m.trajectory),[I,A]=g.useState(m.toolMocks),[P,F]=g.useState(m.requestContext),[D,V]=g.useState(v);v!==D&&(V(v),w(m.input),_(m.groundTruth),j(m.metadata),N(m.trajectory),A(m.toolMocks),F(m.requestContext));const[H,L]=g.useState(!1),z=J=>{h(f?J:J.isLatest?null:J)},B=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},q=()=>{M||L(!0)},$=async()=>{if(!e||!t)return;let J;try{J=JSON.parse(S)}catch{De.error("Input must be valid JSON");return}let ee;if(k.trim())try{ee=JSON.parse(k)}catch{De.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{De.error("Metadata must be valid JSON");return}let ce;const Y=E!==m.trajectory;if(Y&&E.trim())try{ce=JSON.parse(E)}catch{De.error("Expected Trajectory must be valid JSON");return}let ne;const ue=I!==m.toolMocks;if(ue&&I.trim())try{const ve=JSON.parse(I);if(!Array.isArray(ve)){De.error("Tool Mocks must be a JSON array");return}ne=ve}catch{De.error("Tool Mocks must be valid JSON");return}let pe;const oe=P!==m.requestContext;if(oe&&P.trim())try{pe=JSON.parse(P)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:J,groundTruth:ee,metadata:ae,...Y?{expectedTrajectory:ce??null}:{},...ue?{toolMocks:ne??[]}:{},...oe?{requestContext:pe}:{}}),De.success("Item updated successfully"),b(!1)}catch(ve){De.error(`Failed to update item: ${ve instanceof Error?ve.message:"Unknown error"}`)}},U=()=>{d&&(w(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),j(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),F(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),De.success("Item deleted successfully"),L(!1),r(`/datasets/${e}`)}catch(J){De.error(`Failed to delete item: ${J instanceof Error?J.message:"Unknown error"}`)}},X=p??d,te=X?{id:t??"",datasetId:e??"",datasetVersion:X.datasetVersion,input:X.input,groundTruth:X.groundTruth,expectedTrajectory:X.expectedTrajectory,metadata:X.metadata,createdAt:X.createdAt,updatedAt:X.updatedAt}:null;return i&&gs(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):i&&ys(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[60rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(vN,{}),t," ",o.jsx(ka,{content:t})]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Item of ",o.jsx(oy,{})," ",u?.name]})}),o.jsxs(ua.Description,{children:[o.jsxs(Il,{children:[o.jsx(Flt,{})," Created at"," ",d?.createdAt?er(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(Il,{children:[o.jsx(d_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ua.Column,{children:!y&&!f&&o.jsxs(Dr,{children:[o.jsxs(de,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(act,{})," Edit"]}),o.jsxs(de,{onClick:q,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(ou,{})," Delete"]})]})})]}),o.jsxs(ay,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Qr,{withRightSeparator:!y,children:[f&&d&&o.jsx(In,{variant:"destructive",title:"Item deleted",children:o.jsxs(In.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(In,{variant:"warning",title:"Previous version",action:o.jsxs(In.Button,{onClick:B,children:[o.jsx(Plt,{})," Return to the latest version"]}),children:o.jsxs(In.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(rFt,{inputValue:S,setInputValue:w,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:j,trajectoryValue:E,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,requestContextValue:P,setRequestContextValue:F,validationErrors:null,onSave:$,onCancel:U,isSaving:l.isPending}):te?o.jsx(ETe,{item:te,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Qr,{children:o.jsx(ans,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:z,onCompareVersionsClick:J=>{r(`/datasets/${e}/items/${t}/versions?ids=${J.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(Tt,{open:H,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function HQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function kns(){const{datasetId:e}=ur(),[t,n]=ga(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Vx(e??""),{Link:i}=yn(),[l,c]=g.useState(!1),{data:u}=BU(e??"",r[0]??""),{data:d}=BU(e??"",r[1]??"");return a&&gs(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):a&&ys(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||r.length<2?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Iy,{owner:"dataset-items-compare",children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Tc,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{}),"Compare Dataset Items"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Comparing ",r.length," items of"," ",o.jsx(Ma,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ua.Column,{children:o.jsx(Dr,{children:o.jsx(de,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(Wlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(hun,{})," Diff View"]})})})})]}),o.jsx(ay,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(g.Fragment,{children:[o.jsx(Ons,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(z_e,{codeA:HQe(u),codeB:HQe(d)})]})})]})}function Ons({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=BU(e,t),{data:u}=C1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"flex gap-4",children:[o.jsxs(da,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(pa,{"aria-label":"Item",children:o.jsx(fa,{placeholder:"Select item"})}),o.jsx(ha,{children:f.map(p=>o.jsx(Fr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(de,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(d_,{}),"Versions"]})]}),i&&o.jsx(Qr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Mts,{item:l}),o.jsx(ETe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function WQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function _ns(){const{datasetId:e,itemId:t}=ur(),[n,r]=ga(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Vx(e??""),{Link:u}=yn(),{data:d}=kTe(e??"",t??""),{data:f}=Wve(e??"",t??"",i[0]??0,l?.version),{data:p}=Wve(e??"",t??"",i[1]??0,l?.version);return c&&gs(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):c&&ys(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Iy,{owner:"dataset-item-versions-compare",children:o.jsxs(de,{as:Ma,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Tc,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{}),"Compare Dataset Item Versions"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Comparing ",i.length," versions of"," ",o.jsx(Ma,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ua.Column,{children:o.jsx(Dr,{children:o.jsx(de,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(Wlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Jun,{})," Diff View"]})})})})]}),o.jsx(ay,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Cns,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(z_e,{codeA:WQe(f),codeB:WQe(p)})]})})]})}function Cns({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=Wve(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",er(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(Xs,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"grid gap-4 grid-cols-[auto_1fr]",children:[o.jsx(d_,{className:"w-6 h-6 opacity-50"}),o.jsxs(da,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(pa,{"aria-label":"Version",className:"w-full",children:o.jsx(fa,{placeholder:"Select version"})}),o.jsx(ha,{children:h.map(v=>o.jsx(Fr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(Qr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(ETe,{item:m,Link:i})})]})}function Ens(){const{datasetId:e}=ur(),[t]=ga(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=bs(),{data:s,error:a}=Vx(e??""),i=C1(e??"",void 0,n[0]??null),l=C1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&gs(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})});if(a&&ys(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Ffn,{})," Compare Dataset Versions"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:[o.jsx(d_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ua.Column,{children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})]}),o.jsx(ay,{children:o.jsxs(Qr,{children:[o.jsx(lns,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(fns,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Gve({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function jns(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 Tns({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,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=jns(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,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(p)}),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,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(h)}),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,{})]})]})}const ZQe="auto 1fr auto auto auto auto auto auto auto";function Nns(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Ins={completed:"success",running:"warning",failed:"error",pending:"neutral"};function Ans({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=yn(),u=g.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=g.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=g.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",v=!p||h.id.toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return v&&y&&b})},[d,s,u,a,i]);return r?o.jsx(nl,{columns:ZQe}):o.jsxs(me,{columns:ZQe,variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Experiment"}),o.jsx(me.TopCell,{children:"Dataset"}),o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{className:"text-center",children:"Items"}),o.jsx(me.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(me.TopCell,{className:"text-center",children:"Failed"}),o.jsx(me.TopCell,{className:"text-center",children:"Review"}),o.jsx(me.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??p.datasetId.slice(0,8):"—",m=p.status??"pending",v=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,S=b>0?Math.round(v/b*100):0;return o.jsxs(me.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(me.NameCell,{className:"font-mono",children:p.id.slice(0,8)}),o.jsx(me.TextCell,{children:h}),o.jsx(me.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(me.Cell,{children:o.jsx(hg,{variant:Ins[m]??"neutral",withDot:!0,children:m})}),o.jsx(me.TextCell,{className:"text-center",children:b}),o.jsx(me.TextCell,{className:"text-center",children:o.jsxs("span",{className:v>0?"text-accent1":"",children:[v," (",S,"%)"]})}),o.jsx(me.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(me.Cell,{className:"text-center",children:(()=>{const w=n?.get(p.id);if(!w)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=w.needsReview+w.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):w.needsReview>0?o.jsxs(Xs,{size:"small",color:"yellow",children:[w.needsReview," pending"]}):o.jsxs(Xs,{size:"small",color:"green",children:[w.complete,"/",k," reviewed"]})})()}),o.jsx(me.TextCell,{children:Nns(p.createdAt)})]},p.id)})]})}const Rns=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Pns(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const sF={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},$ns=[{label:"Completed",color:sF.completed},{label:"Running",color:sF.running},{label:"Pending",color:sF.pending},{label:"Failed",color:sF.failed}];function Mns({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 p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Ut.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ut.Loading,{}):r?o.jsx(Ut.Error,{message:"Failed to load experiments data"}):o.jsx(Ut.Content,{children:i?o.jsx(cN,{data:s,segments:$ns,maxVal:a,fmt:l=>String(l)}):o.jsx(Ut.NoData,{message:"No experiments have been run yet"})})]})}const Dns=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(de,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Oa,{})]})})})});function Lns({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(jf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Dr,{children:[o.jsx(wc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Rns],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(wc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(de,{onClick:l,size:"sm",variant:"default",children:[o.jsx(vs,{className:"size-3"})," Reset"]})]})]})}function Fns(){const{data:e,isLoading:t,error:n}=ih(),{data:r,isLoading:s,error:a}=Dg(),{data:i,isLoading:l,error:c}=tG(),{data:u,isLoading:d,isError:f,error:p}=UZr(),{data:h,isLoading:m,isError:v,error:y}=NTe(),b=r?.datasets,S=i?.experiments,w=g.useMemo(()=>gns(h),[h]),k=n||a||c||p||y;return k&&gs(k)?o.jsx(lr,{children:o.jsx(Vs,{})}):k&&ys(k)?o.jsx(lr,{children:o.jsx(Ds,{resource:"evaluation"})}):k?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load evaluation data",message:k.message})}):o.jsx(Lt,{width:"wide",height:"full",children:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Gve,{children:o.jsx(Tns,{scorers:e,datasets:b,experiments:S,avgScore:u?.avgScore??null,prevAvgScore:u?.prevAvgScore??null,totalNeedsReview:w.needsReview,isLoadingScorers:t,isLoadingDatasets:s,isLoadingExperiments:l,isLoadingScores:d,isLoadingReview:m})}),o.jsx(eZr,{summaryData:u?.summaryData??[],overTimeData:u?.overTimeData??[],scorerNames:u?.scorerNames??[],avgScore:u?.avgScore??null,isLoading:d,isError:f}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(ves,{experiments:S,isLoading:l,isError:!!c}),o.jsx(Mns,{experiments:S,datasets:b,isLoading:l,isError:!!c})]}),o.jsx(hns,{reviewSummary:h,experiments:S,datasets:b,isLoading:m,isError:!!v})]})})}function zns(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),{data:i,isLoading:l,error:c}=Dg(),{data:u,isLoading:d,error:f}=tG(),{data:p}=NTe(),h=g.useMemo(()=>i?.datasets??[],[i?.datasets]),m=g.useMemo(()=>u?.experiments??[],[u?.experiments]),v=g.useMemo(()=>Pns(h),[h]),y=g.useMemo(()=>oFt(p),[p]),b=l||d,S=f||c;if(S&&gs(S))return o.jsx(lr,{children:o.jsx(Vs,{})});if(f&&ys(f))return o.jsx(lr,{children:o.jsx(Ds,{resource:"experiments"})});if(c&&ys(c))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(S)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load experiments",message:S.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Dns,{})});const w=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lns,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:v,onReset:k,hasActiveFilters:w})}),o.jsx(Ans,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function aF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Bns(){const{experimentId:e}=ur(),{data:t,isLoading:n}=tG(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=zU(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=KZ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&gs(l)?o.jsx(aF,{children:o.jsx(Vs,{})}):l&&ys(l)?o.jsx(aF,{children:o.jsx(Ds,{resource:"datasets"})}):l&&$Se(l)||!n&&!s||!i&&!l&&!a?o.jsx(aF,{children:o.jsx(Cr,{iconSlot:o.jsx(obe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(de,{as:Ma,to:"/experiments",children:[o.jsx(Tc,{}),"Back to Experiments"]})})}):l?o.jsx(aF,{children:o.jsx(zi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(lFt,{experiment:a}),o.jsx(Lt.MainArea,{children:o.jsx(iFt,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Uns({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 cFt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Uns,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function qns({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(cFt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Vns({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(qns,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(cFt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Hns({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:p,onToolkitChange:h,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=>p(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=>h(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 GQe=e=>e.authorId?.trim()||"shared",Wns=(e,t)=>{if(!t||new Set(e.map(GQe)).size<=1)return null;const r=new Map;for(const a of e){const i=GQe(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},Zns=["*","tool-providers:*","tool-providers:admin"];function Gns(){const{data:e}=Sm();return e?.permissions?.some(t=>Zns.includes(t))??!1}function Qns(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=QN(),l=xH(e||null),c=qCt(e||null,n||null),u=UCt(),d=FCt(),f=Gns(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Wns(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()}})},S=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(Hns,{providers:p,toolkits:h,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(Vns,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:S})]})}function Yns({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"flex min-h-screen items-center justify-center bg-surface1",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(Qh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-xl font-semibold text-neutral6",children:e})]}),t,n,r]})})}function uFt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=ac(),{mutate:i,isPending:l,error:c}=jsr(),{mutate:u,isPending:d,error:f}=Nsr(),{mutate:p,isPending:h}=f_t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[S,w]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,j=C.type==="sso"||C.type==="both",E=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,A=m==="signin"||!I,P=A?l:d,F=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href="/"},V=M=>{M.preventDefault(),A?i({email:S,password:k},{onSuccess:D}):u({email:S,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},L=()=>{v(A?"signup":"signin")},z=C.description?o.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border1 bg-surface1 p-3",children:[o.jsx(yf,{className:"mt-0.5 h-4 w-4 shrink-0 text-neutral4"}),o.jsx("p",{className:"text-sm text-neutral3",children:C.description})]}):null,B=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(Yns,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:B,children:[E&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"block text-sm text-neutral4",children:"Name"}),o.jsx(kn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"block text-sm text-neutral4",children:"Email"}),o.jsx(kn,{id:"email",type:"email",value:S,onChange:M=>w(M.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:"block text-sm text-neutral4",children:"Password"}),o.jsx(kn,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),F&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:F.message}),o.jsx(de,{type:"submit",disabled:P,className:"w-full",size:"lg",children:P?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:L,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),j&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"w-full border-t border-border1"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 px-2 text-neutral3",children:"or continue with"})})]}),j&&N&&o.jsxs(de,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function Xns(){const[e]=ga(),t=bs(),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(uFt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const Kf=Mi.KeyValueList;function Kns(e){return e instanceof Date?e:new Date(e)}function Jns({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,p=Kns(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Mi,{collapsed:d,children:[o.jsxs(Mi.Header,{children:[o.jsxs(Mi.Heading,{children:["Log ",o.jsx("b",{children:er(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[l&&o.jsx(de,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Gq,{}):o.jsx(Uxe,{})}),o.jsxs(Dr,{spacing:"close",children:[o.jsx(de,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(Zq,{})}),o.jsx(de,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(zD,{})})]}),o.jsx(Mi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Mi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:K("grid gap-2 my-8","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Dr,{spacing:"close",className:"min-w-0 w-full",children:[o.jsxs(de,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx($z,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:" ml-auto text-ui-sm text-neutral2 min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Dr,{spacing:"close",className:"min-w-0 w-full",children:[o.jsxs(de,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx($z,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:" ml-auto text-ui-sm text-neutral2 min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(Kf,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Entity Type"}),o.jsx(Kf.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Entity Name"}),o.jsx(Kf.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Service"}),o.jsx(Kf.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Environment"}),o.jsx(Kf.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Source"}),o.jsx(Kf.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(Kf.Key,{children:v}),o.jsx(Kf.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Mi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function ers({error:e,resource:t,errorTitle:n}){if(gs(e))return o.jsx(Vs,{});if(ys(e))return o.jsx(Ds,{resource:t});if(iOt(e,"logs"))return o.jsx(Cr,{iconSlot:o.jsx(Qq,{}),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(zi,{title:n,message:r??"Unknown error"})}function trs({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 gap-4 items-start",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid gap-4 h-full 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 nrs={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 rrs({level:e}){const t=nrs[e];return o.jsx(ko,{height:"compact",children:o.jsx("span",{className:"uppercase text-ui-sm font-semibold",style:{color:t.color},children:t.label})})}function srs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case Os.AGENT:return o.jsx(al,{className:n,"aria-hidden":!0});case"workflow":case Os.WORKFLOW_RUN:return o.jsx(jd,{className:n,"aria-hidden":!0});case Os.TOOL:return o.jsx(Jp,{className:n,"aria-hidden":!0});default:return null}}function ars({entityType:e,entityName:t}){const n=e??"";return o.jsxs(ko,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(srs,{entityType:n}),t?o.jsx("span",{className:"min-w-0 text-ui-smd truncate",children:t}):"-"]})}function irs({message:e}){return o.jsx(ko,{height:"compact",className:"text-neutral4 text-ui-smd min-w-0 truncate font-mono",children:e})}function ors({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(ko,{height:"compact",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(sSe,{children:t})}const Ul=Object.assign(S3,{Top:JV,TopCell:R_,TopCellWithTooltip:eH,TopCellSmart:sSt,RowWrapper:cSe,RowButton:k3,RowLink:aSt,Spacer:lSe,NoMatch:KV,DateCell:aSe,TimeCell:iSe,LevelCell:rrs,EntityCell:ars,MessageCell:irs,DataCell:ors,NextPageLoading:XV}),QQe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",lrs=36,crs=8;function urs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=H9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>lrs,overscan:crs}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(nl,{columns:QQe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ul,{columns:QQe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ul.Top,{children:[o.jsx(Ul.TopCell,{children:"Date"}),o.jsx(Ul.TopCell,{children:"Time"}),o.jsx(Ul.TopCell,{children:"Level"}),o.jsx(Ul.TopCell,{children:"Entity"}),o.jsx(Ul.TopCell,{children:"Message"}),o.jsx(Ul.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ul.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ul.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const S=b===i;return o.jsxs(Ul.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:S,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ul.DateCell,{timestamp:y.timestamp}),o.jsx(Ul.TimeCell,{timestamp:y.timestamp}),o.jsx(Ul.LevelCell,{level:y.level}),o.jsx(Ul.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ul.MessageCell,{message:y.message}),o.jsx(Ul.DataCell,{data:y.data})]},b)}),o.jsx(Ul.Spacer,{height:m})]}),o.jsx(Ul.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function drs({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=>frs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(hTe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(fTe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function frs(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 prs={"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"},ose="MMM d, yyyy HH:mm",lse="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function hrs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${prs[e]}`,description:lse}:t&&n?{title:`No logs between ${er(t,ose)} and ${er(n,ose)}`,description:lse}:t?{title:`No logs since ${er(t,ose)}`,description:lse}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const mrs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=hrs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Qq,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(de,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(qxe,{})]})})})},grs=20,vrs=1e4;function yrs(e,t,n){if(e?.pagination?.hasMore)return n+1}function brs(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 xrs(e){return iOt(e.state.error,"logs")?!1:vrs}const wrs=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=N_(),s=P1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:grs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:yrs,select:brs,retry:!1,refetchInterval:xrs}),{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}},iF={AGENT:Os.AGENT,WORKFLOW:Os.WORKFLOW_RUN,SCORER:Os.SCORER,INGEST:Os.RAG_INGESTION},dFt=[{label:"Agent",entityType:iF.AGENT},{label:"Workflow",entityType:iF.WORKFLOW},{label:"Scorer",entityType:iF.SCORER},{label:"Ingest",entityType:iF.INGEST}],Srs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],$x="rootEntityType",qb="datePreset",Vb="dateFrom",Hb="dateTo",krs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),_l={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"},X4=Object.keys(_l),ITe=new Set(["tags"]),ATe="mastra:logs:saved-filters";function Ors(e,t=ATe){const n=Trs(e),r=e.get(qb);r&&n.set(qb,r);const s=e.get(Vb);s&&n.set(Vb,s);const a=e.get(Hb);a&&n.set(Hb,a);try{localStorage.setItem(t,n.toString())}catch{}}function _rs(e=ATe){try{localStorage.removeItem(e)}catch{}}function YQe(e=ATe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Crs(e){if(e.has(qb)||e.has(Vb)||e.has(Hb)||e.has($x))return!0;for(const t of X4)if(e.has(_l[t]))return!0;return!1}function Ers({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:dFt.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:Srs.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 jrs(e){const t=[],n=new Map([[$x,"rootEntityType"]]);for(const s of X4)n.set(_l[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),ITe.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 Trs(e){const t=new URLSearchParams,n=e.get($x);n&&t.set($x,n);for(const r of X4){const s=_l[r];if(ITe.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 Nrs(e,t){e.delete($x);for(const n of X4)e.delete(_l[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set($x,n.value);continue}const r=_l[n.fieldId];if(r){if(ITe.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 Irs({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 Ars(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 Rrs="Filters setting for Logs saved",Prs="Filters setting for Logs cleared up";function $rs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>YQe(r)!==null),c=g.useCallback(()=>{Ors(e,r),l(!0);const f=s?.saved??Rrs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{_rs(r),l(!1);const f=s?.cleared??Prs;f!==!1&&De.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Crs(e)))return;const f=YQe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Mrs(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 Drs(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,Mrs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Lrs(e,t,n,r){const s=g.useMemo(()=>Drs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Qve="logId",Yve="traceId",Xve="spanId",PR=1440*60*1e3,Frs={"last-24h":PR,"last-3d":3*PR,"last-7d":7*PR,"last-14d":14*PR,"last-30d":30*PR};function oF(e){e.delete(Qve),e.delete(Yve),e.delete(Xve)}function zrs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(qb);return _&&krs.has(_)?_:"last-24h"},[e]),a=e.get(Vb),i=e.get(Hb),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=Frs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Qve),f=e.get(Yve),p=e.get(Xve),h=g.useMemo(()=>dFt.find(_=>_.entityType===e.get($x)),[e]),m=g.useMemo(()=>jrs(e),[e]),v=g.useCallback(_=>{t(C=>{const j=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Qve:E==="traceId"?Yve:Xve;N?j.set(I,N):j.delete(I)}return j},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const j=new URLSearchParams(C);return Nrs(j,_),oF(j),j},{replace:!0})},[t]),b=y,S=g.useCallback((_,C)=>{if(u.current!=="custom")return;const j=C==="from"?Vb:Hb;t(E=>{const N=new URLSearchParams(E);return _?N.set(j,_.toISOString()):N.delete(j),oF(N),N},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const j=new URLSearchParams(C);return _==="last-24h"?(j.delete(qb),j.delete(Vb),j.delete(Hb)):_==="custom"?j.set(qb,"custom"):(j.set(qb,_),j.delete(Vb),j.delete(Hb)),oF(j),j},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete($x);for(const j of X4)C.delete(_l[j]);return C.delete(qb),C.delete(Vb),C.delete(Hb),oF(C),C},{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:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:S,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,S,w,k,y])}const wb=Mi.KeyValueList;function Brs({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(Mi,{children:[o.jsxs(Mi.Header,{children:[o.jsxs(Mi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Mi.CloseButton,{onClick:r})]}),n?o.jsx(Mi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Mi.Content,{children:[o.jsxs(wb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Type"}),o.jsx(wb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Started"}),o.jsx(wb.Value,{children:er(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Ended"}),o.jsx(wb.Value,{children:er(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Duration"}),o.jsx(wb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(Mi.CodeSection,{title:"Input",icon:o.jsx(Ufe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Output",icon:o.jsx(qfe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Metadata",icon:o.jsx(pw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Attributes",icon:o.jsx(pw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Mi.NoData,{children:"Span not found."})]})}function Urs(){const[e,t]=ga(),n=zrs(e,t),r=$rs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=STe(),{data:d=[],isPending:f}=bTe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=xTe(),{data:m=[],isPending:v}=wTe(),y=g.useMemo(()=>Ers({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Irs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:S=[],isLoading:w,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:j}=wrs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=Lrs(S,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:F,isLoading:D}=sH(n.featuredTraceId??null),{data:V,isLoading:H}=HN(n.featuredTraceId??"",n.featuredSpanId??""),L=g.useCallback(()=>n.applyFilterTokens(Ars(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),B=g.useCallback(X=>n.handleFeaturedChange({traceId:X,spanId:null}),[n]),M=g.useCallback((X,te)=>n.handleFeaturedChange({traceId:X,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(X=>n.handleFeaturedChange({spanId:X??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(dTe,{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(mTe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(drs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:L,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(ers,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return S.length===0&&!w&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(mrs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(trs,{logCollapsed:i,listSlot:o.jsx(urs,{logs:S,isLoading:w,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:j,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Jns,{log:N,onClose:z,onTraceClick:B,onSpanClick:M,onPrevious:A,onNext:P,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(jSt,{traceId:n.featuredTraceId,spans:F?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Brs,{spanId:n.featuredSpanId,span:V?.span,isLoading:H,onClose:q}):null})]})}function qrs({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=oLt(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=dm(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function Vrs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(nl,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(al,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Jp,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(jd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(qrs,{server:s},s.id))]})}const Hrs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),Wrs=()=>{const{data:e=[],isLoading:t,error:n}=LZ(),[r,s]=g.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Hrs,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Vrs,{mcpServers:e,isLoading:t,search:r})]})},Zrs=(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 Grs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=g.useMemo(()=>Zrs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(nl,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(al,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=dm(c.id,50),d=dm(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Qrs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),Yrs=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new l_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Xrs=({toolId:e})=>{const{canExecute:t}=il(),n=t("tools"),{data:r={}}=km(),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}=frr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Yrs(),{requestContext:p}=_s();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?cm(om(gx(c?.inputSchema))):Ss({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(Xje,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Krs({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}){const{data:c={},isLoading:u,isError:d,error:f}=ZN(),{data:p={},isLoading:h,isError:m,error:v}=km(),{navigate:y,paths:b}=yn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,v]);const S=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{S.has(C.id)||S.set(C.id,C)})}),Object.values(c).forEach(_=>{S.has(_.id)||S.set(_.id,_)});const w=Array.from(S.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Jl,{options:w,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Jrs=({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(Sy,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Sy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(dn,{icon:o.jsx(ySt,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(dn,{className:"rounded-l-sm text-neutral4!",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:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(ess,{server:t})})]})},ess=({server:e})=>{const{data:t={},isLoading:n}=oLt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(P_,{})}),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(nss,{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 nss=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=yn(),a=P6t[e.toolType||"tool"],i=tss(e._meta);return o.jsxs(Nf,{onClick:()=>n.current?.click(),children:[o.jsx(BCt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Af,{children:[o.jsx(If,{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(dn,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(eh,{children:e.description})]})]})},rss=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=LZ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Jrs,{isLoading:n,server:r})})};function sss(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}=il(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=wje(t,e),{mutateAsync:c,isPending:u,data:d}=vBr(t,e),f=a?sss(a._meta):void 0,{data:p}=St({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.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(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=cm(om(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),v=Ss({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(iLt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(Xje,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},iss=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=wje(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})})},fFt=[{label:"Agent",entityType:Os.AGENT},{label:"Workflow",entityType:Os.WORKFLOW_RUN},{label:"Scorer",entityType:Os.SCORER},{label:"Ingest",entityType:Os.RAG_INGESTION}],uN="rootEntityType",dN={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"},nG=Object.keys(dN),RTe="mastra:metrics:saved-filters";function oss(e){const t=fss(e);try{localStorage.setItem(RTe,t.toString())}catch{}}function lss(){try{localStorage.removeItem(RTe)}catch{}}function pFt(){try{const e=localStorage.getItem(RTe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function css(e){if(e.has(uN))return!0;for(const t of nG)if(e.has(dN[t]))return!0;return!1}function uss({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:fFt.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 dss(e){const t=[],n=new Map([[uN,"rootEntityType"]]);for(const s of nG)n.set(dN[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(uN);for(const r of n)t.append(uN,r);for(const r of nG){const s=dN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function pss(e,t){e.delete(uN);for(const n of nG)e.delete(dN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?uN:dN[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 hss="Any";function XQe(e){const t=e.trim();return t===""||t===hss}const mss=new Set(fFt.map(e=>e.entityType));function KQe(e){const t=e.trim();return mss.has(t)?t:void 0}function gss(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=>!XQe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?KQe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(XQe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=KQe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const hFt=[{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(hFt.map(e=>e.value));function yss(e){return typeof e=="string"&&(vss.has(e)||e==="custom")}const mFt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function rG(){return g.useContext(mFt)}function bss(e,t){return e!=="custom"?hFt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${er(t.from,"MMM d, yyyy")} – ${er(t.to,"MMM d, yyyy")}`:er(t.from,"MMM d, yyyy"):"Custom range"}function xss({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(()=>gss(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=bss(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(mFt.Provider,{value:m,children:e})}const wss=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Sss(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 kss(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 Oss(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=rG(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(dTe,{preset:Sss(e),onPresetChange:i=>{const l=kss(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:wss})}const Kve=1440*60*1e3,_ss={"24h":Kve,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Css(e,t,n){if(e!=="custom"){const r=_ss[e]??Kve;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Kve),end:t?.to??new Date(n)}}function jm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=rG(),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(()=>Css(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 gFt(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function K4({href:e,LinkComponent:t="a"}){return o.jsx(de,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(TOn,{})})}function Ess({href:e,LinkComponent:t="a"}){return o.jsx(de,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(d_n,{})})}const jss=[{dataKey:"p50",label:"p50",color:Pp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Pp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Tss(e){return e==="agents"||e==="workflows"||e==="tools"}function cse({data:e,onPointClick:t}){return e.length===0?o.jsx(Ut.NoData,{message:"No latency data yet"}):o.jsx(LU,{data:e,series:jss,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Nss({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"),p=c[d]?d:u,h=typeof s=="function"?s(p):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,S)=>b+S,0)/v.length)}ms`:"—";return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ut.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Ut.Actions,{children:h}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load latency data"}):o.jsx(Ut.Content,{children:m?o.jsxs(Ic,{value:p,onValueChange:b=>{Tss(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ar,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ar,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(cse,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(cse,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(cse,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ut.NoData,{message:"No latency data yet"})})]})}function Iss(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 Ass(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 vFt(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=Iss(s);l&&e.set(t,l)}function To(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function yFt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function JQe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(bw,"branches"),vFt(a,xw,ww,Sw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Rx,i),r.status&&a.set(Px,r.status),To(a,Ol.entityName,r.entityName??n.entityName),To(a,Ol.threadId,r.threadId??n.threadId),To(a,Ol.resourceId,r.resourceId??n.resourceId),To(a,Ol.entityId,n.entityId),To(a,Ol.runId,n.runId),To(a,Ol.sessionId,n.sessionId),To(a,Ol.requestId,n.requestId),To(a,Ol.userId,n.userId),To(a,Ol.organizationId,n.organizationId),To(a,Ol.experimentId,n.experimentId),To(a,Ol.serviceName,n.serviceName),To(a,Ol.environment,n.environment),yFt(a,Ol.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Rss({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;vFt(a,qb,Vb,Hb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set($x,i),To(a,_l.entityName,r.entityName??n.entityName),To(a,_l.threadId,r.threadId??n.threadId),To(a,_l.resourceId,r.resourceId??n.resourceId),To(a,_l.runId,n.runId),To(a,_l.sessionId,n.sessionId),To(a,_l.requestId,n.requestId),To(a,_l.userId,n.userId),To(a,_l.organizationId,n.organizationId),To(a,_l.experimentId,n.experimentId),To(a,_l.serviceName,n.serviceName),To(a,_l.environment,n.environment),yFt(a,_l.tags,n.tags),r.status==="error"&&a.append(_l.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function _I(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=rG(),a=g.useCallback((c={})=>JQe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>Rss({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Ass(u,d);return JQe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const bFt="1h";async function use(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:bFt,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 Pss(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([use(e,"mastra_agent_duration_ms",t),use(e,"mastra_workflow_duration_ms",t),use(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:bFt}}})}const eYe={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function $ss(){const{data:e,isLoading:t,isError:n}=Pss(),{getTracesHref:r,getBucketTracesHref:s}=_I(),{Link:a}=yn(),i=bs();return o.jsx(Nss,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:eYe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(K4,{href:r({rootEntityType:eYe[l]}),LinkComponent:a})})}function Mss(e){return e==="threads"||e==="resources"}function dse(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Dss({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,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=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(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ut.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ut.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Ut.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ut.Loading,{}):m.isError?o.jsx(Ut.Error,{message:"Failed to load memory data"}):o.jsx(Ut.Content,{children:o.jsxs(Ic,{defaultTab:"threads",value:i,onValueChange:y=>{Mss(y)&&l(y)},className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"threads",children:"Threads"}),o.jsx(Ar,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(me,{columns:"auto auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:dse(y.threadId)}),o.jsx(me.NumberCell,{children:y.resourceId?dse(y.resourceId):"—"}),o.jsx(me.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?xc(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?wg(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(me.RowStatic,{children:S},y.key)})]}):o.jsx(Ut.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(me,{columns:"auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:dse(y.resourceId)}),o.jsx(me.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?xc(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?wg(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(me.RowStatic,{children:S},y.key)})]}):o.jsx(Ut.NoData,{message:"No resource activity yet"})})]})})]})}function J4(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const fse=20;function Lss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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:fse}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:fse}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:fse})]),l=new Map,c=d=>J4(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const pse=20;function Fss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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:pse}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:pse}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:pse})]),l=new Map,c=d=>J4(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function zss(){const e=Lss(),t=Fss(),{getTracesHref:n}=_I(),{Link:r}=yn();return o.jsx(Dss,{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 e5({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 Bss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Uss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 qss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Vss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Hss(){const{data:e,isLoading:t,isError:n}=gFt();return o.jsx(e5,{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 Wss(){const{data:e,isLoading:t,isError:n}=qss();return o.jsx(e5,{label:"Total Model Cost",value:e?.cost!=null?wg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?wg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Zss(){const{data:e,isLoading:t,isError:n}=Vss();return o.jsx(e5,{label:"Total Tokens",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Gss(){const{data:e,isLoading:t,isError:n}=Uss();return o.jsx(e5,{label:"Total Threads",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Qss(){const{data:e,isLoading:t,isError:n}=Bss();return o.jsx(e5,{label:"Total Resources",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Yss({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=>Xss(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(hTe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(fTe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Xss(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 Kss({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.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?wg(l):"—":c.size===1?u=l>0?wg(l,[...c][0]):"—":u="Mixed",o.jsx(Ut.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ut.Actions,{children:s}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load model usage data"}):o.jsx(Ut.Content,{children:i?o.jsxs(me,{columns:"auto auto auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Model"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(me.NumberCell,{children:l.input}),o.jsx(me.NumberCell,{children:l.output}),o.jsx(me.NumberCell,{children:l.cacheRead}),o.jsx(me.NumberCell,{children:l.cacheWrite}),o.jsx(me.NumberCell,{highlight:!0,children:l.cost!=null?wg(l.cost,l.costUnit):"—"})]});return c?o.jsx(me.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(me.RowStatic,{children:u},l.model)})]}):o.jsx(Ut.NoData,{message:"No model usage data yet"})})]})}function Jss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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=>J4(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",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:xc(f.input),output:xc(f.output),cacheRead:xc(f.cacheRead),cacheWrite:xc(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function eas(){const{data:e,isLoading:t,isError:n}=Jss(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(Kss,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Os.AGENT}),actions:o.jsx(K4,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function tas(e){return e==="tokens"||e==="cost"}function nas({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,S)=>b+S.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,S)=>b+(S.cost??0),0):0,y=h&&v>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ut.Summary,{value:wg(v,m),label:"Total cost"}):o.jsx(Ut.Summary,{value:xc(d),label:"Total tokens"})),u&&s?o.jsx(Ut.Actions,{children:s}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load token usage data"}):o.jsx(Ut.Content,{children:u?o.jsxs(Ic,{defaultTab:"tokens",value:i,onValueChange:b=>{tas(b)&&l(b)},className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(cN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Pp.blueDark},{label:"Output",color:Pp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:xc})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(cN,{LinkComponent:a,data:f.slice().sort((b,S)=>(S.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Pp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>wg(b,m)}):o.jsx(Ut.NoData,{message:"No cost data yet"})})]}):o.jsx(Ut.NoData,{message:"No token usage data yet"})})]})}function ras(){const e=We(),{filters:t,filterKey:n}=jm();return St({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=>J4(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 sas(){const{data:e,isLoading:t,isError:n}=ras(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(nas,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Os.AGENT,entityName:a.name}),actions:o.jsx(K4,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function Jve(e,t=xc){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const aas=[{dataKey:"input",label:"Input tokens",color:Pp.blue,aggregate:Jve("input")},{dataKey:"output",label:"Output tokens",color:Pp.yellow,aggregate:Jve("output")}];function ias(e){return e==="tokens"||e==="cost"}function oas({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,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,S=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Pp.purple,aggregate:Jve("cost",k=>wg(k,v))}];return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Token usage over time",description:S}),u&&(a==="cost"&&b?o.jsx(Ut.Summary,{value:wg(y,v),label:"Total cost"}):o.jsx(Ut.Summary,{value:xc(d),label:"Total tokens"})),u&&s?o.jsx(Ut.Actions,{children:s}):null]}),n?o.jsx(Ut.Loading,{}):r?o.jsx(Ut.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ut.Content,{children:u?o.jsxs(Ic,{defaultTab:"tokens",value:a,onValueChange:k=>{ias(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(LU,{data:c,series:aas})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(LU,{data:p,series:w}):o.jsx(Ut.NoData,{message:"No cost data yet"})})]}):o.jsx(Ut.NoData,{message:"No token usage data yet"})})]})}function las(e){return e==="24h"?"1h":"1d"}function cas(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 tYe(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 uas(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function das(){const e=We(),{datePreset:t,filters:n,filterKey:r}=jm(),s=las(t);return St({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 tYe(l,a.series[0],"input"),tYe(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:cas(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:uas(u)}}),interval:s}}})}function fas(){const{data:e,isLoading:t,isError:n}=das(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(oas,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(K4,{href:r(),LinkComponent:s})})}function hse({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(cN,{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:Pp.blueDark},{label:"Errors",color:Pp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:xc})}function pas({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,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ut.Summary,{value:xc(f),label:"Total runs"}),u?o.jsx(Ut.Actions,{children:u}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load trace volume data"}):o.jsx(Ut.Content,{children:d?o.jsxs(Ic,{value:l,onValueChange:c,defaultTab:"agents",className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"agents",children:"Agents"}),o.jsx(Ar,{value:"workflows",children:"Workflows"}),o.jsx(Ar,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(hse,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(hse,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(hse,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No tool data yet"})})]}):o.jsx(Ut.NoData,{message:"No trace volume data yet"})})]})}async function mse(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=J4(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 has(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mse(e,"mastra_agent_duration_ms",t),mse(e,"mastra_workflow_duration_ms",t),mse(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const lF={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function mas(){const{data:e,isLoading:t,isError:n}=has(),{getTracesHref:r,getLogsHref:s}=_I(),{Link:a}=yn();return o.jsx(pas,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:lF[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:lF[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(K4,{href:r({rootEntityType:lF[i]}),LinkComponent:a}),o.jsx(Ess,{href:s({rootEntityType:lF[i],status:"error"}),LinkComponent:a})]})})}const gas=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),gse="period",cF="dateFrom",uF="dateTo";function vas(){const[e,t]=ga(),n=e.get(gse),r=yss(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(cF)),p=d(e.get(uF));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>dss(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(gse):p.set(gse,d),d!=="custom"&&(p.delete(cF),p.delete(uF)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(cF,d.from.toISOString()):p.delete(cF),d?.to?p.set(uF,d.to.toISOString()):p.delete(uF),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return pss(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,css(e)))return;const d=pFt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(xss,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(yas,{})})}function yas(){const[e]=ga(),{error:t,isLoading:n}=gFt(),{filterTokens:r,setFilterTokens:s}=rG(),[a,i]=g.useState(),{data:l,isLoading:c}=L3(),u=l?.observabilityStorageType,d=u?gas.has(u):!1,f=u==="ObservabilityInMemory",{data:p,isLoading:h}=STe(),{data:m,isLoading:v}=bTe(),{data:y,isLoading:b}=wTe(),{data:S,isLoading:w}=xTe(),k=g.useMemo(()=>uss({availableTags:p??[],availableEntityNames:m??[],availableServiceNames:y??[],availableEnvironments:S??[],loading:{tags:h,entityNames:v,serviceNames:b,environments:w}}),[p,m,y,S,h,v,b,w]),[_,C]=g.useState(()=>pFt()!==null),j=g.useCallback(()=>{oss(e),C(!0),De.success("Filters setting for Metrics saved")},[e]),E=g.useCallback(()=>{lss(),C(!1),De.success("Filters setting for Metrics cleared up")},[]),N=g.useCallback(()=>{s([])},[s]),I=g.useCallback(()=>{const A=r.map(P=>{const F=k.find(D=>D.id===P.fieldId);return F?F.kind==="text"?{fieldId:P.fieldId,value:""}:F.kind==="pick-multi"?F.multi?{fieldId:P.fieldId,value:[]}:{fieldId:P.fieldId,value:"Any"}:F.kind==="multi-select"?{fieldId:P.fieldId,value:[]}:P:P});s(A)},[k,r,s]);return t&&gs(t)?o.jsx(lr,{children:o.jsx(Vs,{})}):t&&ys(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(zi,{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(Oss,{}),o.jsx(mTe,{fields:k,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Yss,{isLoading:n,filterFields:k,filterTokens:r,onFilterTokensChange:s,onClear:I,onRemoveAll:N,onSave:j,onRemoveSaved:_?E:void 0,autoFocusFilterFieldId:a})]}),c?null:d?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[f&&o.jsx(In,{variant:"info",title:"Metrics are not persisted",children:o.jsx(In.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(Gve,{children:[o.jsx(Hss,{}),o.jsx(Wss,{}),o.jsx(Zss,{}),o.jsx(Gss,{}),o.jsx(Qss,{})]}),o.jsxs(Gve,{children:[o.jsx(eas,{}),o.jsx(sas,{}),o.jsx(fas,{}),o.jsx(zss,{}),o.jsx(mas,{}),o.jsx($ss,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}function bas(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=M6t(),{isCmsAvailable:s}=Z1(),[a,i]=g.useState(""),l=t?.promptBlocks??[];return r&&gs(r)?o.jsx(lr,{children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(WGr,{})}):o.jsxs(Lt,{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(jf,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(de,{as:Ma,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Hr,{}),"Create Prompt"]})]})}),o.jsx(HGr,{promptBlocks:l,isLoading:n,search:a})]})}function xas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(ZBr,{children:o.jsx(xve,{})})})})}const was=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:bun,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Dlt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:Qj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Hlt,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:Llt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Sas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:was.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(Oa,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function kas(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&gs(n))return o.jsx(lr,{children:o.jsx(Vs,{})});if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(aZr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(oZr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(sZr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Oas(){const{scorerId:e}=ur(),[t,n]=ga(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=$Wr(e),{data:d={},isLoading:f,error:p}=km(),{isLoading:h,error:m}=zy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:S,hasNextPage:w,setEndOfListElement:k}=PWr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(B=>d[B]).map(B=>({value:B,label:d[B].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(B=>({value:B,label:B,type:"WORKFLOW"}))||[],[c?.workflowIds]),j=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),E=t.get("entity")??"all",N=j.find(B=>B.value===E);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const B=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${B}`)}},[u]),g.useEffect(()=>{if(p){const B=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${B}`)}},[p]),g.useEffect(()=>{if(m){const B=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${B}`)}},[m]);const I=B=>{B?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",B.value),G})};g.useEffect(()=>{const B=t.get("scoreId")??void 0;if(B===s)return;if(!B){a(void 0);return}v.find(G=>G.id===B)&&a(B)},[t,v]);const A=g.useCallback(B=>{a(B||void 0),n(M=>{const G=new URLSearchParams(M);return B?G.set("scoreId",B):G.delete("scoreId"),G})},[n]);if(!c)return null;const P=gs(u)||gs(p)||gs(m),F=u&&ys(u),D=!P&&!F&&(u||p||m),V=!y&&v.length===0,H=i?.value!=="all",L=c?.scorer?.source==="stored"?o.jsx(Iy,{owner:"scorer-detail",children:o.jsxs(de,{variant:"default",as:Ma,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(sm,{})," Edit"]})}):null;if(P||F||D||V&&!H){const B=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",children:[L,o.jsx(Lt.MainArea,{isCentered:!0,children:P?o.jsx(Vs,{}):F?o.jsx(Ds,{resource:"scorers"}):D?o.jsx(zi,{title:"Failed to load scorer",message:B}):o.jsx(TWr,{})})]})}return o.jsxs(Lt,{width:"wide",children:[L,o.jsx(Lt.TopArea,{children:o.jsx(NWr,{selectedEntity:i,entityOptions:j,onEntityChange:I,onReset:()=>{n(B=>{const M=new URLSearchParams(B);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(jWr,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:S,hasNextPage:w,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function _as({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:K("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Rt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const xFt=[{value:"dark",label:"Dark",Icon:Gdn},{value:"light",label:"Light",Icon:opn},{value:"system",label:"System",Icon:tct}],Cas=e=>xFt.some(t=>t.value===e);function Eas({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full 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 jas=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Xq(),{theme:r,setTheme:s}=RN();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(age,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(_as,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(da,{value:r,onValueChange:a=>{Cas(a)&&s(a)},children:[o.jsx(pa,{id:"theme",className:"w-full sm:w-48",children:o.jsx(fa,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(ha,{children:xFt.map(a=>o.jsx(Fr,{value:a.value,children:o.jsx(Eas,{option:a})},a.value))})]})})}),o.jsx(age,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(tjt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Tas(){const[e]=ga(),t=bs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(uFt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const wFt=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function Nas(e){return e.replace(/\/$/,"").split("/").pop()}function sG({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 Ias({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:"h-16 bg-surface3 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:"w-full h-full bg-cover thumb transition-scale 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:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",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(al,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Jp,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(nct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(mD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(P_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 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:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(wFt,{})," ",Nas(a.githubUrl)]})})]},a.slug)})})}function Aas({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(jT,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(wc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(wc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(de,{onClick:c,children:["Reset ",o.jsx(vs,{})]})]})}function Ras(){const{data:e,isLoading:t}=tXn(),{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(S=>{f.push({value:S,label:S})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(S=>{p.push({value:S,label:S})});const h=(S,w)=>{w==="tag"?i(S):w==="provider"&&c(S)},m=S=>{d(S)},v=()=>{i("all"),c("all"),d("")},y=n.filter(S=>!(u&&!S.title.toLowerCase().includes(u)&&!S.description.toLowerCase().includes(u)||a!=="all"&&!S.tags.includes(a)||l!=="all"&&!S.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(cs,{children:[o.jsx(a0e,{children:o.jsxs(Gpt,{children:[o.jsx(Ue,{children:o.jsx(Gv,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Aas,{selectedTag:a,onTagChange:S=>h(S,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:S=>h(S,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Ias,{templates:y,linkComponent:Ma,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const Pas="1.50.1-alpha.2";function $as({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(Ep,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Gun,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(sG,{className:"space-y-4 text-neutral3 mb-8 content-center",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:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",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:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function Mas({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(sG,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",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(rct,{})]}),o.jsx(wc,{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] gap-4 items-start",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(Gt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(gO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(gO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",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(p6t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(de,{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(Gt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(gm,{})]})})]})})}function Das({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(Gv,{}),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 lg:grid-cols-[1fr_1fr] gap-x-24",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:"shrink-0 mt-0.5",children:o.jsx(Dx,{className:"w-[1.1em] h-[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(ube,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",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 px-1.5 py-0.5 rounded text-ui-sm 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:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(wFt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Zje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Las(e){switch(e){case"running":return o.jsx(Gt,{});case"success":return o.jsx(mx,{});case"failed":return o.jsx(Fu,{});default:return null}}function Fas({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:K("grid gap-6 grid-cols-[1fr_auto] py-3 px-4 rounded-lg",ms.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("text-ui-md min-w-6 flex justify-end",ms.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:K("text-ui-md",ms.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:K("w-[1.75rem] h-[1.75rem] rounded-full flex items-center justify-center self-center",ms.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:Las(t.status)})]})}function zas({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(Fas,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Bas({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex justify-center flex-col gap-4 content-center w-full",children:[o.jsx("div",{className:"grid grid-cols-[0_repeat(9,1fr)] w-full",children:e.map((r,s)=>o.jsx("div",{className:K("flex justify-end items-center relative h-[2rem]",ms.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("w-[2rem] h-[2rem] rounded-full flex items-center justify-center self-center absolute right-0 translate-x-[50%] bg-surface3 z-10 text-neutral3 font-bold text-ui-sm",ms.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Gt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-xs text-neutral3 text-center",ms.colors),children:[n," of ",t," steps completed"]})]})}function Uas({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)),p=f.length,h=()=>{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(sG,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(Bas,{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(sfn,{}),l||"Something went wrong"]}),u&&o.jsx(zas,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Gt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function qas({name:e,installedEntities:t}){return o.jsxs(sG,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(rct,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",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(Zje,{data:t})]})}function Vas(){const{templateSlug:e}=ur(),[t,n]=ga(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,S]=g.useState(""),[w,k]=g.useState(!1),[_,C]=g.useState(!1),[j,E]=g.useState([]),{data:N,isLoading:I}=nXn({repoOrSlug:e,owner:"mastra-ai"}),P=Pas?.includes("beta")??!1?"beta":"main",{data:F,isLoading:D}=rXn({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:V,isLoading:H}=sXn(),{mutateAsync:L,isPending:z}=aXn(),{mutateAsync:B}=iXn(),{streamInstall:M,streamResult:G,isStreaming:q}=lXn(V),{observeInstall:$,streamResult:U,isStreaming:Z}=cXn(V);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),S(ne),B({runId:ne}).then(ue=>{const pe=ue.snapshot;if(pe?.status==="success"&&pe?.result?.success)y(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ve,errors:ye}=pe.result.validationResults,Se=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Se),E(ye||[])}else{const ve=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,B]),g.useEffect(()=>{const ne=t.get("runId"),ue=t.get("resume"),pe=t.get("provider");if(ne&&ue==="true"&&pe&&!q&&!Z&&!w&&!_&&V){S(ne),k(!0);try{B({runId:ne}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(oe=>{const ve=new URLSearchParams(oe);return ve.delete("resume"),ve})}).catch(oe=>{console.error("❌ Failed to resume template installation:",oe),oe.message?.includes("404")||oe.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(oe){console.error("❌ Auto-resume failed with error:",oe),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,w,_,V,B,$,n]);const X=[{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(Jp,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(al,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(mD,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Pv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(xN,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{F&&d(F)},[F]),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 ee=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ce=async()=>{const ne=Object.entries(u).reduce((ue,[pe,oe])=>(oe===""&&ue.push(pe),ue),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),S(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:oe}=await L({});S(oe),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",oe),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:oe})}catch(ue){C(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=ne=>{const{name:ue,value:pe}=ne.target;pe.trim()===""?p(oe=>[...oe,ue]):p(oe=>oe.filter(ve=>ve!==ue)),d(oe=>({...oe,[ue]:pe}))};return o.jsx(cs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(Das,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(Uas,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:V}),v&&o.jsx(qas,{name:N.title,installedEntities:J,linkComponent:Ma}),h&&o.jsx($as,{errorMsg:h,validationErrors:j.length>0?j:G?.validationResults?.errors||U?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(Mas,{providerOptions:X,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:ce,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Has=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(cGr,{toolId:e,agentId:t})})},Was=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Xrs,{toolId:e})})};function Zas(){const{traceId:e}=ur(),[t,n]=ga(),r=bs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:S,isLoading:w,error:k}=sH(e),_=g.useMemo(()=>S?.spans??[],[S?.spans]),C=g.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:j,isLoading:E}=HN(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:N,isLoading:I}=ih(),{data:A,isLoading:P}=I6t({traceId:e,spanId:c??void 0,page:m}),[F,D]=g.useState(0);g.useEffect(()=>D(0),[e,c]);const{data:V,isLoading:H}=J9t({traceId:e,page:F});g.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(ce=>ce.id===l);ae&&f(ae)}},[l,A?.scores,d]);const L=g.useCallback(ae=>{const ce=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?ce.delete(Y):ce.set(Y,ne);n(ce,{replace:!0})},[t,n]),z=g.useCallback(ae=>{const ce=ae??null,Y=ce===c;u(ce),Y||(f(void 0),h("details"),L({spanId:ce,tab:null,scoreId:null}))},[c,L]),B=g.useCallback(()=>{u(null),f(void 0),h("details"),L({spanId:null,tab:null,scoreId:null})},[L]),M=g.useCallback(ae=>{u(ae),f(void 0),h("details"),L({spanId:ae,tab:null,scoreId:null})},[L]),{handlePreviousSpan:G,handleNextSpan:q}=aH(_,c,M),$=g.useCallback(ae=>{const ce=ae;h(ce),f(void 0),L({tab:ce==="details"?null:ce,scoreId:null})},[L]),U=g.useCallback(ae=>{f(ae),L({scoreId:ae.id})},[L]),Z=g.useCallback(()=>{f(void 0),L({scoreId:null})},[L]),X=g.useCallback(()=>{r("/observability")},[r]),te=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),L({spanId:C.spanId,tab:"scoring",scoreId:null})):L({tab:"scoring"})},[C,c,L]),J=C?o.jsx(Iy,{owner:"trace-detail",children:o.jsxs(Dr,{children:[o.jsxs(de,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(Bcn,{}),"Evaluate"]}),o.jsxs(de,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(gd,{}),"Save"]})]})}):null,ee=C?o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(U9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Lt,{height:"full",children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(q9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Lt,{children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(G9t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:K("grid h-full min-h-0 gap-4 overflow-hidden items-start mt-4",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(gTe,{traceId:e,spans:_,isLoading:w,onClose:X,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!w&&o.jsxs("div",{className:K("grid gap-4 max-h-full min-h-0 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(rH,{traceId:e,spanId:c,span:j?.span,isLoading:E,onClose:B,onPrevious:G,onNext:q,activeTab:p,onTabChange:$,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Y9t,{feedbackData:V,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:ce,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K9t,{traceId:ce,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===Os.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===Os.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(X9t,{scoresData:A,onPageChange:v,isLoadingScoresData:P,onScoreSelect:U})]})}),d&&o.jsx(Wje,{score:d,onClose:Z})]})]})]})}function Gas(){const{data:e,isLoading:t,error:n}=zy(),[r,s]=g.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(x3r,{})}):o.jsxs(Lt,{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(jf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(de,{as:Ma,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(fD,{}),"Schedules"]})]})}),o.jsx(b3r,{workflows:e||{},isLoading:t,search:r})]})}const Qas={active:"bg-accent1",paused:"bg-accent3"},Yas={active:"text-accent1",paused:"text-accent3"},SFt=({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 ${Qas[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Yas[e]}`,children:e})]}),Dj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),cP=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 kFt({status:e}){const{icon:t,color:n}=Xas(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Xas(e){switch(e){case"success":return{icon:o.jsx(ea,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(vs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Gt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(lq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Of,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(Gj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const nYe="auto auto auto auto 1fr";function Kas(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 Jas(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 eis=3e4,tis=5*6e4;function nis({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(nl,{columns:nYe}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:nYe,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Jas(u),f=`Scheduled ${Dj(c.scheduledFireAt)} — published ${Dj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>eis&&m<=tis,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),S=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),w=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:S}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(Ep,{size:14}),"publish failed"]}):c.run?o.jsx(kFt,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Ep,{size:14})})}),o.jsx(Ln,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:cP(c.actualFireAt)}),v?o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Ep,{size:14})})}),o.jsxs(Ln,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Kas(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:w},y):o.jsx(me.RowStatic,{children:w},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const ris=e=>{const t=We();return St({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},rYe=25,sis=e=>{const t=We(),{inView:n,setRef:r}=N_(),s=P1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:rYe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<rYe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.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}},ais=e=>{const t=We(),n=Br();return Rn({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"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function dF({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function iis(){const{scheduleId:e}=ur(),{paths:t}=yn(),{data:n,error:r}=ris(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=sis(e),d=ais(e);if(r&&gs(r))return o.jsx(lr,{children:o.jsx(Vs,{})});if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=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(de,{as:Ma,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Tc,{}),"Back to schedules"]}),f?o.jsx(de,{as:Ma,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(de,{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(sct,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Lp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(dF,{label:p?"Agent":"Workflow",children:f?o.jsx(Ma,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(Ma,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(dF,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(dF,{label:"Status",children:o.jsx(SFt,{status:n.status})}),o.jsx(dF,{label:"Next fire",children:o.jsx("span",{title:Dj(n.nextFireAt),children:cP(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(zi,{title:"Failed to load trigger history",message:i.message}):o.jsx(nis,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const sYe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function ois({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(nl,{columns:sYe}):o.jsxs(me,{columns:sYe,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.workflowId??i.agentId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(SFt,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:Dj(i.nextFireAt),children:cP(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(kFt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Dj(i.lastFireAt),children:i.lastFireAt?cP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Dj(i.lastFireAt),children:cP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function lis({workflowId:e}={}){const{data:t,isLoading:n,error:r}=r0e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(zi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(ois,{schedules:t??[],isLoading:n,search:s})})]})}function cis(){const[e]=ga(),t=e.get("workflowId")??void 0,{error:n}=r0e(t?{workflowId:t}:{});return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(lis,{workflowId:t})})})}function uis({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=$1e({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=Ewt(r),[d]=jwt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=sPt({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:"w-full h-full relative bg-surface1",children:a?o.jsxs(Cwt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(K_e,{position:"bottom-left"}),o.jsx(Nwt,{variant:ty.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Gt,{})})})}function dis(){const{stepDetail:e,closeStepDetail:t}=ZV();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(afe,{className:"w-4 h-4",style:{color:Cu.map}}),e.type==="nested-graph"&&o.jsx(jd,{className:"w-4 h-4",style:{color:Cu.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:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(vs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(sP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(P1e,{children:o.jsx(uis,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function fis(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function pis(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 his({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 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:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(Ue,{children:o.jsx(lq,{})}),"Step suspended"]}),o.jsx(dn,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?cm(om(gx(i.resumeSchema))):op(dr(),lT());return o.jsx(mis,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function mis({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 font-medium truncate",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:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Ydn,{})}),"The step is asking"]}),o.jsxs(xf,{open:a,onOpenChange:i,children:[o.jsxs(Od,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(Ue,{children:o.jsx(la,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:pis(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:fis(e.suspendPayload)})]}),o.jsx(_d,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Yr,{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:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Jdn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(B7,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Lp,{}),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 gis(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext($l),{runId:a}=ur(),i=Dwt(e,r??""),l=yGn(),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:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(his,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const vis=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"})]}),yis=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"})]}),bis=e=>e.includes("."),xis=e=>e==="input"||e.endsWith(".input"),wis=1;function Sis(e){return`${Number((e/1e3).toPrecision(3))}s`}function kis(e,t){const n=Object.entries(e).filter(([i])=>!xis(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,p=Math.max(d/a*100,wis);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:bis(i)}})}const Ois=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(vis,{className:"text-accent1"}),e==="failed"&&o.jsx(yis,{className:"text-accent2"}),e==="suspended"&&o.jsx(lq,{className:"text-accent3"}),e==="waiting"&&o.jsx(sfe,{className:"text-accent5"}),e==="skipped"&&o.jsx(sfe,{className:"text-icon3"}),e==="running"&&o.jsx(Ks,{className:"text-accent6 animate-spin"})]}),_is={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function OFt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const aYe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Cis=e=>{const t=e;return Q2t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Eis=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Cis(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(Ois,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(de,{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(tpn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(hU,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:OFt(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",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 ${_is[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(de,{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(Jfn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:Sis(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function jis(){const{steps:e}=u4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sV(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);d0e(f,{enabled:!l});const p=kis(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.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:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 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:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Aa,{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:p.map((m,v)=>o.jsx(Eis,{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:aYe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:aYe(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(Fwt,{data:u.data,title:`${OFt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Tis=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=ZV();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(fPt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(gis,{}),o.jsx(jis,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(dis,{})})]})},iYe=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=w3(e);return r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(K1e,{children:o.jsx(Tis,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Nis(e,t){if(e==null)return{};var n,r,s=qbt(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 eye(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 Iis(e){if(Array.isArray(e))return eye(e)}function Ais(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Ris(e,t){if(e){if(typeof e=="string")return eye(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)?eye(e,t):void 0}}function Pis(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
728
|
+
]`})]})]})}function Tts({errors:e,maxErrors:t=5}){if(e.length===0)return null;const n=e.slice(0,t),r=e.length-t;return o.jsxs("div",{className:"bg-accent2/10 border border-accent2/30 rounded-md p-3",children:[o.jsxs("div",{className:"flex items-center gap-2 text-accent2 mb-2",children:[o.jsx(Ue,{children:o.jsx(Ep,{className:"w-4 h-4"})}),o.jsxs("span",{className:"font-medium text-sm",children:[e.length," validation error",e.length!==1?"s":""]})]}),o.jsx("ul",{className:"text-sm text-accent2/80 space-y-1",children:n.map((s,a)=>o.jsxs("li",{className:"flex gap-2",children:[o.jsx("span",{className:"shrink-0",children:"•"}),o.jsx("span",{children:s.message})]},a))}),r>0&&o.jsxs("div",{className:"text-xs text-accent2/60 mt-2",children:["+",r," more error",r!==1?"s":""]})]})}function Nts({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("upload"),[i,l]=g.useState(null),[c,u]=g.useState({current:0,total:0}),[d,f]=g.useState(null),[p,h]=g.useState(!1),{parseFile:m,isParsing:v,error:y}=nes(),{batchInsertItems:b}=Ei(),S=g.useCallback(async I=>{try{const A=await m(I);l(A),a("preview")}catch{}},[m]),w=g.useCallback(async()=>{if(!i||i.items.length===0)return;a("importing"),h(!0);const{items:I}=i;u({current:0,total:I.length});try{await b.mutateAsync({datasetId:e,items:I.map(A=>({input:A.input,groundTruth:A.groundTruth,metadata:A.metadata}))}),f({success:I.length,errors:0})}catch{f({success:0,errors:I.length})}u({current:I.length,total:I.length}),h(!1),a("complete")},[i,b,e]),k=g.useCallback(()=>{n(!1),r?.(),d&&d.success>0&&De.success(`Imported ${d.success} item${d.success!==1?"s":""}`),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150)},[n,r,d]),_=g.useCallback(()=>{p||(n(!1),setTimeout(()=>{a("upload"),l(null),u({current:0,total:0}),f(null)},150))},[p,n]),C=i&&i.items.length>0&&i.errors.length===0,j=()=>{switch(s){case"upload":return o.jsx(jts,{onFileSelect:S,isParsing:v,error:y?.message});case"preview":return i?o.jsx("div",{className:"flex flex-col gap-4",children:i.errors.length>0?o.jsxs(o.Fragment,{children:[o.jsx(Tts,{errors:i.errors}),o.jsx("div",{className:"text-sm text-neutral4",children:"Please fix the errors in your JSON file and try again."})]}):o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"text-sm text-neutral4",children:["Found ",i.items.length," valid item",i.items.length!==1?"s":""," to import."]}),o.jsx(Ets,{items:i.items,maxRows:5})]})}):null;case"importing":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx(Gt,{}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Importing items..."}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[c.current," of ",c.total]})]})]});case"complete":return o.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[o.jsx("div",{className:"text-4xl",children:d&&d.errors===0?"✓":"⚠"}),o.jsxs("div",{className:"text-center",children:[o.jsx("div",{className:"text-lg font-medium text-neutral1",children:"Import Complete"}),o.jsxs("div",{className:"text-sm text-neutral4 mt-1",children:[d?.success??0," item",d?.success!==1?"s":""," imported",d&&d.errors>0&&o.jsxs("span",{className:"text-accent2",children:[" ","(",d.errors," error",d.errors!==1?"s":"",")"]})]})]})]})}},E=()=>{switch(s){case"upload":return o.jsx(de,{onClick:_,children:"Cancel"});case"preview":return o.jsxs(o.Fragment,{children:[o.jsx(de,{onClick:()=>a("upload"),children:"Back"}),o.jsxs(de,{variant:"primary",onClick:w,disabled:!C,children:["Import ",i?.items.length??0," Item",i?.items.length!==1?"s":""]})]});case"importing":return null;case"complete":return o.jsx(de,{variant:"primary",onClick:k,children:"Done"})}},N={upload:"Import JSON",preview:"Preview Data",importing:"Importing",complete:"Import Complete"};return o.jsx(br,{open:t,onOpenChange:_,children:o.jsxs(xr,{className:"max-w-2xl max-h-[90vh]",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:N[s]}),o.jsx(Qs,{children:"Import dataset items from a JSON file."})]}),o.jsx(Pr,{className:"min-h-[200px] max-h-[50vh] overflow-y-auto",children:j()}),o.jsx(_c,{className:"px-6 pt-4 flex justify-end gap-2",children:E()})]})})}const CTe=e=>{const t=We(),{data:n}=JM(e),r=n?.experiments;return St({queryKey:["dataset-review-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="needs-review").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})},Its=e=>{const t=We(),{data:n}=JM(e),r=n?.experiments;return St({queryKey:["dataset-completed-items",e,r?.map(s=>s.id)],queryFn:async()=>!r||r.length===0?[]:(await Promise.all(r.map(async a=>{if(!a.datasetId)return[];try{const{results:i}=await t.listDatasetExperimentResults(a.datasetId,a.id);return i.filter(l=>l.status==="complete").map(l=>({id:l.id,input:l.input,output:l.output,error:l.error,itemId:l.itemId,experimentId:l.experimentId,datasetId:a.datasetId??void 0,traceId:l.traceId??void 0,scores:l.scores?Object.fromEntries(l.scores.map(c=>[c.scorerId,c.score??0])):{},tags:l.tags??[],comment:""}))}catch{return[]}}))).flat(),enabled:!!e&&!!r&&r.length>0,refetchOnWindowFocus:!1})};function Ats(e,t){if(typeof e=="string")return e.length>t?e.slice(0,t)+"...":e;try{const n=JSON.stringify(e);return n.length>t?n.slice(0,t)+"...":n}catch{return String(e)}}function aFt({datasetId:e,experimentId:t,featuredItemId:n}){const r=We(),{data:s}=Vx(e),{data:a,isLoading:i}=CTe(e),{data:l,isLoading:c}=Its(e),u=g.useMemo(()=>t?(a??[]).filter(Ee=>Ee.experimentId===t):a,[a,t]),d=g.useMemo(()=>t?(l??[]).filter(Ee=>Ee.experimentId===t):l,[l,t]),{updateExperimentResult:f}=Ei(),[p,h]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&h(n)},[n]);const[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,w]=g.useState(!1),[k,_]=g.useState(!1),[C,j]=g.useState(!1),[E,N]=g.useState(""),[I,A]=g.useState(""),[P,F]=g.useState(""),[D,V]=g.useState([]),[H,L]=g.useState(!1),[z,B]=g.useState(null),M=g.useMemo(()=>z??u??[],[z,u]);g.useEffect(()=>{B(null)},[e,t]),g.useEffect(()=>{u&&z===null&&B(u)},[u,z]);const G=g.useMemo(()=>{const Ee=new Set;if(s?.tags)for(const _e of s.tags)Ee.add(_e);for(const _e of M)for(const Ce of _e.tags)Ee.add(Ce);return[...Ee].sort()},[s,M]),q=g.useCallback(Ee=>{!s||!e||(s.tags??[]).includes(Ee)},[s,e]),$=g.useMemo(()=>m?m==="__untagged__"?M.filter(Ee=>Ee.tags.length===0):M.filter(Ee=>Ee.tags.includes(m)):M,[M,m]),U=g.useMemo(()=>{const Ee=new Map;for(const _e of M)for(const Ce of _e.tags)Ee.set(Ce,(Ee.get(Ce)??0)+1);return[...Ee.entries()].sort((_e,Ce)=>Ce[1]-_e[1])},[M]),Z=g.useMemo(()=>M.filter(Ee=>Ee.tags.length===0).length,[M]),X=g.useMemo(()=>{let Ee=0;return m&&Ee++,S&&Ee++,Ee},[m,S]),te=g.useCallback((Ee,_e)=>{B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,tags:_e}:Re));const Ce=M.find(Oe=>Oe.id===Ee);Ce?.experimentId&&Ce?.datasetId&&f.mutate({datasetId:Ce.datasetId,experimentId:Ce.experimentId,resultId:Ce.id,tags:_e})},[M,f]),J=g.useCallback((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee);Ce?.traceId&&_e!==void 0&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"rating",value:_e==="positive"?1:-1,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,rating:_e}:Re))},[M,r]),ee=g.useCallback((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee);Ce?.traceId&&r.createFeedback({feedback:{traceId:Ce.traceId,source:"studio",feedbackSource:"studio",feedbackType:"comment",value:_e,comment:_e,experimentId:Ce.experimentId??void 0,sourceId:Ce.id}}).catch(()=>{}),B(Oe=>(Oe??[]).map(Re=>Re.id===Ee?{...Re,comment:_e}:Re))},[M,r]),ae=g.useCallback(Ee=>{const _e=M.find(Ce=>Ce.id===Ee);B(Ce=>(Ce??[]).filter(Oe=>Oe.id!==Ee)),b(Ce=>{const Oe=new Set(Ce);return Oe.delete(Ee),Oe}),p===Ee&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:null})},[M,f,p]),ce=g.useCallback(Ee=>{const _e=M.find(Ce=>Ce.id===Ee);B(Ce=>(Ce??[]).filter(Oe=>Oe.id!==Ee)),b(Ce=>{const Oe=new Set(Ce);return Oe.delete(Ee),Oe}),p===Ee&&h(null),_e?.experimentId&&_e?.datasetId&&f.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:"complete"})},[M,f,p]),Y=g.useMemo(()=>{const Ee=S?d??[]:$;return!S||!m?Ee:m==="__untagged__"?Ee.filter(_e=>_e.tags.length===0):Ee.filter(_e=>_e.tags.includes(m))},[S,d,$,m]),ne=S?c:!1,ue=g.useMemo(()=>new Set(Y.map(Ee=>Ee.id)),[Y]),pe=g.useMemo(()=>[...y].filter(Ee=>ue.has(Ee)).length,[y,ue]),oe=Y.length>0&&pe===Y.length,ve=pe>0&&!oe,ye=g.useCallback(Ee=>{b(_e=>{const Ce=new Set(_e);return Ce.has(Ee)?Ce.delete(Ee):Ce.add(Ee),Ce})},[]),Se=g.useCallback(()=>{b(oe?new Set:new Set(Y.map(Ee=>Ee.id)))},[oe,Y]),Ne=g.useCallback(Ee=>{for(const _e of y){const Ce=M.find(Oe=>Oe.id===_e);Ce&&!Ce.tags.includes(Ee)&&te(_e,[...Ce.tags,Ee])}},[M,y,te]),ke=g.useCallback(Ee=>{for(const _e of y){const Ce=M.find(Oe=>Oe.id===_e);Ce&&Ce.tags.includes(Ee)&&te(_e,Ce.tags.filter(Oe=>Oe!==Ee))}},[M,y,te]),Ie=g.useCallback(()=>{for(const Ee of y)ce(Ee);b(new Set)},[y,ce]),ze=g.useCallback(()=>{for(const Ee of y)ae(Ee);b(new Set)},[y,ae]),le=g.useCallback(()=>{N(""),j(!0)},[]),se=g.useCallback(async()=>{if(!(!I||!P)){_(!0),j(!1);try{const Ee=M.filter(Ce=>y.has(Ce.id));if(Ee.length===0){_(!1);return}const _e=await r.clusterFailures({modelId:`${I}/${P}`,items:Ee.map(Ce=>({id:Ce.id,input:Ce.input,output:Ce.output??void 0,error:typeof Ce.error=="string"?Ce.error:Ce.error?String(Ce.error):void 0,scores:Ce.scores,existingTags:Ce.tags.length>0?Ce.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:E||void 0});_e.proposedTags&&_e.proposedTags.length>0&&(V(_e.proposedTags.map(Ce=>({...Ce,accepted:!0}))),L(!0))}catch(Ee){console.error("Analysis failed:",Ee)}finally{_(!1)}}},[I,P,M,y,r,G,E]),re=g.useCallback(()=>{for(const Ee of D){if(!Ee.accepted)continue;const _e=M.find(Ce=>Ce.id===Ee.itemId);if(_e){const Ce=[...new Set([..._e.tags,...Ee.tags])];te(_e.id,Ce)}}L(!1)},[D,M,te]),he=g.useCallback(Ee=>{h(_e=>_e===Ee?null:Ee)},[]),xe=g.useMemo(()=>p?Y.find(Ee=>Ee.id===p)??null:null,[p,Y]),je=p?Y.findIndex(Ee=>Ee.id===p):-1,Pe=je>0?()=>h(Y[je-1].id):void 0,Ge=je>=0&&je<Y.length-1?()=>h(Y[je+1].id):void 0,Ze="auto minmax(15rem,1fr) 10rem 8rem 6rem 6rem";return i?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):o.jsxs("div",{className:"flex flex-1 min-h-0 overflow-hidden",children:[o.jsx(br,{open:C,onOpenChange:j,children:o.jsxs(xr,{children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Analyze Items"}),o.jsx(Qs,{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(Rt,{className:"text-xs mb-1 block",children:"Provider"}),o.jsx(Ly,{value:I,onValueChange:A})]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs mb-1 block",children:"Model"}),o.jsx(Fy,{llmId:I,value:P,onValueChange:F})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[y.size," item",y.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Rt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Kl,{value:E,onChange:Ee=>N(Ee.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-xs mt-1"})]})]}),o.jsxs(_c,{children:[o.jsx(de,{variant:"outline",onClick:()=>j(!1),children:"Cancel"}),o.jsxs(de,{onClick:se,disabled:!I||!P||k,children:[k?o.jsx(Gt,{className:"w-4 h-4 mr-1"}):null,"Analyze"]})]})]})}),o.jsx(br,{open:H,onOpenChange:L,children:o.jsxs(xr,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Review Proposed Tags"}),o.jsxs(Qs,{children:[D.filter(Ee=>Ee.accepted).length," of ",D.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:D.map((Ee,_e)=>{const Ce=M.find(Oe=>Oe.id===Ee.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!Ee.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(Mo,{checked:Ee.accepted,onCheckedChange:Oe=>V(Re=>Re.map((qe,Xe)=>Xe===_e?{...qe,accepted:!!Oe}:qe))}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate block",children:Ce?typeof Ce.input=="string"?Ce.input.slice(0,100):JSON.stringify(Ce.input).slice(0,100):Ee.itemId}),o.jsx("div",{className:"flex gap-1 flex-wrap mt-1.5",children:Ee.tags.map((Oe,Re)=>o.jsx(M9t,{tag:Oe,onRename:qe=>V(Xe=>Xe.map((tt,At)=>At===_e?{...tt,tags:tt.tags.map((ot,zt)=>zt===Re?qe:ot)}:tt)),onRemove:()=>V(qe=>qe.map((Xe,tt)=>tt===_e?{...Xe,tags:Xe.tags.filter((At,ot)=>ot!==Re)}:Xe))},`${Oe}-${Re}`))}),Ee.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:Ee.reason})]})]})},Ee.itemId)})}),o.jsxs(_c,{children:[o.jsx(de,{variant:"outline",onClick:()=>L(!1),children:"Cancel"}),o.jsxs(de,{onClick:re,disabled:D.filter(Ee=>Ee.accepted).length===0,children:["Accept ",D.filter(Ee=>Ee.accepted).length," proposals"]})]})]})}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",xe&&"grid-cols-[1fr_1fr]"),children:[o.jsxs("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:[o.jsxs("div",{className:"flex items-center justify-between w-full flex-wrap gap-4 gap-x-6",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsxs(de,{variant:"outline",size:"md",children:[o.jsx(Glt,{}),"Filter",X>0&&o.jsx("span",{className:K("ml-0.5 inline-flex items-center justify-center rounded-full bg-accent1/50 text-neutral5 text-ui-sm w-5 h-5"),children:X})]})}),o.jsxs(pt.Content,{align:"start",className:K("min-w-48"),children:[o.jsxs(pt.Sub,{children:[o.jsxs(pt.SubTrigger,{children:["Status",S&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(pt.SubContent,{children:[o.jsx(pt.CheckboxItem,{checked:!S,onCheckedChange:()=>{w(!1),h(null)},onSelect:Ee=>Ee.preventDefault(),children:"Review Queue"}),o.jsx(pt.CheckboxItem,{checked:S,onCheckedChange:()=>{w(!0),h(null)},onSelect:Ee=>Ee.preventDefault(),children:"Completed"})]})]}),o.jsxs(pt.Sub,{children:[o.jsxs(pt.SubTrigger,{children:["Tags",m&&o.jsx("span",{className:K("ml-auto text-ui-sm text-accent1"),children:"1"})]}),o.jsxs(pt.SubContent,{children:[o.jsx(pt.CheckboxItem,{checked:!m,onCheckedChange:()=>v(null),onSelect:Ee=>Ee.preventDefault(),children:"All"}),Z>0&&o.jsx(pt.CheckboxItem,{checked:m==="__untagged__",onCheckedChange:()=>v(m==="__untagged__"?null:"__untagged__"),onSelect:Ee=>Ee.preventDefault(),children:"Untagged"}),U.length>0&&o.jsx(pt.Separator,{}),U.map(([Ee])=>o.jsx(pt.CheckboxItem,{checked:m===Ee,onCheckedChange:()=>v(m===Ee?null:Ee),onSelect:_e=>_e.preventDefault(),children:Ee},Ee))]})]}),X>0&&o.jsxs(o.Fragment,{children:[o.jsx(pt.Separator,{}),o.jsxs(pt.Item,{onSelect:()=>{v(null),w(!1),h(null)},children:[o.jsx(vs,{}),"Clear all filters"]})]})]})]}),X>0&&o.jsxs(de,{variant:"outline",size:"md",onClick:()=>{v(null),w(!1),h(null)},children:[o.jsx(vs,{}),"Reset"]})]}),!S&&y.size>0&&o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx($9t,{selectedCount:y.size,vocabulary:G,onApplyTag:Ne,onRemoveTag:ke,onNewTag:Ee=>Ne(Ee)}),o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsxs(de,{disabled:k,children:[k?o.jsx(Gt,{className:"w-4 h-4"}):o.jsx(Ue,{size:"sm",children:o.jsx(Aa,{})}),"Actions"]})}),o.jsxs(pt.Content,{align:"end",children:[o.jsxs(pt.Item,{onSelect:Ie,children:[o.jsx(Ue,{size:"sm",children:o.jsx(cO,{})}),"Complete"]}),o.jsxs(pt.Item,{onSelect:ze,children:[o.jsx(Ue,{size:"sm",children:o.jsx(ou,{})}),"Remove"]}),o.jsx(pt.Separator,{}),o.jsxs(pt.Item,{onSelect:le,children:[o.jsx(Ue,{size:"sm",children:o.jsx(kg,{})}),"Analyze"]})]})]})]})]}),ne?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsx(Gt,{className:"w-6 h-6"})}):Y.length===0?o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center px-8",children:[o.jsx(ge,{variant:"ui-sm",className:"text-neutral3 block",children:S?"No completed reviews yet":"No items to review"}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-2 block",children:S?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})]})}):o.jsxs(me,{columns:Ze,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:!0,children:[S?o.jsx(me.TopCell,{children:" "}):o.jsx(me.TopSelectCell,{checked:oe?!0:ve?"indeterminate":!1,onToggle:()=>Se(),"aria-label":"Select all"}),o.jsxs(me.TopCells,{colStart:2,children:[o.jsx(me.TopCell,{children:"Input"}),o.jsx(me.TopCell,{children:"Comment"}),o.jsx(me.TopCell,{children:"Tags"}),o.jsx(me.TopCell,{children:"Rating"}),o.jsx(me.TopCell,{children:"Scores"})]})]}),Y.map(Ee=>{const _e=Ee.scores?Object.entries(Ee.scores):[],Ce=p===Ee.id,Oe=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",className:"min-w-0 text-neutral4",children:o.jsx("span",{className:"block truncate",children:Ats(Ee.input,200)})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ee.comment?o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 truncate",children:Ee.comment}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:Ee.tags.length>0?o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 truncate",children:Ee.tags.join(", ")}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})}),o.jsxs(me.Cell,{height:"compact",children:[Ee.rating==="positive"&&o.jsx(Ue,{size:"sm",className:"text-positive1",children:o.jsx(ybe,{})}),Ee.rating==="negative"&&o.jsx(Ue,{size:"sm",className:"text-negative1",children:o.jsx(vbe,{})}),!Ee.rating&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})]}),o.jsx(me.Cell,{height:"compact",children:_e.length>0?o.jsxs("div",{className:"flex items-center gap-1",children:[o.jsx(Ue,{size:"sm",className:"text-neutral3",children:o.jsx(rm,{})}),o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 font-mono",children:_e[0][1].toFixed(2)}),_e.length>1&&o.jsxs(dn,{variant:"default",children:["+",_e.length-1]})]}):o.jsx(ge,{variant:"ui-xs",className:"text-neutral2",children:"—"})})]});return o.jsxs(me.RowWrapper,{children:[S?o.jsx(me.Cell,{height:"compact",className:"justify-items-center px-4",children:o.jsx("div",{role:"img","aria-label":Ee.error?"Error":"Success",title:Ee.error?"Error":"Success",className:K("w-2 h-2 rounded-full",Ee.error?"bg-red-700":"bg-green-600")})}):o.jsx(me.SelectCell,{checked:y.has(Ee.id),onToggle:()=>ye(Ee.id),"aria-label":`Select item ${Ee.id}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:Ce,onClick:()=>he(Ee.id),children:Oe})]},Ee.id)})]})]}),xe&&o.jsx(P9t,{item:xe,isCompleted:S,tagVocabulary:G,onRate:Ee=>J(xe.id,Ee),onSetTags:Ee=>{te(xe.id,Ee);for(const _e of Ee)G.includes(_e)||q(_e)},onComment:Ee=>ee(xe.id,Ee),onRemove:()=>ae(xe.id),onComplete:S?void 0:()=>ce(xe.id),onPrevious:Pe,onNext:Ge,onClose:()=>h(null)})]})]})}function Rts({datasetId:e,onAddItemClick:t,onNavigateToDataset:n}){const{navigate:r}=yn(),[s,a]=ga(),{tab:i,activeVersion:l,handleTabChange:c}=OTe(s,a),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),[v,y]=g.useState([]),[b,S]=g.useState(!1),[w,k]=g.useState([]),[_,C]=g.useState(!1),[j,E]=g.useState([]),[N,I]=g.useState(0),[A,P]=g.useState(null),[F,D]=g.useState(""),[V]=D0e(F,300),{data:H}=Vx(e),{data:L=[],total:z,isLoading:B,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q}=C1(e,V||void 0,l),{total:$}=C1(e,void 0,l),[U,Z]=g.useState({}),{data:X,isLoading:te}=JM(e,void 0,U),{data:J}=JM(e),{deleteItems:ee}=Ei(),ae=X?.experiments??[],ce=J?.experiments??[],Y=Pes({hasSearchQuery:!!V,filteredItemsLength:L.length,unfilteredItemsTotal:$,itemsTotal:z}),{data:ne}=CTe(e),ue=ne?.length??0,pe=re=>{P(re)},oe=()=>{P(null)},ve=re=>{y(re),m(!0)},ye=re=>{k(re),S(!0)},Se=re=>{S(re),re||(k([]),I(he=>he+1))},Ne=re=>{r(`/datasets/${e}/items?items=${re.join(",")}`)},ke=re=>{r(`/datasets/${e}/versions?ids=${re.join(",")}`)},Ie=re=>{E(re),C(!0)},ze=async()=>{await ee.mutateAsync({datasetId:e,itemIds:j}),De.success(`Deleted ${j.length} items`),C(!1),E([]),I(re=>re+1)},le=re=>{m(!1),y([]),I(he=>he+1),n?.(re)},se=re=>{m(re),re||(y([]),I(he=>he+1))};return o.jsxs(o.Fragment,{children:[o.jsxs(Ic,{defaultTab:"items",value:i,onValueChange:c,className:"grid grid-rows-[auto_1fr] h-full",children:[o.jsxs(Nc,{children:[o.jsxs(Ar,{value:"items",children:["Items ",o.jsx(Xs,{color:"gray",children:Y})]}),o.jsxs(Ar,{value:"experiments",children:["Experiments",o.jsx(Xs,{color:"gray",children:ae.length})]}),o.jsxs(Ar,{value:"review",children:["Review",ue>0&&o.jsx(Xs,{color:"orange",children:ue})]})]}),o.jsx(Xr,{value:"items",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(Cts,{datasetId:e,items:L,isLoading:B,featuredItemId:A,onItemSelect:pe,onItemClose:oe,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>p(!0),onBulkDeleteClick:Ie,onCreateDatasetClick:ve,onAddToDatasetClick:ye,onCompareItemsClick:Ne,datasetName:H?.name,clearSelectionTrigger:N,setEndOfListElement:M,isFetchingNextPage:G,hasNextPage:q,searchQuery:F,activeSearchQuery:V,onSearchChange:D,currentDatasetVersion:H?.version,onCompareVersionsClick:ke})}),o.jsx(Xr,{value:"experiments",className:"grid overflow-auto mt-5 pb-0",children:o.jsx(Xes,{experiments:ae,allExperiments:ce,isLoading:te,datasetId:e,filters:U,onFiltersChange:Z})}),o.jsx(Xr,{value:"review",className:"overflow-auto mt-2 pb-0",children:o.jsx(aFt,{datasetId:e})})]}),o.jsx(qes,{datasetId:e,open:u,onOpenChange:d}),o.jsx(Nts,{datasetId:e,open:f,onOpenChange:p}),o.jsx(bes,{open:h,onOpenChange:se,items:v,onSuccess:le}),o.jsx(xes,{open:b,onOpenChange:Se,items:w,currentDatasetId:e}),o.jsx(Tt,{open:_,onOpenChange:C,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Items"}),o.jsxs(Tt.Description,{children:["Are you sure you want to delete ",j.length," item",j.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:ze,children:ee.isPending?"Deleting...":"Delete"})]})]})})]})}function Pts(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 sse({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-xs text-destructive",children:[o.jsxs("code",{className:"bg-destructive/10 px-1 rounded",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function $ts({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(""),[p,h]=g.useState(""),[m,v]=g.useState(null),{addItem:y}=Ei(),b=async C=>{C.preventDefault();let j;try{j=JSON.parse(s)}catch{De.error("Input must be valid JSON");return}let E;if(i.trim())try{E=JSON.parse(i)}catch{De.error("Ground Truth must be valid JSON");return}let N;if(c.trim())try{N=JSON.parse(c)}catch{De.error("Expected Trajectory must be valid JSON");return}let I;if(d.trim())try{const P=JSON.parse(d);if(!Array.isArray(P)){De.error("Tool Mocks must be a JSON array");return}I=P}catch{De.error("Tool Mocks must be valid JSON");return}let A;if(p.trim())try{A=JSON.parse(p)}catch{De.error("Request Context must be valid JSON");return}try{await y.mutateAsync({datasetId:e,input:j,groundTruth:E,expectedTrajectory:N,toolMocks:I,requestContext:A}),De.success("Item added successfully"),v(null),a("{}"),l(""),u(""),f(""),h(""),n(!1),r?.()}catch(P){const F=Pts(P);F?v(F):De.error(`Failed to add item: ${P instanceof Error?P.message:"Unknown error"}`)}},S=C=>{a(C),m?.field==="input"&&v(null)},w=C=>{l(C),m?.field==="groundTruth"&&v(null)},k=C=>{f(C),m?.field==="toolMocks"&&v(null)},_=()=>{a("{}"),l(""),u(""),f(""),h(""),v(null),n(!1)};return o.jsx(br,{open:t,onOpenChange:n,children:o.jsxs(xr,{className:"max-w-lg",children:[o.jsx(wr,{children:o.jsx(gr,{children:"Add Item"})}),o.jsx(Pr,{children:o.jsxs("form",{onSubmit:b,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Yr,{value:s,onChange:S,showCopyButton:!1,className:"min-h-[120px]"}),m?.field==="input"&&o.jsx(sse,{field:"input",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Yr,{value:i,onChange:w,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="groundTruth"&&o.jsx(sse,{field:"groundTruth",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Yr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Yr,{value:d,onChange:k,showCopyButton:!1,className:"min-h-[80px]"}),m?.field==="toolMocks"&&o.jsx(sse,{field:"toolMocks",errors:m.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Yr,{value:p,onChange:h,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(de,{type:"button",onClick:_,children:"Cancel"}),o.jsx(de,{type:"submit",variant:"primary",disabled:y.isPending,children:y.isPending?"Adding...":"Add Item"})]})]})})]})})}function Mts({item:e}){return o.jsx(ua,{withMargins:!1,children:o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(vN,{}),o.jsx("span",{className:"truncate",children:e.id}),o.jsx(ka,{content:e.id,tooltip:`Copy item ID: ${e.id}`})]}),o.jsxs(ua.Description,{children:[o.jsxs(Il,{children:[o.jsx(Flt,{})," Created ",er(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")]}),e.datasetVersion!=null&&o.jsxs(Il,{children:[o.jsx(d_,{})," Version v",e.datasetVersion]})]})]})})}function ETe({item:e}){const t=e?.input?JSON.stringify(e.input,null,2):"null",n=e?.groundTruth?JSON.stringify(e.groundTruth,null,2):"null",r=e?.metadata?JSON.stringify(e.metadata,null,2):"null",s=e?.expectedTrajectory?JSON.stringify(e.expectedTrajectory,null,2):null;return o.jsxs(Gje,{children:[o.jsx(Ps.CodeSection,{title:"Input",icon:o.jsx(uO,{}),codeStr:t}),o.jsx(Ps.CodeSection,{title:"Ground Truth",icon:o.jsx(yg,{}),codeStr:n}),s&&o.jsx(Ps.CodeSection,{title:"Expected Trajectory",icon:o.jsx(hbe,{}),codeStr:s}),o.jsx(Ps.CodeSection,{title:"Metadata",icon:o.jsx(xN,{}),codeStr:r})]})}function Dts({selectedScorers:e,setSelectedScorers:t,disabled:n=!1,container:r}){const{data:s,isLoading:a}=ih(),i=g.useMemo(()=>s?Object.entries(s).map(([l,c])=>({value:l,label:c.scorer?.config?.name||l,description:c.scorer?.config?.description||""})):[],[s]);return o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Scorers (Optional)"}),o.jsx(Jl,{multiple:!0,options:i,value:e,onValueChange:t,placeholder:"Select scorers...",searchPlaceholder:"Search scorers...",emptyText:"No scorers available",disabled:n||a,container:r})]})}const Lts=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function Fts({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=km(),{data:l,isLoading:c}=zy(),{data:u,isLoading:d}=ih(),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})):[],p=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,h=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:"Target Type"}),o.jsx(Jl,{options:Lts,value:e,onValueChange:h,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Rt,{children:m}),o.jsx(Jl,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:p,container:s})]})]})}function zts({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return cm(om(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(Rt,{children:"Request Context"}),o.jsx(s3,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-sm text-destructive",children:"Failed to parse request context schema"})}function Bts({datasetId:e,version:t,requestContextSchema:n,open:r,onOpenChange:s,onSuccess:a}){const i=g.useRef(null),[l,c]=g.useState(""),[u,d]=g.useState(""),[f,p]=g.useState([]),[h,m]=g.useState({}),[v,y]=g.useState(""),{triggerExperiment:b}=Ei(),S=!!(n&&Object.keys(n).length>0),w=l&&u,k=b.isPending,_=()=>{c(""),d(""),p([]),m({}),y("")},C=()=>{if(S){const N=Object.entries(h).filter(([,I])=>I!==void 0&&I!=="");return N.length>0?Object.fromEntries(N):void 0}if(v.trim()){let N;try{N=JSON.parse(v)}catch{throw new Error("Request Context must be valid JSON")}if(!N||typeof N!="object"||Array.isArray(N))throw new Error("Request Context must be a JSON object");return N}},j=async()=>{if(!w)return;let N;try{N=C()}catch(I){const A=I instanceof Error?I.message:"Request Context must be valid JSON";ru.error(A);return}try{const I=await b.mutateAsync({datasetId:e,targetType:l,targetId:u,scorerIds:f.length>0?f:void 0,version:t,requestContext:N});ru.success("Experiment triggered successfully"),s(!1),a?.(I.experimentId),_()}catch(I){const A=I instanceof Error?I.message:"Failed to trigger experiment";ru.error(A)}},E=()=>{k||(s(!1),_())};return o.jsx(br,{open:r,onOpenChange:E,children:o.jsxs(xr,{ref:i,children:[o.jsxs(wr,{children:[o.jsx(gr,{children:"Run Experiment"}),o.jsx(Qs,{children:t?`Execute items from ${er(new Date(t),"MMM d, yyyy")} version against a target.`:"Execute all items in this dataset against a target."})]}),o.jsxs(Pr,{className:"grid gap-6",children:[o.jsx(Fts,{targetType:l,setTargetType:c,targetId:u,setTargetId:d,container:i}),l&&l!=="scorer"&&o.jsx(Dts,{selectedScorers:f,setSelectedScorers:p,disabled:k,container:i}),S?o.jsx(zts,{requestContextSchema:n,onChange:m}):o.jsxs("div",{className:"space-y-2",children:[o.jsx(Rt,{children:"Request Context (JSON, optional)"}),o.jsx(Yr,{value:v,onChange:y,showCopyButton:!1,className:"min-h-[80px]"})]})]}),o.jsxs(_c,{className:"px-6 pt-4",children:[o.jsx(de,{onClick:E,disabled:k,children:"Cancel"}),o.jsx(de,{variant:"primary",onClick:j,disabled:!w||k,children:k?o.jsxs(o.Fragment,{children:[o.jsx(Gt,{className:"w-4 h-4"}),"Running..."]}):"Run"})]})]})})}const Uts=e=>{const t=We();return St({queryKey:["experiment-trace-light",e],queryFn:async()=>{if(!e)throw new Error("Trace ID is required");return t.getTraceLight(e)},enabled:!!e})},jTe=e=>o.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 9.45892 8.88606",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{d:"M8.53702 7.36403C8.98547 7.36403 9.34918 7.70502 9.34918 8.12535C9.34906 8.54559 8.9854 8.88606 8.53702 8.88606H5.6839C5.23552 8.88606 4.87186 8.54559 4.87174 8.12535C4.87174 7.70502 5.23545 7.36403 5.6839 7.36403H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.53702 3.67209C8.98547 3.67209 9.34918 4.01309 9.34918 4.43342C9.34911 4.8537 8.98543 5.19413 8.53702 5.19413H5.6839C5.23549 5.19413 4.87181 4.8537 4.87174 4.43342C4.87174 4.01309 5.23545 3.67209 5.6839 3.67209H8.53702Z",fill:"currentColor"}),o.jsx("path",{d:"M8.67155 0C9.10635 2.06584e-05 9.45892 0.341006 9.45892 0.761326C9.45878 1.18153 9.10627 1.52201 8.67155 1.52203H2.88163C2.4469 1.52203 2.0944 1.18154 2.09427 0.761326C2.09427 0.340993 2.44681 3.80132e-08 2.88163 0H8.67155Z",fill:"currentColor"}),o.jsx("path",{d:"M0.757606 0.760086V4.01122H3.50594V4.76883H0.759466L0.762566 5.4291C0.76837 6.70703 1.8058 7.73972 3.08374 7.73973H3.67953V8.49796H3.08374C1.38863 8.49795 0.0120204 7.1273 0.00433981 5.4322L0 4.39188V0.760086H0.757606Z",fill:"currentColor"})]});function ase(e){try{return JSON.stringify(e??{})}catch{return String(e)}}function qts({report:e}){const{served:t,unconsumed:n,liveCalls:r,failure:s}=e,a=[...t.map(i=>({outcome:"served",toolName:i.toolName,args:i.args})),...r.map(i=>({outcome:"live",toolName:i.toolName,args:i.args})),...n.map(i=>({outcome:"unconsumed",toolName:i.toolName,args:i.args}))];return o.jsxs("div",{className:"grid gap-2","data-testid":"tool-mock-report",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(Fp,{}),className:"mb-2",children:"Tool Mocks"}),s&&o.jsx(In,{variant:"destructive",title:"Mock mismatch",children:o.jsxs(In.Message,{children:[o.jsx("span",{className:"block",children:`Tool "${s.toolName}" was called with arguments that did not match an available mock (${s.code}).`}),o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Called with: ",ase(s.args)]}),n.length>0&&o.jsxs("span",{className:"mt-1 block font-mono text-xs",children:["Unconsumed mocks: ",n.map(i=>ase(i.args)).join(", ")]})]})}),o.jsx("div",{className:"rounded border border-border1 divide-y divide-border1 text-sm",children:a.map((i,l)=>o.jsxs("div",{className:"flex items-center justify-between gap-2 px-3 py-1.5",children:[o.jsxs("span",{className:"min-w-0 truncate",children:[o.jsx("span",{className:"font-mono text-neutral4",children:i.toolName}),o.jsx("span",{className:"ml-2 font-mono text-xs text-neutral3",children:ase(i.args)})]}),o.jsx("span",{className:`shrink-0 text-xs px-2 py-0.5 rounded ${Vts(i.outcome)}`,children:i.outcome})]},`${i.outcome}-${i.toolName}-${l}`))})]})}function Vts(e){switch(e){case"served":return"bg-accent1/10 text-accent1";case"live":return"bg-orange-500/10 text-orange-400";case"unconsumed":return"bg-neutral3/10 text-neutral4"}}function Hts({result:e,scores:t,onPrevious:n,onNext:r,onClose:s,onShowTrace:a,onOpenInReview:i,onScoreClick:l,featuredScoreId:c,onFlagForReview:u,collapsed:d,onCollapsedChange:f}){const[p,h]=g.useState(!1),m=d??p,v=f??h,y=!!e?.error,b=eF(e?.input),S=eF(e?.output),w=eF(e?.groundTruth),k=u&&e.status!=="needs-review"&&e.status!=="complete",_=Array.isArray(e.tags)?e.tags:[];return o.jsxs(bn,{collapsed:m,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Result ",o.jsxs("b",{children:["# ",e.id.length>12?`${e.id.slice(0,12)}…`:e.id]})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[f&&o.jsx(de,{size:"md",tooltip:m?"Expand panel":"Collapse panel",onClick:()=>v(!m),children:m?o.jsx(qlt,{}):o.jsx(Ult,{})}),o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:r,previousLabel:"Previous result",nextLabel:"Next result"}),o.jsxs(de,{size:"md",onClick:a,disabled:!e.traceId,children:[o.jsx(jTe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close result panel"})]})]}),!m&&o.jsxs(bn.Content,{children:[o.jsxs("div",{className:"grid gap-4 mb-6",children:[o.jsxs(Bt,{children:[o.jsx(Bt.Key,{children:"Item Id"}),o.jsx(Bt.ValueWithCopyBtn,{copyTooltip:"Copy Item Id to clipboard",copyValue:e.itemId,children:e.itemId}),o.jsx(Bt.Key,{children:"Created"}),o.jsx(Bt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")})]}),y&&o.jsx(In,{variant:"destructive",title:"Error",children:o.jsx(In.Message,{children:eF(e?.error&&typeof e.error=="object"?e.error.message:e?.error)})}),t&&t.length>0&&o.jsxs(me,{columns:"1fr 1fr",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Scorer"}),o.jsx(me.TopCell,{children:"Score"})]}),t.map(C=>o.jsxs(me.RowButton,{featured:c===C.id,onClick:()=>l?.(C.id),children:[o.jsx(me.Cell,{height:"compact",children:C.scorerId}),o.jsx(me.MonoCell,{children:C.score.toFixed(3)})]},C.id))]}),e.toolMockReport&&o.jsx(qts,{report:e.toolMockReport}),(e.status||_.length>0||k)&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(bn.SectionHeading,{icon:o.jsx(xN,{}),className:"mb-2",children:"Review"}),(e.status||_.length>0)&&o.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.status&&o.jsx("span",{className:`text-xs px-2 py-0.5 rounded-full font-medium ${e.status==="needs-review"?"bg-orange-500/10 text-orange-400":e.status==="complete"?"bg-accent1/10 text-accent1":"bg-neutral3/10 text-neutral4"}`,children:e.status}),_.map(C=>o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-surface4 text-neutral4",children:C},C))]}),k&&o.jsx("div",{children:o.jsxs(de,{size:"sm",onClick:()=>u(e.id),children:[o.jsx(cq,{}),"Flag for Review"]})}),e.status==="needs-review"&&i&&o.jsx("div",{children:o.jsxs(de,{size:"sm",onClick:i,children:[o.jsx(Oa,{}),"Review"]})})]})]}),o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:"Input",icon:o.jsx(vN,{}),codeStr:b}),o.jsx(bn.CodeSection,{title:"Output",icon:o.jsx(yg,{}),codeStr:S}),o.jsx(bn.CodeSection,{title:"Ground Truth",icon:o.jsx(gbe,{}),codeStr:w})]})]})]})}function eF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Wts({results:e,isLoading:t,featuredResultId:n,onResultClick:r,columns:s,scoresByItemId:a,scorerIds:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u,selectedIds:d,onToggleSelect:f}){const p=!!(d&&f),h=[p?"auto":"",...s.map(v=>v.size)].filter(Boolean).join(" "),m=s.some(v=>v.name==="input");return t?o.jsx(nl,{columns:h}):o.jsxs(me,{columns:h,className:"min-w-0",children:[o.jsxs(me.Top,{hasLeadingCell:p,children:[p&&o.jsx(me.TopCell,{children:" "}),p?o.jsx(me.TopCells,{colStart:2,children:s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))}):s.map(v=>o.jsx(me.TopCell,{children:v.label},v.name))]}),e.length===0?o.jsx(me.NoMatch,{message:"No results yet"}):o.jsxs(o.Fragment,{children:[e.map(v=>{const y=!!v.error,b=v.id===n,S=o.jsxs(o.Fragment,{children:[o.jsx(me.IdCell,{id:v.itemId}),o.jsx(me.Cell,{height:"compact",children:o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("div",{className:"flex items-center justify-center w-10 relative bg-transparent h-full",children:o.jsx("div",{role:"img","aria-label":y?"Error":"Success",className:K("w-2 h-2 rounded-full",y?"bg-red-700":"bg-green-600")})})}),o.jsx(Ln,{children:y?"Error":"Success"})]})}),m&&o.jsx(me.MonoCell,{children:Gts(Zts(v.input),200)}),i?.map(w=>{const _=a?.[v.itemId]?.find(C=>C.scorerId===w);return o.jsx(me.Cell,{height:"compact",className:"font-mono text-neutral3 text-ui-smd",children:_!=null?_.score.toFixed(3):"-"},w)})]});return p?o.jsxs(me.RowWrapper,{children:[o.jsx(me.SelectCell,{checked:d.has(v.id),onToggle:()=>f(v.id),"aria-label":`Select result ${v.itemId}`}),o.jsx(me.RowButton,{flushLeft:!0,colStart:2,featured:b,onClick:()=>r(v.id),children:S})]},v.id):o.jsx(me.RowButton,{featured:b,onClick:()=>r(v.id),children:S},v.id)}),o.jsx(me.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:l})]})]})}function Zts(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function Gts(e,t){return e.length<=t?e:e.slice(0,t-1)+"..."}function Qts(e){const t=e.scorer;return t?.hasJudge===!1?!0:t?.hasJudge===!0?!1:!e.preprocessPrompt&&!e.analyzePrompt&&!e.generateScorePrompt&&!e.generateReasonPrompt}function Yts({score:e,onNext:t,onPrevious:n,onClose:r,onShowTrace:s,collapsed:a,onCollapsedChange:i}){const[l,c]=g.useState(!1),u=a??l,d=i??c,f=Qts(e),p=f?"N/A — code-based scorer":"N/A — step not configured";return o.jsxs(bn,{collapsed:u,children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Score ",o.jsx("b",{children:e.scorerId})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[i&&o.jsx(de,{size:"md",tooltip:u?"Expand panel":"Collapse panel",onClick:()=>d(!u),children:u?o.jsx(qlt,{}):o.jsx(Ult,{})}),(n||t)&&o.jsx(bn.NextPrevNav,{onPrevious:n,onNext:t,previousLabel:"Previous score",nextLabel:"Next score"}),s&&o.jsxs(de,{size:"md",onClick:s,disabled:!e.traceId,children:[o.jsx(jTe,{}),"Trace"]}),o.jsx(bn.CloseButton,{onClick:r,tooltip:"Close score panel"})]})]}),!u&&o.jsx(bn.Content,{children:o.jsxs("div",{className:"grid gap-3",children:[o.jsx(bn.CodeSection,{title:`Score: ${e.score}`,icon:o.jsx(rm,{}),codeStr:e.reason||p,simplified:!0}),!f&&o.jsxs(o.Fragment,{children:[o.jsx(bn.CodeSection,{title:"Preprocess Prompt",icon:o.jsx(Oh,{}),codeStr:e.preprocessPrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Analyze Prompt",icon:o.jsx(Oh,{}),codeStr:e.analyzePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Score Prompt",icon:o.jsx(Oh,{}),codeStr:e.generateScorePrompt||p,simplified:!0}),o.jsx(bn.CodeSection,{title:"Generate Reason Prompt",icon:o.jsx(Oh,{}),codeStr:e.generateReasonPrompt||p,simplified:!0})]})]})})]})}const UQe=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"avg",label:"Avg Score",size:"1fr"},{name:"count",label:"Items Scored",size:"1fr"}];function Xts({scoresByItemId:e,experimentStatus:t}){const n=g.useMemo(()=>{if(!e)return[];const r={};for(const s of Object.values(e))for(const a of s)r[a.scorerId]||(r[a.scorerId]={sum:0,count:0}),r[a.scorerId].sum+=a.score,r[a.scorerId].count++;return Object.entries(r).map(([s,{sum:a,count:i}])=>({scorerId:s,avg:a/i,count:i})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))},[e]);if(n.length===0){const r=t==="running"||t==="pending",s=e!==void 0;let a,i;return r?(a="Experiment in progress",i="Summary metrics will appear here once the experiment completes."):s?(a="No scorers configured",i="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(a="Loading scores",i="Fetching scorer results…"),o.jsx("div",{className:"flex h-full items-center justify-center py-12",children:o.jsx(Cr,{iconSlot:o.jsx(rm,{className:"w-8 h-8 text-neutral3"}),titleSlot:a,descriptionSlot:i})})}return o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:UQe,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{children:"Avg Score"}),o.jsx(gn.HeaderCol,{children:"Items Scored"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:n.map(({scorerId:r,avg:s,count:a})=>o.jsxs(gn.Row,{columns:UQe,children:[o.jsx(gn.TextCell,{children:r}),o.jsx(gn.TextCell,{className:"font-mono",children:s.toFixed(3)}),o.jsx(gn.TextCell,{className:"font-mono",children:a})]},r))})})]})}function iFt({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoading:s,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l}){const[c,u]=g.useState(null),[d,f]=g.useState(null),[p,h]=g.useState(void 0),[m,v]=g.useState(null),[y,b]=g.useState(new Set),[S,w]=g.useState(!1),[k,_]=g.useState(!1),[C,j]=g.useState(!1),[E,N]=g.useState(!1),{updateExperimentResult:I}=Ei(),A=g.useCallback(se=>{b(re=>{const he=new Set(re);return he.has(se)?he.delete(se):he.add(se),he})},[]),P=g.useCallback(()=>b(new Set),[]),F=g.useCallback(()=>{const se=r.filter(re=>!!re.error).map(re=>re.id);b(new Set(se))},[r]),D=g.useCallback(async se=>{if(S||se.length===0)return;w(!0);let re=0;const he=new Set;try{for(const xe of se)try{await I.mutateAsync({datasetId:t,experimentId:e,resultId:xe,status:"needs-review"}),re++,he.add(xe)}catch{}}finally{w(!1)}he.size>0&&b(xe=>{const je=new Set(xe);for(const Pe of he)je.delete(Pe);return je}),re>0&&De(`${re} result${re>1?"s":""} flagged for review`)},[t,e,S,I]),V=r.find(se=>se.id===c)??null,[H,L]=g.useState("summary"),[z,B]=g.useState(null),M=se=>{L(se),se!=="reviews"&&B(null)},{data:G}=CTe(t),q=(G??[]).filter(se=>se.experimentId===e).length,{data:$}=N9t(e,n),U=g.useMemo(()=>{if(!$)return[];const se=new Set;for(const re of Object.values($))for(const he of re)se.add(he.scorerId);return[...se].sort()},[$]),Z=se=>{u(se),f(null),h(void 0),v(null)},X=se=>{Z(se===c?null:se)},te=()=>{Z(null)},J=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>=0&&se<r.length-1)return()=>Z(r[se+1].id)},ee=()=>{if(!V)return;const se=r.findIndex(re=>re.id===V.id);if(se>0)return()=>Z(r[se-1].id)},ae=V?$?.[V.itemId]:void 0,ce=ae?.find(se=>se.id===m)??null,Y=se=>{v(se===m?null:se),f(null),h(void 0)},ne=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>=0&&se<ae.length-1)return()=>v(ae[se+1].id)},ue=()=>{if(!m||!ae)return;const se=ae.findIndex(re=>re.id===m);if(se>0)return()=>v(ae[se-1].id)},{data:pe,isLoading:oe}=Uts(d),ve=pe?.spans,{data:ye,isLoading:Se}=HN(d,p),Ne=ye?.span,{handlePreviousSpan:ke,handleNextSpan:Ie}=aH(ve,p??null,h),ze=(()=>{const se=[],re=!!ce,he=!!d;return se.push(k?"auto":re||he?"2fr":"1fr"),re&&se.push(E?"auto":"3fr"),he&&se.push(C?"auto":"3fr"),he&&p&&se.push("3fr"),se.join(" ")})(),le=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"7rem"},{name:"status",label:"Status",size:"5rem"},{name:"input",label:"Input",size:"minmax(15rem,1fr)"},...U.map(se=>({name:se,label:se,size:"12rem"}))],[U]);return o.jsxs(Ic,{defaultTab:"summary",value:H,onValueChange:M,className:"grid grid-rows-[auto_1fr] h-full overflow-hidden",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"summary",children:"Summary"}),o.jsx(Ar,{value:"results",children:"Results"}),o.jsxs(Ar,{value:"reviews",children:["Reviews",q>0&&o.jsx(Xs,{color:"orange",children:q})]})]}),o.jsx(Xr,{value:"summary",className:"overflow-y-auto mt-5",children:o.jsx(Xts,{scoresByItemId:$,experimentStatus:n})}),o.jsx(Xr,{value:"reviews",className:"overflow-auto mt-2 pb-0",children:o.jsx(aFt,{datasetId:t,experimentId:e,featuredItemId:z})}),o.jsxs(Xr,{value:"results",className:"grid grid-rows-[auto_1fr] overflow-hidden mt-2",children:[o.jsxs("div",{className:"mb-4",children:[y.size>0&&o.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-surface3",children:[o.jsxs(ge,{variant:"ui-xs",className:"text-neutral5 font-medium",children:[y.size," selected"]}),o.jsx("div",{className:"flex-1"}),o.jsxs(de,{variant:"outline",size:"sm",disabled:S,onClick:()=>D([...y]),children:[o.jsx(Ue,{size:"sm",children:o.jsx(cq,{})}),"Flag for Review"]}),o.jsx(de,{variant:"ghost",size:"sm",onClick:P,children:"Clear"})]}),r.length>0&&y.size===0&&!s&&o.jsx("div",{className:"flex items-center gap-2 px-4 py-2",children:o.jsx(de,{variant:"ghost",size:"sm",onClick:F,children:"Select loaded failures"})})]}),o.jsxs("div",{className:K("grid w-full h-full grid-cols-1 gap-4 overflow-y-auto",V&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"flex overflow-y-auto w-full",children:o.jsx("div",{className:"grid gap-8 content-start w-full overflow-y-auto",children:o.jsx(Wts,{results:r,isLoading:s,featuredResultId:c,onResultClick:X,columns:le,scoresByItemId:$,scorerIds:U,setEndOfListElement:a,isFetchingNextPage:i,hasNextPage:l,selectedIds:y,onToggleSelect:A})})}),V&&o.jsxs("div",{className:"grid gap-4 max-h-full min-h-0 overflow-auto content-start",style:{gridTemplateRows:ze},children:[o.jsx(Hts,{result:V,scores:ae,onPrevious:ee(),onNext:J(),onClose:te,onScoreClick:Y,featuredScoreId:m,onShowTrace:()=>{V.traceId&&(f(V.traceId),h(void 0),v(null),_(!0),j(!1))},onOpenInReview:()=>{B(V.id),L("reviews")},onFlagForReview:se=>D([se]),collapsed:k,onCollapsedChange:_}),ce&&o.jsx(Yts,{score:ce,onNext:ne(),onPrevious:ue(),onClose:()=>v(null),onShowTrace:()=>{ce.traceId&&(f(ce.traceId),h(void 0),_(!0),N(!0),j(!1))},collapsed:E,onCollapsedChange:N}),d&&o.jsxs(o.Fragment,{children:[o.jsx(gTe,{traceId:d,spans:ve,isLoading:oe,onClose:()=>{f(null),h(void 0),_(!1),N(!1)},onSpanSelect:h,initialSpanId:p??null,placement:"traces-list",showUnavailableFeaturesMsg:!1,collapsed:C,onCollapsedChange:j,LinkComponent:FD,traceHref:`/traces/${d}`}),p&&o.jsx(rH,{traceId:d,spanId:p,span:Ne,isLoading:Se,onPrevious:ke,onNext:Ie,onClose:()=>h(void 0)})]})]})]})]})]})}const Kts={pending:o.jsx(Gj,{}),running:o.jsx(ife,{}),completed:o.jsx(ea,{}),failed:o.jsx(vs,{})};function Jts({experiment:e,className:t}){const n=e.status,r=e.totalItems-e.succeededCount-e.failedCount;return o.jsxs("div",{className:K("grid justify-items-end gap-3",t),children:[o.jsxs("div",{className:"flex p-1 px-3 text-ui-lg capitalize text-neutral4 gap-2 items-center bg-surface5 rounded-lg ",children:[o.jsx("span",{className:K("w-5 h-5 flex items-center justify-center rounded-full text-black","[&>svg]:w-4 [&>svg]:h-4",{"bg-green-700":n==="completed","bg-red-700":n==="failed","bg-cyan-600":n==="running","bg-yellow-600":n==="pending"}),children:Kts[n]}),e.status]}),o.jsxs("div",{className:K("flex items-center gap-3 text-neutral3 text-ui-md ","[&>span]:flex [&>span]:gap-1 [&>span]:items-center ","[&_b]:text-neutral4 [&_b]:font-semibold"),children:[o.jsxs("span",{children:["Total: ",o.jsx("b",{children:e.totalItems})]}),o.jsxs("span",{children:["Succeeded: ",o.jsx("b",{children:e.succeededCount})]}),o.jsxs("span",{children:["Failed: ",o.jsx("b",{children:e.failedCount})]}),(n==="pending"||n==="running")&&o.jsxs("span",{children:["Pending: ",o.jsx("b",{children:r})]})]})]})}function ens({onPrevious:e,onNext:t,previousAriaLabel:n="Previous",nextAriaLabel:r="Next"}){return o.jsxs(Dr,{spacing:"close",children:[o.jsxs(de,{onClick:e,disabled:!e,"aria-label":n,children:[o.jsx(Zq,{})," Prev"]}),o.jsxs(de,{onClick:t,disabled:!t,"aria-label":r,children:["Next",o.jsx(zD,{})]})]})}function TTe({delta:e}){const t=e>0?o.jsx(Xs,{size:"small",color:"green",intensity:"muted",children:o.jsx(dD,{})}):e<0?o.jsx(Xs,{size:"small",color:"red",intensity:"muted",children:o.jsx(Jln,{})}):null;return o.jsxs("span",{className:K("font-mono text-sm text-neutral4 min-w-20"),children:[o.jsx("span",{className:"w-3 inline-block",children:e>0?"+ ":e<0?"- ":""}),Math.abs(e).toFixed(2)," ",t]})}function tF(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function tns({item:e,baselineId:t,contenderId:n,baselineVersion:r,contenderVersion:s,onPrevious:a,onNext:i,onClose:l}){const c=e.results[t],u=e.results[n],d=!!(c&&u),f=new Set;if(c)for(const h of Object.keys(c.scores))f.add(h);if(u)for(const h of Object.keys(u.scores))f.add(h);const p=[...f].sort();return o.jsxs(Qr,{withLeftSeparator:!0,children:[o.jsxs(Qr.Toolbar,{children:[o.jsx(ens,{onPrevious:a,onNext:i,previousAriaLabel:"Previous comparison item",nextAriaLabel:"Next comparison item"}),o.jsx(Dr,{children:o.jsx(de,{onClick:l,"aria-label":"Close comparison detail panel",children:o.jsx(vs,{})})})]}),o.jsxs(Qr.Content,{className:"pb-6",children:[o.jsx(ua,{withMargins:!1,children:o.jsx(ua.Column,{children:o.jsxs(ua.Title,{size:"smaller",children:[o.jsx(vN,{})," ",e.itemId]})})}),d?o.jsx(o.Fragment,{children:o.jsxs(Gje,{children:[p.length>0&&o.jsxs("div",{className:"grid gap-3",children:[o.jsx("h4",{className:"text-sm font-medium text-neutral5",children:"Scores"}),o.jsx("div",{className:"grid gap-2",children:p.map(h=>{const m=c?.scores[h]??null,v=u?.scores[h]??null,y=m!=null&&v!=null?v-m:null;return o.jsxs("div",{className:"flex items-center justify-between gap-4 px-3 py-2 rounded-lg bg-surface2",children:[o.jsx("span",{className:"text-sm text-neutral5 font-medium",children:h}),o.jsxs("div",{className:"flex items-center gap-4",children:[o.jsxs("span",{className:"text-sm text-neutral3",children:[m!=null?m.toFixed(3):"-"," →"," ",v!=null?v.toFixed(3):"-"]}),y!=null&&o.jsx(TTe,{delta:y})]})]},h)})})]}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"purple",children:"Baseline "})," Experiment Output"]}),icon:o.jsx(yg,{}),codeStr:tF(c?.output)}),o.jsx(Ps.CodeSection,{title:o.jsxs(o.Fragment,{children:[o.jsx(Xs,{color:"cyan",children:"Contender "})," Experiment Output"]}),icon:o.jsx(yg,{}),codeStr:tF(u?.output)}),o.jsx(Ps.CodeSection,{title:"Item Input",icon:o.jsx(uO,{}),codeStr:tF(e.input)}),o.jsx(Ps.CodeSection,{title:"Item Ground Truth",icon:o.jsx(gbe,{}),codeStr:tF(e.groundTruth)})]})}):o.jsx(In,{variant:"warning",title:"Comparison not available",children:o.jsx(In.Message,{children:(()=>{const h=c?"Contender":"Baseline",m=c?s:r;return o.jsxs(o.Fragment,{children:["The ",h," experiment was run against dataset",m!=null?` v. ${m}`:"",", which does not contain this item."]})})()})})]})]})}function nns({items:e,baselineId:t,contenderId:n,scorerIds:r,featuredItemId:s,columns:a,onItemClick:i}){return o.jsx(Qr,{children:o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:a,children:[o.jsx(gn.HeaderCol,{children:"Item ID"}),!s&&r.map(l=>o.jsx(gn.HeaderCol,{className:"flex justify-center",children:l},l))]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:e.map(l=>{const c=l.results[t],u=l.results[n],d=!!(c&&u);return o.jsx(gn.Row,{children:o.jsxs(gn.RowButton,{item:{id:l.itemId},columns:a,isFeatured:s===l.itemId,onClick:i,children:[o.jsx(gn.IdCell,{id:l.itemId,className:d?"":"text-neutral1"}),!s&&o.jsx(o.Fragment,{children:r.map(f=>{const p=c?.scores[f]??null,h=u?.scores[f]??null,m=p!=null&&h!=null?h-p:null;return o.jsx(gn.Cell,{className:"flex items-center gap-5 justify-center font-mono",children:m!=null?o.jsxs(o.Fragment,{children:[o.jsxs("span",{className:"flex items-center text-neutral2 min-w-24",children:[p?.toFixed(2)," → ",h?.toFixed(2)]}),o.jsx(TTe,{delta:m})]}):o.jsx("span",{className:"text-neutral1",children:"-"})},f)})})]})},l.itemId)})})})]})})}const rns={baseline:{label:"Baseline",color:"purple",customStyle:"items-end justify-items-end [&>div]:justify-end border-r-0 rounded-r-none"},contender:{label:"Contender",color:"cyan",customStyle:"items-start justify-items-start [&>div]:justify-start border-l-0 rounded-l-none"}};function qQe({datasetId:e,experiment:t,type:n}){const{Link:r}=yn(),{label:s,color:a,customStyle:i}=rns[n];if(!t)return null;const l=t.createdAt?new Date(t.createdAt):null;return o.jsxs("div",{className:`grid border-2 border-border1 rounded-lg p-5 gap-3 ${i}`,children:[o.jsxs("div",{className:"flex items-center gap-3 w-full overflow-clip",children:[n==="contender"&&o.jsxs(Xs,{size:"small",color:a,children:[s,o.jsx(gm,{})]}),o.jsx(de,{as:r,href:`/datasets/${e}/experiments/${t.id}`,children:o.jsx("span",{className:"truncate min-w-0",children:t.id})}),n==="baseline"&&o.jsxs(Xs,{size:"small",color:a,children:[o.jsx(Tc,{})," ",s]})]}),o.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-ui-sm text-neutral3",children:[o.jsxs(Il,{children:[o.jsx(gbe,{})," ",t.targetType," / ",t.targetId]}),o.jsxs(Il,{children:[o.jsx(fq,{})," v",t.datasetVersion??"—"]}),l&&o.jsxs(Il,{children:[o.jsx(zlt,{})," ",er(l,"MMM d, yyyy HH:mm")]})]})]})}function sns({datasetId:e,experimentIdA:t,experimentIdB:n,onSwap:r}){const[s,a]=g.useState(null),{data:i,isLoading:l,error:c}=WJr(e,t,n),{data:u}=zU(e,t),{data:d}=zU(e,n),f=u&&d&&u.datasetVersion!==d.datasetVersion,p=g.useMemo(()=>{if(!i)return[];const j=new Set;for(const E of i.items)for(const N of Object.values(E.results))if(N)for(const I of Object.keys(N.scores))j.add(I);return[...j].sort()},[i]),h=g.useMemo(()=>{if(!i||p.length===0)return[];const j=i.baselineId,E=t===j?n:t;return p.map(N=>{let I=0,A=0,P=0,F=0;for(const L of i.items){const z=L.results[j]?.scores[N],B=L.results[E]?.scores[N];z!=null&&(I+=z,P++),B!=null&&(A+=B,F++)}const D=P>0?I/P:null,V=F>0?A/F:null,H=D!=null&&V!=null?V-D:null;return{scorerId:N,avgA:D,avgB:V,delta:H}})},[i,p,t,n]),m=[{name:"scorer",label:"Scorer",size:"1fr"},{name:"baselineAvg",label:"Baseline Avg",size:"1fr"},{name:"comparisonAvg",label:"Comparison Avg",size:"1fr"},{name:"delta",label:"Delta",size:"1fr"}],v=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"8rem"},...s?[]:p.map(j=>({name:j,label:j,size:"1fr"}))],[p,s]),y=i?.items.find(j=>j.itemId===s)??null,b=j=>{a(j===s?null:j)},S=()=>{a(null)},w=()=>{if(!i||!s)return;const j=i.items.findIndex(E=>E.itemId===s);if(j>=0&&j<i.items.length-1)return()=>a(i.items[j+1].itemId)},k=()=>{if(!i||!s)return;const j=i.items.findIndex(E=>E.itemId===s);if(j>0)return()=>a(i.items[j-1].itemId)};if(l)return o.jsx("div",{className:"flex items-center justify-center h-64",children:o.jsx(Gt,{})});if(c)return o.jsx(In,{variant:"warning",title:"Error loading comparison",children:o.jsx(In.Message,{children:c instanceof Error?c.message:"Unknown error"})});if(!i||i.items.length===0)return o.jsx("div",{className:"text-neutral4 text-sm text-center py-8",children:"No comparison data"});const _=i.baselineId,C=t===_?n:t;return o.jsxs("div",{className:"grid gap-10",children:[u&&d&&o.jsxs("div",{className:K("relative grid xl:grid-cols-[1fr_auto_1fr] gap-4 xl:gap-0"),children:[o.jsx(qQe,{datasetId:e,experiment:u,type:"baseline"}),o.jsx("div",{className:"relative flex items-center justify-center px-[2vw] before:absolute before:inset-y-0 before:left-1/2 before:-translate-x-1/2 before:w-[2px] before:bg-border1",children:o.jsx("div",{className:"relative z-1 bg-surface2 rounded-lg p-2",children:o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(de,{onClick:r,children:"VS"})}),o.jsx(Ln,{children:"Switch the order"})]})})}),o.jsx(qQe,{datasetId:e,experiment:d,type:"contender"})]}),f&&o.jsx(In,{variant:"warning",title:"Version mismatch",children:o.jsxs(In.Message,{children:["These experiments used different dataset versions (v",u.datasetVersion," vs v",d.datasetVersion,"). Results may not be directly comparable."]})}),h.length>0&&o.jsxs(gn,{children:[o.jsxs(gn.Header,{columns:m,children:[o.jsx(gn.HeaderCol,{children:"Scorer"}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(qGe,{children:[o.jsx(Xs,{color:"purple",size:"small",intensity:"muted",children:"Baseline"}),o.jsx(Xs,{color:"purple",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:o.jsxs(qGe,{children:[o.jsx(Xs,{color:"cyan",size:"small",intensity:"muted",children:"Contender"}),o.jsx(Xs,{color:"cyan",size:"small",children:"Avg"})]})}),o.jsx(gn.HeaderCol,{className:"flex justify-center",children:"Delta"})]}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:h.map(({scorerId:j,avgA:E,avgB:N,delta:I})=>o.jsxs(gn.Row,{columns:m,children:[o.jsx(gn.TextCell,{children:j}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:E!=null?E.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"text-center font-mono",children:N!=null?N.toFixed(3):"-"}),o.jsx(gn.TextCell,{className:"flex justify-center",children:I!=null?o.jsx(TTe,{delta:I}):"-"})]},j))})})]}),o.jsxs(ay,{className:K({"grid-cols-[1fr_2fr]":!!y}),children:[o.jsx(nns,{items:i.items,baselineId:_,contenderId:C,scorerIds:p,featuredItemId:s,columns:v,onItemClick:b}),!!y&&o.jsx(tns,{item:y,baselineId:_,contenderId:C,baselineVersion:u?.datasetVersion,contenderVersion:d?.datasetVersion,onPrevious:k(),onNext:w(),onClose:S})]})]})}function ans({datasetId:e,itemId:t,onVersionSelect:n,onCompareVersionsClick:r,activeVersion:s}){const{data:a,isLoading:i}=kTe(e,t),[l,c]=g.useState(!1),[u,d]=g.useState(new Set),f=b=>{n?.(b)},p=b=>s==null?b.isLatest:b.datasetVersion===s,h=b=>{d(S=>{const w=new Set(S);if(w.has(b))w.delete(b);else if(w.size>=2){const[k]=Array.from(w);return new Set([k,b])}else w.add(b);return w})},m=()=>{c(!1),d(new Set)},v=()=>{c(!0)},y=()=>{u.size===2&&r?.([...u])};return o.jsxs(Qr,{className:"min-w-56",children:[l?o.jsx(Qr.Toolbar,{className:"grid justify-stretch gap-3 w-full",children:o.jsxs(Dr,{children:[o.jsx(de,{onClick:m,children:"Cancel"}),o.jsx(de,{variant:"primary",disabled:u.size!==2,onClick:y,tooltip:u.size!==2?"Check 2 versions to compare":void 0,className:"grow",children:"Compare"})]})}):o.jsx(o.Fragment,{children:(a||[]).length>1&&o.jsx(Qr.Toolbar,{children:o.jsxs(de,{onClick:v,className:"w-full",children:[o.jsx(Yw,{})," Compare Ver."]})})}),i?o.jsx(ins,{}):o.jsxs(gn,{children:[o.jsx(gn.Header,{children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:a?.map(b=>{const S=String(b.datasetVersion),w=typeof b.updatedAt=="string"?new Date(b.updatedAt):b.updatedAt;return o.jsxs(gn.Row,{isSelected:l&&u.has(S),children:[l&&o.jsx(gn.LabelCell,{children:o.jsx(Mo,{checked:u.has(S),disabled:b.isDeleted,onCheckedChange:()=>{},onClick:k=>{k.stopPropagation(),b.isDeleted||h(S)},"aria-label":`Select version ${b.datasetVersion}`})}),o.jsx(gn.RowButton,{item:b,columns:[{name:"version",label:"Item Version History",size:"1fr"}],isFeatured:p(b),onClick:()=>f(b),className:"py-2",children:o.jsx(gn.VersionCell,{version:b.datasetVersion,date:w,isLatest:b.isLatest,isDeleted:b.isDeleted})})]},String(b.datasetVersion))})})})]})]})}function ins(){return o.jsxs(gn,{children:[o.jsx(gn.Header,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.HeaderCol,{children:"Item Version History"})}),o.jsx(gn.Items,{children:Array.from({length:3}).map((e,t)=>o.jsx(gn.Row,{children:o.jsx(gn.RowButton,{columns:[{name:"version",label:"Item Version History",size:"1fr"}],children:o.jsx(gn.TextCell,{isLoading:!0,children:"Loading..."})})},t))})]})}function ons(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${er(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function lns({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=lTe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${ons(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(Qr.Toolbar,{className:"grid grid-cols-[1fr_1fr_1fr_10rem] gap-4 w-full",children:[o.jsx("div",{}),o.jsx(wc,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(wc,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}const cns=[{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"}],uns={added:{color:"blue",borderColor:"border-blue-900",icon:o.jsx(Hr,{}),tooltip:"Added in this version"},changed:{color:"orange",borderColor:"border-yellow-900",icon:o.jsx(act,{}),tooltip:"Changed in this version"},same:{color:"green",borderColor:"border-green-900",icon:o.jsx(Sun,{}),tooltip:"Same in both versions"}};function ise({red:e=!1,tooltip:t}){return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx(ccn,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),t&&o.jsx(Ln,{children:t})]})}function GS({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{color:n,icon:r,tooltip:s}=uns[e];return o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"pr-3 text-ui-md text-neutral4 min-w-16 flex justify-end",children:["v. ",t]}),o.jsx(Xs,{color:n,size:"small",children:r})]})}),o.jsx(Ln,{children:s})]})}function dns(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function fns({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=yn(),l=t>n;return o.jsx(gn,{children:o.jsx(gn.Scroller,{children:o.jsx(gn.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=dns(u,d);return o.jsxs(gn.Row,{columns:cns,children:[o.jsx(gn.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!d&&l?o.jsx(GS,{variant:"added",version:u.datasetVersion}):f==="changed"&&l?o.jsx(GS,{variant:"changed",version:u.datasetVersion}):o.jsx(GS,{version:u.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ise,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",children:!u&&!l?o.jsx(GS,{variant:"added",version:d.datasetVersion}):f==="changed"&&!l?o.jsx(GS,{variant:"changed",version:d.datasetVersion}):o.jsx(GS,{version:d.datasetVersion})}):o.jsx(gn.Cell,{className:"justify-center flex items-center",children:o.jsx(ise,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",children:o.jsx(GS,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(gn.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?ids=${u?.datasetVersion},${d?.datasetVersion}`,children:"Compare"}):o.jsx(gn.Cell,{children:o.jsx(ise,{tooltip:o.jsxs(o.Fragment,{children:["Comparing is available",o.jsx("br",{})," only for changed items"]})})})]},c)})})})})}const VQe={needsReview:"#facc15",complete:"#22c55e"},pns=[{label:"Needs Review",color:VQe.needsReview},{label:"Reviewed",color:VQe.complete}];function hns({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,p=0;const h=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;p+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,S=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);h.push({name:S,values:[m.needsReview,m.complete]})}return{data:h,maxVal:f,totalInPipeline:p}},[e,t,n]),c=a.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Ut.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Ut.Loading,{}):s?o.jsx(Ut.Error,{message:"Failed to load review data"}):o.jsx(Ut.Content,{children:c?o.jsx(cN,{data:a,segments:pns,maxVal:i,fmt:u=>String(u)}):o.jsx(Ut.NoData,{message:"No items have been sent to review yet"})})]})}function NTe(){const e=We();return St({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function oFt(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 mns(e,t){const n=new Map,r=oFt(e);if(!r.size||!t)return n;for(const s of t){const a=r.get(s.id);if(!a||!s.datasetId||a.needsReview+a.complete===0)continue;const l=n.get(s.datasetId)??{needsReview:0,complete:0};l.needsReview+=a.needsReview,l.complete+=a.complete,n.set(s.datasetId,l)}return n}function gns(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}}const vns=10;function yns(){const[e,t]=g.useState(!1),[n,r]=g.useState(""),[s,a]=g.useState("all"),[i,l]=g.useState("all"),[c,u]=g.useState("all"),[d,f]=g.useState(0),{data:p,isLoading:h,error:m}=Dg({page:d,perPage:vns}),{data:v,isLoading:y,error:b}=tG(),{data:S}=NTe(),w=g.useMemo(()=>p?.datasets??[],[p?.datasets]),k=p?.pagination?.hasMore??!1,_=g.useMemo(()=>v?.experiments??[],[v?.experiments]),C=g.useMemo(()=>ues(w),[w]),j=g.useMemo(()=>mns(S,_),[S,_]),E=h||y,N=m||b,I=()=>t(!0),A=g.useCallback(()=>f(B=>B+1),[]),P=g.useCallback(()=>f(B=>Math.max(0,B-1)),[]),F=g.useCallback(B=>{r(B),f(0)},[]),D=g.useCallback(B=>{a(B),f(0)},[]),V=g.useCallback(B=>{l(B),f(0)},[]),H=g.useCallback(B=>{u(B),f(0)},[]);if(N&&gs(N))return o.jsx(lr,{children:o.jsx(Vs,{})});if(N&&ys(N))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(N)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load datasets",message:N.message})});if(w.length===0&&!E&&d===0)return o.jsxs(o.Fragment,{children:[o.jsx(lr,{children:o.jsx(mes,{onCreateClick:I})}),o.jsx(Vve,{open:e,onOpenChange:t})]});const L=s!=="all"||i!=="all"||c!=="all"||n!=="",z=()=>{r(""),a("all"),l("all"),u("all"),f(0)};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(yes,{search:n,onSearchChange:F,targetFilter:s,onTargetFilterChange:D,experimentFilter:i,onExperimentFilterChange:V,tagFilter:c,onTagFilterChange:H,tagOptions:C,onReset:z,hasActiveFilters:L,onCreateClick:I})}),o.jsx(hes,{datasets:w,experiments:_,reviewByDataset:j,isLoading:E,search:n,targetFilter:s,experimentFilter:i,tagFilter:c,currentPage:d,hasMore:k,onNextPage:A,onPrevPage:P}),o.jsx(Vve,{open:e,onOpenChange:t})]})}function nF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function bns(){const{datasetId:e}=ur(),t=bs(),[n,r]=ga(),{activeVersion:s}=OTe(n,r),[a,i]=g.useState(!1),[l,c]=g.useState(!1),[u,d]=g.useState(!1),[f,p]=g.useState(!1),[h,m]=g.useState(!1),{data:v,error:y,isLoading:b}=Vx(e),{data:S=[],isLoading:w}=C1(e,void 0,s),k=!w&&S.length===0;if(b)return null;if(y&&gs(y))return o.jsx(nF,{children:o.jsx(Vs,{})});if(y&&ys(y))return o.jsx(nF,{children:o.jsx(Ds,{resource:"datasets"})});if(y&&$Se(y)||!b&&!y&&!v)return o.jsx(nF,{children:o.jsx(Cr,{iconSlot:o.jsx(oy,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(de,{as:Ma,to:"/datasets",children:[o.jsx(Tc,{}),"Back to Datasets"]})})});if(y)return o.jsx(nF,{children:o.jsx(zi,{title:"Failed to load dataset",message:y instanceof Error?y.message:"An unexpected error occurred. Please try again."})});const _=j=>{t(`/datasets/${e}/experiments/${j}`)},C=()=>{t("/datasets")};return o.jsxs(o.Fragment,{children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsxs(Lt.Column,{children:[v?.description&&o.jsx("p",{className:"text-ui-smd text-neutral3 mb-1",children:v.description}),o.jsxs(Bt,{numOfCol:2,children:[o.jsx(Bt.Key,{children:"Created at"}),o.jsx(Bt.Value,{children:v?.createdAt?er(new Date(v.createdAt),"MMM d, yyyy"):""}),o.jsx(Bt.Key,{children:"Latest version"}),o.jsxs(Bt.Value,{children:["v",v?.version??""]})]})]}),o.jsx(Lt.Column,{children:o.jsxs(Dr,{children:[k?o.jsxs(Un,{children:[o.jsx(Dn,{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(de,{variant:"primary",children:[o.jsx(Lp,{}),s!=null?`Run on v${s}`:"Run Experiment"]})})})}),o.jsx(Ln,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(de,{variant:"primary",onClick:()=>i(!0),children:[o.jsx(Lp,{}),s!=null?`Run on v${s}`:"Run Experiment"]}),o.jsxs(pt,{children:[o.jsx(pt.Trigger,{asChild:!0,children:o.jsx(de,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(pD,{})})}),o.jsxs(pt.Content,{align:"end",className:"w-48",children:[o.jsxs(pt.Item,{onSelect:()=>d(!0),children:[o.jsx(sm,{})," Edit Dataset"]}),o.jsxs(pt.Item,{onSelect:()=>m(!0),children:[o.jsx(Dp,{})," Duplicate Dataset"]}),o.jsxs(pt.Item,{onSelect:()=>p(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ou,{})," Delete Dataset"]})]})]})]})})]})}),o.jsx(Lt.MainArea,{children:o.jsx(Rts,{datasetId:e,onAddItemClick:()=>c(!0)})})]}),o.jsx(Bts,{datasetId:e,version:s??void 0,requestContextSchema:v?.requestContextSchema,open:a,onOpenChange:i,onSuccess:_}),o.jsx($ts,{datasetId:e,open:l,onOpenChange:c}),v&&o.jsx(Oes,{open:u,onOpenChange:d,dataset:{id:v.id,name:v.name,description:v?.description||"",targetType:v.targetType,inputSchema:v.inputSchema,groundTruthSchema:v.groundTruthSchema,requestContextSchema:v.requestContextSchema}}),v&&o.jsx(wes,{open:h,onOpenChange:m,sourceDatasetId:v.id,sourceDatasetName:v.name,sourceDatasetDescription:v.description,sourceDatasetTargetType:v.targetType}),v&&o.jsx(Ces,{open:f,onOpenChange:p,datasetId:v.id,datasetName:v.name,onSuccess:C})]})}function lFt({experiment:e}){const{Link:t,paths:n}=yn(),{data:r}=km(),{data:s}=zy(),{data:a}=ih(),i=()=>{switch(e.targetType){case"agent":return n.agentLink(e.targetId);case"workflow":return n.workflowLink(e.targetId);case"scorer":return n.scorerLink(e.targetId);default:return"#"}},l=()=>{const u=e.targetId;if(!u)return u;switch(e.targetType){case"agent":return r?.[u]?.name??u;case"workflow":return s?.[u]?.name??u;case"scorer":return a?.[u]?.scorer?.config?.name??u;default:return u}},c=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${n.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{children:[o.jsx(Lt.Column,{children:o.jsxs(Bt,{numOfCol:2,children:[o.jsx(Bt.Key,{children:"Created at"}),o.jsx(Bt.Value,{children:er(new Date(e.createdAt),"MMM d, yyyy 'at' h:mm a")}),e.completedAt&&o.jsxs(o.Fragment,{children:[o.jsx(Bt.Key,{children:"Completed at"}),o.jsx(Bt.Value,{children:er(new Date(e.completedAt),"MMM d, yyyy 'at' h:mm a")})]}),o.jsx(Bt.Key,{children:"Target"}),o.jsx(Bt.ValueLink,{href:i(),as:t,children:l()}),e.agentVersion&&o.jsxs(o.Fragment,{children:[o.jsx(Bt.Key,{children:"Version"}),c?o.jsx(Bt.ValueLink,{href:c,as:t,children:e.agentVersion}):o.jsx(Bt.Value,{children:e.agentVersion})]})]})}),o.jsx(Lt.Column,{children:o.jsx(Jts,{experiment:e})})]})})}function rF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function xns(){const{datasetId:e,experimentId:t}=ur(),{data:n,isLoading:r,error:s}=zU(e,t),{data:a,isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u}=KZ({datasetId:e,experimentId:t,experimentStatus:n?.status});return!e||!t||r?null:s&&gs(s)?o.jsx(rF,{children:o.jsx(Vs,{})}):s&&ys(s)?o.jsx(rF,{children:o.jsx(Ds,{resource:"datasets"})}):s&&$Se(s)||!r&&!s&&!n?o.jsx(rF,{children:o.jsx(Cr,{iconSlot:o.jsx(obe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${t}".`,actionSlot:o.jsxs(de,{as:Ma,to:`/datasets/${e}?tab=experiments`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})}):s?o.jsx(rF,{children:o.jsx(zi,{title:"Failed to load experiment",message:s instanceof Error?s.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(lFt,{experiment:n}),o.jsx(Lt.MainArea,{children:o.jsx(iFt,{experimentId:t,datasetId:e,experimentStatus:n.status,results:a??[],isLoading:i,setEndOfListElement:l,isFetchingNextPage:c,hasNextPage:u})})]})}function wns(){const{datasetId:e}=ur(),[t,n]=ga(),{error:r}=Vx(e??""),s=t.get("baseline")??"",a=t.get("contender")??"";return r&&gs(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):r&&ys(r)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!s||!a?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsxs("div",{className:"text-neutral4 text-center py-8",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-sm mt-2",children:["Use the URL format: /datasets/","{datasetId}","/experiments?baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):o.jsx(cs,{children:o.jsx(Sy,{children:o.jsxs("div",{className:"max-w-[100rem] w-full px-12 mx-auto grid content-start ",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{})," Dataset Experiments Comparison"]}),o.jsxs(ua.Description,{children:["Comparing"," ",o.jsx(Ma,{to:`/datasets/${e}/experiments/${s}`,children:s.slice(0,8)})," vs"," ",o.jsx(Ma,{to:`/datasets/${e}/experiments/${a}`,children:a.slice(0,8)})]})]}),o.jsx(ua.Column,{children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})]}),o.jsx(sns,{datasetId:e,experimentIdA:s,experimentIdB:a,onSwap:()=>{n({baseline:a,contender:s})}})]})})})}function Sns(){const{datasetId:e,itemId:t}=ur(),{Link:n}=yn(),r=bs(),{data:s,isLoading:a,error:i}=kTe(e??"",t??""),{updateItem:l,deleteItem:c}=Ei(),{data:u}=Vx(e??""),d=s?.[0]??null,f=d?.isDeleted??!1,[p,h]=g.useState(null),m=g.useMemo(()=>!d||f?{input:"",groundTruth:"",metadata:"",trajectory:"",toolMocks:"",requestContext:""}:{input:JSON.stringify(d.input,null,2),groundTruth:d.groundTruth?JSON.stringify(d.groundTruth,null,2):"",metadata:d.metadata?JSON.stringify(d.metadata,null,2):"",trajectory:d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):"",toolMocks:d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):"",requestContext:d.requestContext?JSON.stringify(d.requestContext,null,2):""},[d,f]),v=d?.datasetVersion??0,[y,b]=g.useState(!1),[S,w]=g.useState(m.input),[k,_]=g.useState(m.groundTruth),[C,j]=g.useState(m.metadata),[E,N]=g.useState(m.trajectory),[I,A]=g.useState(m.toolMocks),[P,F]=g.useState(m.requestContext),[D,V]=g.useState(v);v!==D&&(V(v),w(m.input),_(m.groundTruth),j(m.metadata),N(m.trajectory),A(m.toolMocks),F(m.requestContext));const[H,L]=g.useState(!1),z=J=>{h(f?J:J.isLatest?null:J)},B=()=>{h(null)},M=!f&&p!=null,G=()=>{M||b(!0)},q=()=>{M||L(!0)},$=async()=>{if(!e||!t)return;let J;try{J=JSON.parse(S)}catch{De.error("Input must be valid JSON");return}let ee;if(k.trim())try{ee=JSON.parse(k)}catch{De.error("Ground Truth must be valid JSON");return}let ae;if(C.trim())try{ae=JSON.parse(C)}catch{De.error("Metadata must be valid JSON");return}let ce;const Y=E!==m.trajectory;if(Y&&E.trim())try{ce=JSON.parse(E)}catch{De.error("Expected Trajectory must be valid JSON");return}let ne;const ue=I!==m.toolMocks;if(ue&&I.trim())try{const ve=JSON.parse(I);if(!Array.isArray(ve)){De.error("Tool Mocks must be a JSON array");return}ne=ve}catch{De.error("Tool Mocks must be valid JSON");return}let pe;const oe=P!==m.requestContext;if(oe&&P.trim())try{pe=JSON.parse(P)}catch{De.error("Request Context must be valid JSON");return}try{await l.mutateAsync({datasetId:e,itemId:t,input:J,groundTruth:ee,metadata:ae,...Y?{expectedTrajectory:ce??null}:{},...ue?{toolMocks:ne??[]}:{},...oe?{requestContext:pe}:{}}),De.success("Item updated successfully"),b(!1)}catch(ve){De.error(`Failed to update item: ${ve instanceof Error?ve.message:"Unknown error"}`)}},U=()=>{d&&(w(JSON.stringify(d.input,null,2)),_(d.groundTruth?JSON.stringify(d.groundTruth,null,2):""),j(d.metadata?JSON.stringify(d.metadata,null,2):""),N(d.expectedTrajectory!=null?JSON.stringify(d.expectedTrajectory,null,2):""),A(d.toolMocks?.length?JSON.stringify(d.toolMocks,null,2):""),F(d.requestContext?JSON.stringify(d.requestContext,null,2):"")),b(!1)},Z=async()=>{if(!(!e||!t))try{await c.mutateAsync({datasetId:e,itemId:t}),De.success("Item deleted successfully"),L(!1),r(`/datasets/${e}`)}catch(J){De.error(`Failed to delete item: ${J instanceof Error?J.message:"Unknown error"}`)}},X=p??d,te=X?{id:t??"",datasetId:e??"",datasetVersion:X.datasetVersion,input:X.input,groundTruth:X.groundTruth,expectedTrajectory:X.expectedTrajectory,metadata:X.metadata,createdAt:X.createdAt,updatedAt:X.updatedAt}:null;return i&&gs(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):i&&ys(i)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):a?null:!e||!t||!s||s.length===0?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral3 p-4",children:"Item not found"})})}):o.jsxs(o.Fragment,{children:[o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-6 pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[60rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(vN,{}),t," ",o.jsx(ka,{content:t})]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Item of ",o.jsx(oy,{})," ",u?.name]})}),o.jsxs(ua.Description,{children:[o.jsxs(Il,{children:[o.jsx(Flt,{})," Created at"," ",d?.createdAt?er(new Date(d.createdAt),"MMM d, yyyy"):""]}),o.jsxs(Il,{children:[o.jsx(d_,{})," Latest version v",d?.datasetVersion??""]})]})]}),o.jsx(ua.Column,{children:!y&&!f&&o.jsxs(Dr,{children:[o.jsxs(de,{onClick:G,disabled:M,title:M?"Return to latest version to edit":void 0,children:[o.jsx(act,{})," Edit"]}),o.jsxs(de,{onClick:q,disabled:M,title:M?"Return to latest version to delete":void 0,children:[o.jsx(ou,{})," Delete"]})]})})]}),o.jsxs(ay,{className:y?"grid-cols-1":"grid-cols-[1fr_auto]",children:[o.jsxs(Qr,{withRightSeparator:!y,children:[f&&d&&o.jsx(In,{variant:"destructive",title:"Item deleted",children:o.jsxs(In.Message,{children:["This item was deleted at version v",d.datasetVersion]})}),!f&&M&&p&&o.jsx(In,{variant:"warning",title:"Previous version",action:o.jsxs(In.Button,{onClick:B,children:[o.jsx(Plt,{})," Return to the latest version"]}),children:o.jsxs(In.Message,{children:["Viewing version v",p.datasetVersion]})}),y?o.jsx(rFt,{inputValue:S,setInputValue:w,groundTruthValue:k,setGroundTruthValue:_,metadataValue:C,setMetadataValue:j,trajectoryValue:E,setTrajectoryValue:N,toolMocksValue:I,setToolMocksValue:A,requestContextValue:P,setRequestContextValue:F,validationErrors:null,onSave:$,onCancel:U,isSaving:l.isPending}):te?o.jsx(ETe,{item:te,Link:n}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})]}),!y&&o.jsx(Qr,{children:o.jsx(ans,{datasetId:e,itemId:t,onClose:()=>{},onVersionSelect:z,onCompareVersionsClick:J=>{r(`/datasets/${e}/items/${t}/versions?ids=${J.join(",")}`)},activeVersion:p?.datasetVersion??null})})]})]})})}),o.jsx(Tt,{open:H,onOpenChange:L,children:o.jsxs(Tt.Content,{children:[o.jsxs(Tt.Header,{children:[o.jsx(Tt.Title,{children:"Delete Item"}),o.jsx(Tt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Tt.Footer,{children:[o.jsx(Tt.Cancel,{children:"Cancel"}),o.jsx(Tt.Action,{onClick:Z,children:c.isPending?"Deleting...":"Delete"})]})]})})]})}function HQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function kns(){const{datasetId:e}=ur(),[t,n]=ga(),r=t.get("items")?.split(",").filter(Boolean)??[],{data:s,error:a}=Vx(e??""),{Link:i}=yn(),[l,c]=g.useState(!1),{data:u}=BU(e??"",r[0]??""),{data:d}=BU(e??"",r[1]??"");return a&&gs(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):a&&ys(a)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||r.length<2?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two items to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Iy,{owner:"dataset-items-compare",children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,variant:"outline",children:[o.jsx(Tc,{}),"Back to Dataset"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":l}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{}),"Compare Dataset Items"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Comparing ",r.length," items of"," ",o.jsx(Ma,{to:`/datasets/${e}`,className:"text-info1 hover:underline",children:s?.name||e?.slice(0,8)})]})})]}),o.jsx(ua.Column,{children:o.jsx(Dr,{children:o.jsx(de,{variant:"primary",onClick:()=>c(f=>!f),children:l?o.jsxs(o.Fragment,{children:[o.jsx(Wlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(hun,{})," Diff View"]})})})})]}),o.jsx(ay,{className:"grid-cols-[1fr_3vw_1fr]",children:r.map((f,p)=>o.jsxs(g.Fragment,{children:[o.jsx(Ons,{datasetId:e,itemId:f,Link:i,idx:p,itemIds:r,showContent:!l,onItemChange:h=>{const m=[...r];m[p]=h,n({items:m.join(",")})}}),p==0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},f))}),l&&u&&d&&o.jsx(z_e,{codeA:HQe(u),codeB:HQe(d)})]})})]})}function Ons({datasetId:e,itemId:t,Link:n,idx:r,itemIds:s,onItemChange:a,showContent:i=!0}){const{data:l,isLoading:c}=BU(e,t),{data:u}=C1(e),d=new Set(s.filter((p,h)=>h!==r)),f=(u??[]).map(p=>({value:p.id,label:p.id,disabled:d.has(p.id)}));return o.jsxs(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"flex gap-4",children:[o.jsxs(da,{name:`compare-item-${r}`,value:t,onValueChange:a,children:[o.jsx(pa,{"aria-label":"Item",children:o.jsx(fa,{placeholder:"Select item"})}),o.jsx(ha,{children:f.map(p=>o.jsx(Fr,{value:p.value,disabled:p.disabled,children:p.label},p.value))})]}),o.jsxs(de,{as:n,to:`/datasets/${e}/items/${t}`,children:[o.jsx(d_,{}),"Versions"]})]}),i&&o.jsx(Qr.Content,{children:c?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):l?o.jsxs(o.Fragment,{children:[o.jsx(Mts,{item:l}),o.jsx(ETe,{item:l,Link:n})]}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Item ",t.slice(0,8)," not found"]})})]})}function WQe(e){return JSON.stringify({input:e.input??null,groundTruth:e.groundTruth??null,metadata:e.metadata??null},null,2)}function _ns(){const{datasetId:e,itemId:t}=ur(),[n,r]=ga(),[s,a]=g.useState(!1),i=n.get("ids")?.split(",").map(Number).filter(h=>!isNaN(h)&&h>0)??[],{data:l,error:c}=Vx(e??""),{Link:u}=yn(),{data:d}=kTe(e??"",t??""),{data:f}=Wve(e??"",t??"",i[0]??0,l?.version),{data:p}=Wve(e??"",t??"",i[1]??0,l?.version);return c&&gs(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})}):c&&ys(c)?o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})}):!e||!t||i.length<2?o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})}):o.jsxs(cs,{children:[o.jsx(Iy,{owner:"dataset-item-versions-compare",children:o.jsxs(de,{as:Ma,to:`/datasets/${e}/items/${t}`,variant:"outline",children:[o.jsx(Tc,{}),"Back to Item"]})}),o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:K("grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",{"grid-rows-[auto_auto_1fr]":s}),children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Yw,{}),"Compare Dataset Item Versions"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:["Comparing ",i.length," versions of"," ",o.jsx(Ma,{to:`/datasets/${e}/items/${t}`,className:"text-info1 hover:underline",children:t})]})})]}),o.jsx(ua.Column,{children:o.jsx(Dr,{children:o.jsx(de,{variant:"primary",onClick:()=>a(h=>!h),children:s?o.jsxs(o.Fragment,{children:[o.jsx(Wlt,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(Jun,{})," Diff View"]})})})})]}),o.jsx(ay,{className:"grid-cols-[1fr_3vw_1fr]",children:i.map((h,m)=>o.jsxs(g.Fragment,{children:[o.jsx(Cns,{datasetId:e,itemId:t,datasetVersion:h,latestVersion:l?.version,allVersions:d??[],versionNumbers:i,Link:u,idx:m,showContent:!s,onVersionChange:v=>{const y=[...i];y[m]=v,r({ids:y.join(",")})}}),m===0&&o.jsx("div",{className:K("bg-surface5 w-[3px] shrink-0 mx-[1.5vw]")})]},h))}),s&&f&&p&&o.jsx(z_e,{codeA:WQe(f),codeB:WQe(p)})]})})]})}function Cns({datasetId:e,itemId:t,datasetVersion:n,latestVersion:r,allVersions:s,versionNumbers:a,Link:i,idx:l,showContent:c=!0,onVersionChange:u}){const{data:d,isLoading:f}=Wve(e,t,n,r),p=new Set(a.filter((v,y)=>y!==l)),h=s.map(v=>{const y=typeof v.updatedAt=="string"?new Date(v.updatedAt):v.updatedAt;return{value:String(v.datasetVersion),label:o.jsxs(o.Fragment,{children:[o.jsxs("b",{children:["v. ",v.datasetVersion]})," - ",er(y,"MMM d, yyyy h:mm a"),v.isLatest?o.jsx(Xs,{color:"blue",size:"small",children:"Latest"}):null]}),disabled:p.has(v.datasetVersion)}}),m=d?{id:d.id,datasetId:e,datasetVersion:d.datasetVersion,input:d.input,groundTruth:d.groundTruth,metadata:d.metadata,createdAt:d.createdAt,updatedAt:d.updatedAt}:null;return o.jsxs(Qr,{children:[o.jsxs(Qr.Toolbar,{className:"grid gap-4 grid-cols-[auto_1fr]",children:[o.jsx(d_,{className:"w-6 h-6 opacity-50"}),o.jsxs(da,{name:`compare-version-${l}`,value:String(n),onValueChange:v=>u(Number(v)),children:[o.jsx(pa,{"aria-label":"Version",className:"w-full",children:o.jsx(fa,{placeholder:"Select version"})}),o.jsx(ha,{children:h.map(v=>o.jsx(Fr,{value:v.value,disabled:v.disabled,children:v.label},v.value))})]})]}),c&&o.jsx(Qr.Content,{children:f?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):!d||!m?o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",n," not found"]}):o.jsx(ETe,{item:m,Link:i})})]})}function Ens(){const{datasetId:e}=ur(),[t]=ga(),n=t.get("ids")?.split(",").map(Number).filter(v=>!isNaN(v)&&v>0)??[],r=bs(),{data:s,error:a}=Vx(e??""),i=C1(e??"",void 0,n[0]??null),l=C1(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const v=new Map;for(const y of[...c,...u])v.has(y.id)||v.set(y.id,{id:y.id,createdAt:new Date(y.createdAt)});return[...v.values()].sort((y,b)=>b.createdAt.getTime()-y.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(v=>[v.id,v])),[c]),p=g.useMemo(()=>new Map(u.map(v=>[v.id,v])),[u]);if(a&&gs(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})})});if(a&&ys(a))return o.jsx(cs,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(cs,{children:o.jsx(Sy,{children:o.jsx("div",{className:"text-neutral4 text-center py-8",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const h=(v,y,b)=>{r(`/datasets/${e}/items/${v}/versions?ids=${y?.datasetVersion??""},${b?.datasetVersion??""}`)},m=(v,y)=>{r(`/datasets/${e}/versions?ids=${v},${y}`,{replace:!0})};return o.jsx(cs,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"grid gap-6 max-w-[140rem] mx-auto grid-rows-[auto_1fr] h-full",children:[o.jsxs(ua,{children:[o.jsxs(ua.Column,{children:[o.jsxs(ua.Title,{children:[o.jsx(Ffn,{})," Compare Dataset Versions"]}),o.jsx(ua.Description,{children:o.jsxs(Il,{children:[o.jsx(d_,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(ua.Column,{children:o.jsxs(de,{as:Ma,to:`/datasets/${e}`,children:[o.jsx(Tc,{}),"Back to Dataset"]})})]}),o.jsx(ay,{children:o.jsxs(Qr,{children:[o.jsx(lns,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:m}),o.jsx(fns,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:p,onItemClick:h})]})})]})})})}function Gve({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function jns(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 Tns({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,p=t?.length,h=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=jns(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,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(p)}),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,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(h)}),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,{})]})]})}const ZQe="auto 1fr auto auto auto auto auto auto auto";function Nns(e){return e?(typeof e=="string"?new Date(e):e).toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}const Ins={completed:"success",running:"warning",failed:"error",pending:"neutral"};function Ans({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all"}){const{paths:l,Link:c}=yn(),u=g.useMemo(()=>{const p=new Map;return t?.forEach(h=>p.set(h.id,h.name)),p},[t]),d=g.useMemo(()=>[...e].sort((p,h)=>{const m=p.createdAt?new Date(p.createdAt).getTime():0;return(h.createdAt?new Date(h.createdAt).getTime():0)-m}),[e]),f=g.useMemo(()=>{const p=s.toLowerCase();return d.filter(h=>{const m=h.datasetId?u.get(h.datasetId)??"":"",v=!p||h.id.toLowerCase().includes(p)||m.toLowerCase().includes(p)||(h.targetId??"").toLowerCase().includes(p),y=a==="all"||h.status===a,b=i==="all"||h.datasetId===i;return v&&y&&b})},[d,s,u,a,i]);return r?o.jsx(nl,{columns:ZQe}):o.jsxs(me,{columns:ZQe,variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Experiment"}),o.jsx(me.TopCell,{children:"Dataset"}),o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{className:"text-center",children:"Items"}),o.jsx(me.TopCell,{className:"text-center",children:"Succeeded"}),o.jsx(me.TopCell,{className:"text-center",children:"Failed"}),o.jsx(me.TopCell,{className:"text-center",children:"Review"}),o.jsx(me.TopCell,{children:"Date"})]}),f.map(p=>{const h=p.datasetId?u.get(p.datasetId)??p.datasetId.slice(0,8):"—",m=p.status??"pending",v=p.succeededCount??0,y=p.failedCount??0,b=p.totalItems??0,S=b>0?Math.round(v/b*100):0;return o.jsxs(me.RowLink,{to:l.experimentLink(p.id),LinkComponent:c,children:[o.jsx(me.NameCell,{className:"font-mono",children:p.id.slice(0,8)}),o.jsx(me.TextCell,{children:h}),o.jsx(me.Cell,{children:o.jsxs("span",{className:"truncate",children:[p.targetType," ",p.targetId]})}),o.jsx(me.Cell,{children:o.jsx(hg,{variant:Ins[m]??"neutral",withDot:!0,children:m})}),o.jsx(me.TextCell,{className:"text-center",children:b}),o.jsx(me.TextCell,{className:"text-center",children:o.jsxs("span",{className:v>0?"text-accent1":"",children:[v," (",S,"%)"]})}),o.jsx(me.TextCell,{className:"text-center",children:o.jsx("span",{className:y>0?"text-accent2":"",children:y})}),o.jsx(me.Cell,{className:"text-center",children:(()=>{const w=n?.get(p.id);if(!w)return o.jsx("span",{className:"text-neutral2",children:"—"});const k=w.needsReview+w.complete;return k===0?o.jsx("span",{className:"text-neutral2",children:"—"}):w.needsReview>0?o.jsxs(Xs,{size:"small",color:"yellow",children:[w.needsReview," pending"]}):o.jsxs(Xs,{size:"small",color:"green",children:[w.complete,"/",k," reviewed"]})})()}),o.jsx(me.TextCell,{children:Nns(p.createdAt)})]},p.id)})]})}const Rns=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function Pns(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const sF={completed:"#22c55e",running:"#facc15",pending:"#fb923c",failed:"#f87171"},$ns=[{label:"Completed",color:sF.completed},{label:"Running",color:sF.running},{label:"Pending",color:sF.pending},{label:"Failed",color:sF.failed}];function Mns({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 p=f.datasetId??"unknown";c.has(p)||c.set(p,{completed:0,running:0,pending:0,failed:0});const h=c.get(p),m=f.status;m in h&&h[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,p])=>{const h=p.completed+p.running+p.pending+p.failed;return h>u&&(u=h),{name:l.get(f)??f.slice(0,12),values:[p.completed,p.running,p.pending,p.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Ut.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Ut.Loading,{}):r?o.jsx(Ut.Error,{message:"Failed to load experiments data"}):o.jsx(Ut.Content,{children:i?o.jsx(cN,{data:s,segments:$ns,maxVal:a,fmt:l=>String(l)}):o.jsx(Ut.NoData,{message:"No experiments have been run yet"})})]})}const Dns=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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.jsx("div",{className:"flex flex-col items-center gap-2",children:o.jsxs(de,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/evals/datasets/running-experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Oa,{})]})})})});function Lns({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c}){return o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsx(jf,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t}),o.jsxs(Dr,{children:[o.jsx(wc,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...Rns],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(wc,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(de,{onClick:l,size:"sm",variant:"default",children:[o.jsx(vs,{className:"size-3"})," Reset"]})]})]})}function Fns(){const{data:e,isLoading:t,error:n}=ih(),{data:r,isLoading:s,error:a}=Dg(),{data:i,isLoading:l,error:c}=tG(),{data:u,isLoading:d,isError:f,error:p}=UZr(),{data:h,isLoading:m,isError:v,error:y}=NTe(),b=r?.datasets,S=i?.experiments,w=g.useMemo(()=>gns(h),[h]),k=n||a||c||p||y;return k&&gs(k)?o.jsx(lr,{children:o.jsx(Vs,{})}):k&&ys(k)?o.jsx(lr,{children:o.jsx(Ds,{resource:"evaluation"})}):k?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load evaluation data",message:k.message})}):o.jsx(Lt,{width:"wide",height:"full",children:o.jsxs("div",{className:"flex flex-col gap-6",children:[o.jsx(Gve,{children:o.jsx(Tns,{scorers:e,datasets:b,experiments:S,avgScore:u?.avgScore??null,prevAvgScore:u?.prevAvgScore??null,totalNeedsReview:w.needsReview,isLoadingScorers:t,isLoadingDatasets:s,isLoadingExperiments:l,isLoadingScores:d,isLoadingReview:m})}),o.jsx(eZr,{summaryData:u?.summaryData??[],overTimeData:u?.overTimeData??[],scorerNames:u?.scorerNames??[],avgScore:u?.avgScore??null,isLoading:d,isError:f}),o.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[o.jsx(ves,{experiments:S,isLoading:l,isError:!!c}),o.jsx(Mns,{experiments:S,datasets:b,isLoading:l,isError:!!c})]}),o.jsx(hns,{reviewSummary:h,experiments:S,datasets:b,isLoading:m,isError:!!v})]})})}function zns(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState("all"),{data:i,isLoading:l,error:c}=Dg(),{data:u,isLoading:d,error:f}=tG(),{data:p}=NTe(),h=g.useMemo(()=>i?.datasets??[],[i?.datasets]),m=g.useMemo(()=>u?.experiments??[],[u?.experiments]),v=g.useMemo(()=>Pns(h),[h]),y=g.useMemo(()=>oFt(p),[p]),b=l||d,S=f||c;if(S&&gs(S))return o.jsx(lr,{children:o.jsx(Vs,{})});if(f&&ys(f))return o.jsx(lr,{children:o.jsx(Ds,{resource:"experiments"})});if(c&&ys(c))return o.jsx(lr,{children:o.jsx(Ds,{resource:"datasets"})});if(S)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load experiments",message:S.message})});if(m.length===0&&!b)return o.jsx(lr,{children:o.jsx(Dns,{})});const w=n!=="all"||s!=="all"||e!=="",k=()=>{t(""),r("all"),a("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lns,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:v,onReset:k,hasActiveFilters:w})}),o.jsx(Ans,{experiments:m,datasets:h,reviewByExperiment:y,isLoading:b,search:e,statusFilter:n,datasetFilter:s})]})}function aF({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Bns(){const{experimentId:e}=ur(),{data:t,isLoading:n}=tG(),s=t?.experiments?.find(h=>h.id===e)?.datasetId??"",{data:a,isLoading:i,error:l}=zU(s,e??""),{data:c,isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p}=KZ({datasetId:s,experimentId:e??"",experimentStatus:a?.status});return!e||n||i?null:l&&gs(l)?o.jsx(aF,{children:o.jsx(Vs,{})}):l&&ys(l)?o.jsx(aF,{children:o.jsx(Ds,{resource:"datasets"})}):l&&$Se(l)||!n&&!s||!i&&!l&&!a?o.jsx(aF,{children:o.jsx(Cr,{iconSlot:o.jsx(obe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(de,{as:Ma,to:"/experiments",children:[o.jsx(Tc,{}),"Back to Experiments"]})})}):l?o.jsx(aF,{children:o.jsx(zi,{title:"Failed to load experiment",message:l instanceof Error?l.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx(lFt,{experiment:a}),o.jsx(Lt.MainArea,{children:o.jsx(iFt,{experimentId:e,datasetId:s,experimentStatus:a.status,results:c??[],isLoading:u,setEndOfListElement:d,isFetchingNextPage:f,hasNextPage:p})})]})}function Uns({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 cFt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(Uns,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function qns({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(cFt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Vns({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(qns,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(cFt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Hns({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:p,onToolkitChange:h,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=>p(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=>h(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 GQe=e=>e.authorId?.trim()||"shared",Wns=(e,t)=>{if(!t||new Set(e.map(GQe)).size<=1)return null;const r=new Map;for(const a of e){const i=GQe(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},Zns=["*","tool-providers:*","tool-providers:admin"];function Gns(){const{data:e}=Sm();return e?.permissions?.some(t=>Zns.includes(t))??!1}function Qns(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=QN(),l=xH(e||null),c=qCt(e||null,n||null),u=UCt(),d=FCt(),f=Gns(),p=i.data?.providers??[],h=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Wns(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()}})},S=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(Hns,{providers:p,toolkits:h,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(Vns,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:S})]})}function Yns({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"flex min-h-screen items-center justify-center bg-surface1",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(Qh,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-xl font-semibold text-neutral6",children:e})]}),t,n,r]})})}function uFt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=ac(),{mutate:i,isPending:l,error:c}=jsr(),{mutate:u,isPending:d,error:f}=Nsr(),{mutate:p,isPending:h}=f_t(),[m,v]=g.useState(n),[y,b]=g.useState(""),[S,w]=g.useState(""),[k,_]=g.useState("");if(a)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"flex min-h-screen items-center justify-center bg-surface1",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:C}=s,j=C.type==="sso"||C.type==="both",E=C.type==="credentials"||C.type==="both",N=C.sso,I=C.signUpEnabled!==!1,A=m==="signin"||!I,P=A?l:d,F=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href="/"},V=M=>{M.preventDefault(),A?i({email:S,password:k},{onSuccess:D}):u({email:S,password:k,name:y||void 0},{onSuccess:D})},H=()=>{p({redirectUri:e},{onSuccess:M=>{window.location.href=M.url}})},L=()=>{v(A?"signup":"signin")},z=C.description?o.jsxs("div",{className:"flex items-start gap-2.5 rounded-md border border-border1 bg-surface1 p-3",children:[o.jsx(yf,{className:"mt-0.5 h-4 w-4 shrink-0 text-neutral4"}),o.jsx("p",{className:"text-sm text-neutral3",children:C.description})]}):null,B=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(Yns,{title:A?"Sign in to Mastra Studio":"Create your account",description:z,errorBanner:B,children:[E&&o.jsxs("form",{onSubmit:V,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"block text-sm text-neutral4",children:"Name"}),o.jsx(kn,{id:"name",type:"text",value:y,onChange:M=>b(M.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"block text-sm text-neutral4",children:"Email"}),o.jsx(kn,{id:"email",type:"email",value:S,onChange:M=>w(M.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:"block text-sm text-neutral4",children:"Password"}),o.jsx(kn,{id:"password",type:"password",value:k,onChange:M=>_(M.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),F&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:F.message}),o.jsx(de,{type:"submit",disabled:P,className:"w-full",size:"lg",children:P?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:L,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),j&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"w-full border-t border-border1"})}),o.jsx("div",{className:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 px-2 text-neutral3",children:"or continue with"})})]}),j&&N&&o.jsxs(de,{onClick:H,disabled:h,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),h?"Redirecting...":N.text||"Sign in"]})]})}function Xns(){const[e]=ga(),t=bs(),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(uFt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const Kf=Mi.KeyValueList;function Kns(e){return e instanceof Date?e:new Date(e)}function Jns({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,p=Kns(e.timestamp),h=e.traceId,m=e.spanId;return o.jsxs(Mi,{collapsed:d,children:[o.jsxs(Mi.Header,{children:[o.jsxs(Mi.Heading,{children:["Log ",o.jsx("b",{children:er(p,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Dr,{className:"ml-auto shrink-0",children:[l&&o.jsx(de,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(Gq,{}):o.jsx(Uxe,{})}),o.jsxs(Dr,{spacing:"close",children:[o.jsx(de,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(Zq,{})}),o.jsx(de,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(zD,{})})]}),o.jsx(Mi.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Mi.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(h||m)&&o.jsxs("div",{className:K("grid gap-2 my-8","[&>button]:justify-between [&>button]:overflow-hidden"),children:[h&&o.jsxs(Dr,{spacing:"close",className:"min-w-0 w-full",children:[o.jsxs(de,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(h),children:[o.jsx($z,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:" ml-auto text-ui-sm text-neutral2 min-w-0 truncate",children:["# ",h]})]}),o.jsx(ka,{content:h,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Dr,{spacing:"close",className:"min-w-0 w-full",children:[o.jsxs(de,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!h||!r,onClick:()=>h&&r?.(h,m),children:[o.jsx($z,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:" ml-auto text-ui-sm text-neutral2 min-w-0 truncate",children:["# ",m]})]}),o.jsx(ka,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(Kf,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Entity Type"}),o.jsx(Kf.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Entity Name"}),o.jsx(Kf.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Service"}),o.jsx(Kf.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Environment"}),o.jsx(Kf.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(Kf.Key,{children:"Source"}),o.jsx(Kf.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(Kf.Key,{children:v}),o.jsx(Kf.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Mi.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function ers({error:e,resource:t,errorTitle:n}){if(gs(e))return o.jsx(Vs,{});if(ys(e))return o.jsx(Ds,{resource:t});if(iOt(e,"logs"))return o.jsx(Cr,{iconSlot:o.jsx(Qq,{}),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(zi,{title:n,message:r??"Unknown error"})}function trs({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 gap-4 items-start",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid gap-4 h-full 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 nrs={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 rrs({level:e}){const t=nrs[e];return o.jsx(ko,{height:"compact",children:o.jsx("span",{className:"uppercase text-ui-sm font-semibold",style:{color:t.color},children:t.label})})}function srs({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case Os.AGENT:return o.jsx(al,{className:n,"aria-hidden":!0});case"workflow":case Os.WORKFLOW_RUN:return o.jsx(jd,{className:n,"aria-hidden":!0});case Os.TOOL:return o.jsx(Jp,{className:n,"aria-hidden":!0});default:return null}}function ars({entityType:e,entityName:t}){const n=e??"";return o.jsxs(ko,{height:"compact",className:"flex min-w-0 items-center gap-2",children:[o.jsx(srs,{entityType:n}),t?o.jsx("span",{className:"min-w-0 text-ui-smd truncate",children:t}):"-"]})}function irs({message:e}){return o.jsx(ko,{height:"compact",className:"text-neutral4 text-ui-smd min-w-0 truncate font-mono",children:e})}function ors({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(ko,{height:"compact",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(sSe,{children:t})}const Ul=Object.assign(S3,{Top:JV,TopCell:R_,TopCellWithTooltip:eH,TopCellSmart:sSt,RowWrapper:cSe,RowButton:k3,RowLink:aSt,Spacer:lSe,NoMatch:KV,DateCell:aSe,TimeCell:iSe,LevelCell:rrs,EntityCell:ars,MessageCell:irs,DataCell:ors,NextPageLoading:XV}),QQe="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",lrs=36,crs=8;function urs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=H9t({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>lrs,overscan:crs}),d=g.useRef(t);if(g.useEffect(()=>{d.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),d.current=t},[t]),t)return o.jsx(nl,{columns:QQe});const f=u.getVirtualItems(),p=u.getTotalSize(),h=f[0]?.start??0,m=f.length>0?Math.max(0,p-(f[f.length-1]?.end??0)):0;return o.jsxs(Ul,{columns:QQe,variant:"striped",scrollRef:c,className:"min-w-0",children:[o.jsxs(Ul.Top,{children:[o.jsx(Ul.TopCell,{children:"Date"}),o.jsx(Ul.TopCell,{children:"Time"}),o.jsx(Ul.TopCell,{children:"Level"}),o.jsx(Ul.TopCell,{children:"Entity"}),o.jsx(Ul.TopCell,{children:"Message"}),o.jsx(Ul.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Ul.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Ul.Spacer,{height:h}),f.map(v=>{const y=e[v.index];if(!y)return null;const b=a.get(y);if(!b)return null;const S=b===i;return o.jsxs(Ul.RowButton,{ref:u.measureElement,"data-index":v.index,onClick:()=>l(y),featured:S,variant:y.level==="error"||y.level==="fatal"?"error":"default",children:[o.jsx(Ul.DateCell,{timestamp:y.timestamp}),o.jsx(Ul.TimeCell,{timestamp:y.timestamp}),o.jsx(Ul.LevelCell,{level:y.level}),o.jsx(Ul.EntityCell,{entityType:y.entityType,entityName:y.entityName}),o.jsx(Ul.MessageCell,{message:y.message}),o.jsx(Ul.DataCell,{data:y.data})]},b)}),o.jsx(Ul.Spacer,{height:m})]}),o.jsx(Ul.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function drs({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=>frs(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(hTe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(fTe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function frs(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 prs={"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"},ose="MMM d, yyyy HH:mm",lse="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function hrs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${prs[e]}`,description:lse}:t&&n?{title:`No logs between ${er(t,ose)} and ${er(n,ose)}`,description:lse}:t?{title:`No logs since ${er(t,ose)}`,description:lse}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const mrs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=hrs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Qq,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(de,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(qxe,{})]})})})},grs=20,vrs=1e4;function yrs(e,t,n){if(e?.pagination?.hasMore)return n+1}function brs(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 xrs(e){return iOt(e.state.error,"logs")?!1:vrs}const wrs=({filters:e}={})=>{const t=We(),{inView:n,setRef:r}=N_(),s=P1({queryKey:["logs",e],queryFn:({pageParam:p})=>t.listLogsVNext({pagination:{page:p,perPage:grs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:yrs,select:brs,retry:!1,refetchInterval:xrs}),{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}},iF={AGENT:Os.AGENT,WORKFLOW:Os.WORKFLOW_RUN,SCORER:Os.SCORER,INGEST:Os.RAG_INGESTION},dFt=[{label:"Agent",entityType:iF.AGENT},{label:"Workflow",entityType:iF.WORKFLOW},{label:"Scorer",entityType:iF.SCORER},{label:"Ingest",entityType:iF.INGEST}],Srs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],$x="rootEntityType",qb="datePreset",Vb="dateFrom",Hb="dateTo",krs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),_l={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"},X4=Object.keys(_l),ITe=new Set(["tags"]),ATe="mastra:logs:saved-filters";function Ors(e,t=ATe){const n=Trs(e),r=e.get(qb);r&&n.set(qb,r);const s=e.get(Vb);s&&n.set(Vb,s);const a=e.get(Hb);a&&n.set(Hb,a);try{localStorage.setItem(t,n.toString())}catch{}}function _rs(e=ATe){try{localStorage.removeItem(e)}catch{}}function YQe(e=ATe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Crs(e){if(e.has(qb)||e.has(Vb)||e.has(Hb)||e.has($x))return!0;for(const t of X4)if(e.has(_l[t]))return!0;return!1}function Ers({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:dFt.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:Srs.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 jrs(e){const t=[],n=new Map([[$x,"rootEntityType"]]);for(const s of X4)n.set(_l[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),ITe.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 Trs(e){const t=new URLSearchParams,n=e.get($x);n&&t.set($x,n);for(const r of X4){const s=_l[r];if(ITe.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 Nrs(e,t){e.delete($x);for(const n of X4)e.delete(_l[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set($x,n.value);continue}const r=_l[n.fieldId];if(r){if(ITe.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 Irs({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 Ars(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 Rrs="Filters setting for Logs saved",Prs="Filters setting for Logs cleared up";function $rs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>YQe(r)!==null),c=g.useCallback(()=>{Ors(e,r),l(!0);const f=s?.saved??Rrs;f!==!1&&De.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{_rs(r),l(!1);const f=s?.cleared??Prs;f!==!1&&De.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Crs(e)))return;const f=YQe(r);f&&t(p=>{const h=new URLSearchParams(p);for(const[m,v]of f)h.append(m,v);return h},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function Mrs(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 Drs(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,Mrs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function Lrs(e,t,n,r){const s=g.useMemo(()=>Drs(e),[e]),a=g.useMemo(()=>{const h=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&h.set(y,{log:v,idx:m})}return h},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(h=>s.get(h),[s]),d=g.useCallback(h=>{const m=s.get(h);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const h=e[l-1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0,p=l>=0&&l<e.length-1?()=>{const h=e[l+1];if(!h)return;const m=s.get(h);m&&n(r?{logId:m,traceId:h.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:p}}const Qve="logId",Yve="traceId",Xve="spanId",PR=1440*60*1e3,Frs={"last-24h":PR,"last-3d":3*PR,"last-7d":7*PR,"last-14d":14*PR,"last-30d":30*PR};function oF(e){e.delete(Qve),e.delete(Yve),e.delete(Xve)}function zrs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const _=e.get(qb);return _&&krs.has(_)?_:"last-24h"},[e]),a=e.get(Vb),i=e.get(Hb),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const C=new Date(a);return Number.isNaN(C.getTime())?void 0:C}if(s==="all")return;const _=Frs[s];return _?new Date(Date.now()-_):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const _=new Date(i);return Number.isNaN(_.getTime())?void 0:_},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(Qve),f=e.get(Yve),p=e.get(Xve),h=g.useMemo(()=>dFt.find(_=>_.entityType===e.get($x)),[e]),m=g.useMemo(()=>jrs(e),[e]),v=g.useCallback(_=>{t(C=>{const j=new URLSearchParams(C);for(const[E,N]of Object.entries(_)){const I=E==="logId"?Qve:E==="traceId"?Yve:Xve;N?j.set(I,N):j.delete(I)}return j},{replace:!0})},[t]),y=g.useCallback(_=>{t(C=>{const j=new URLSearchParams(C);return Nrs(j,_),oF(j),j},{replace:!0})},[t]),b=y,S=g.useCallback((_,C)=>{if(u.current!=="custom")return;const j=C==="from"?Vb:Hb;t(E=>{const N=new URLSearchParams(E);return _?N.set(j,_.toISOString()):N.delete(j),oF(N),N},{replace:!0})},[t]),w=g.useCallback(_=>{u.current=_,t(C=>{const j=new URLSearchParams(C);return _==="last-24h"?(j.delete(qb),j.delete(Vb),j.delete(Hb)):_==="custom"?j.set(qb,"custom"):(j.set(qb,_),j.delete(Vb),j.delete(Hb)),oF(j),j},{replace:!0})},[t]),k=g.useCallback(()=>{t(_=>{const C=new URLSearchParams(_);C.delete($x);for(const j of X4)C.delete(_l[j]);return C.delete(qb),C.delete(Vb),C.delete(Hb),oF(C),C},{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:p,selectedEntityOption:h,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:S,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,p,h,m,v,b,S,w,k,y])}const wb=Mi.KeyValueList;function Brs({spanId:e,span:t,isLoading:n,onClose:r}){const s=t?.startedAt&&t?.endedAt?new Date(t.endedAt).getTime()-new Date(t.startedAt).getTime():null;return o.jsxs(Mi,{children:[o.jsxs(Mi.Header,{children:[o.jsxs(Mi.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Mi.CloseButton,{onClick:r})]}),n?o.jsx(Mi.LoadingData,{children:"Loading span..."}):t?o.jsxs(Mi.Content,{children:[o.jsxs(wb,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Type"}),o.jsx(wb.Value,{children:t.spanType})]}),t.startedAt&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Started"}),o.jsx(wb.Value,{children:er(new Date(t.startedAt),"MMM dd, HH:mm:ss.SSS")})]}),t.endedAt&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Ended"}),o.jsx(wb.Value,{children:er(new Date(t.endedAt),"MMM dd, HH:mm:ss.SSS")})]}),s!=null&&o.jsxs(o.Fragment,{children:[o.jsx(wb.Key,{children:"Duration"}),o.jsx(wb.Value,{children:s<1e3?`${s}ms`:`${(s/1e3).toFixed(2)}s`})]})]}),o.jsx("br",{}),o.jsx(Mi.CodeSection,{title:"Input",icon:o.jsx(Ufe,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Output",icon:o.jsx(qfe,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Metadata",icon:o.jsx(pw,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Mi.CodeSection,{title:"Attributes",icon:o.jsx(pw,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Mi.NoData,{children:"Span not found."})]})}function Urs(){const[e,t]=ga(),n=zrs(e,t),r=$rs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=STe(),{data:d=[],isPending:f}=bTe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:p=[],isPending:h}=xTe(),{data:m=[],isPending:v}=wTe(),y=g.useMemo(()=>Ers({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:p,loading:{tags:u,entityNames:f,serviceNames:v,environments:h}}),[c,d,m,p,u,f,v,h]),b=g.useMemo(()=>Irs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:S=[],isLoading:w,error:k,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:j}=wrs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:P}=Lrs(S,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:F,isLoading:D}=sH(n.featuredTraceId??null),{data:V,isLoading:H}=HN(n.featuredTraceId??"",n.featuredSpanId??""),L=g.useCallback(()=>n.applyFilterTokens(Ars(y,n.filterTokens)),[y,n]),z=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),B=g.useCallback(X=>n.handleFeaturedChange({traceId:X,spanId:null}),[n]),M=g.useCallback((X,te)=>n.handleFeaturedChange({traceId:X,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),q=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(X=>n.handleFeaturedChange({spanId:X??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(dTe,{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(mTe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(drs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:L,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(ers,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const Z=!!n.selectedEntityOption||n.filterTokens.length>0;return S.length===0&&!w&&!Z?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(mrs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(trs,{logCollapsed:i,listSlot:o.jsx(urs,{logs:S,isLoading:w,isFetchingNextPage:_,hasNextPage:C,setEndOfListElement:j,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Jns,{log:N,onClose:z,onTraceClick:B,onSpanClick:M,onPrevious:A,onNext:P,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(jSt,{traceId:n.featuredTraceId,spans:F?.spans,isLoading:D,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(Brs,{spanId:n.featuredSpanId,span:V?.span,isLoading:H,onClose:q}):null})]})}function qrs({server:e}){const{paths:t,Link:n}=yn(),s=We().options.baseUrl,a=s?`${s}/api/mcp/${e.id}/sse`:"",{data:i}=oLt(e),l=Object.values(i||{}),c=l.length,u=l.filter(p=>p.toolType==="agent").length,d=l.filter(p=>p.toolType==="workflow").length,f=dm(e.name,50);return o.jsxs(me.RowLink,{to:t.mcpServerLink(e.id),LinkComponent:n,children:[o.jsx(me.NameCell,{children:f}),o.jsx(me.DescriptionCell,{children:a}),o.jsx(me.TextCell,{className:"text-center",children:u||""}),o.jsx(me.TextCell,{className:"text-center",children:c||""}),o.jsx(me.TextCell,{className:"text-center",children:d||""})]})}function Vrs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const s=n.toLowerCase();return e.filter(a=>a.name?.toLowerCase().includes(s)||a.id?.toLowerCase().includes(s))},[e,n]);return t?o.jsx(nl,{columns:"auto 1fr auto auto auto"}):o.jsxs(me,{columns:"auto 1fr auto auto auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"URL"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(al,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Tools",short:o.jsx(Jp,{}),tooltip:"Tools",className:"text-center"}),o.jsx(me.TopCellSmart,{long:"Workflows",short:o.jsx(jd,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(me.NoMatch,{message:"No MCP Servers match your search"}):null,r.map(s=>o.jsx(qrs,{server:s},s.id))]})}const Hrs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Oa,{})]})})}),Wrs=()=>{const{data:e=[],isLoading:t,error:n}=LZ(),[r,s]=g.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"MCP servers"})}):n?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(lr,{children:o.jsx(Hrs,{})}):o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(Vrs,{mcpServers:e,isLoading:t,search:r})]})},Zrs=(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 Grs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=yn(),i=g.useMemo(()=>Zrs(e,t),[e,t]),l=g.useMemo(()=>i.filter(c=>c.id.toLowerCase().includes(r.toLowerCase())),[i,r]);return n?o.jsx(nl,{columns:"auto 1fr auto"}):o.jsxs(me,{columns:"auto 1fr auto",variant:"striped",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Name"}),o.jsx(me.TopCell,{children:"Description"}),o.jsx(me.TopCellSmart,{long:"Agents",short:o.jsx(al,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(me.NoMatch,{message:"No Tools match your search"}):null,l.map(c=>{const u=dm(c.id,50),d=dm(c.description??"",200),f=c.agents.length;return o.jsxs(me.RowLink,{to:s.toolLink(c.id),LinkComponent:a,children:[o.jsx(me.NameCell,{children:u}),o.jsx(me.DescriptionCell,{children:d}),o.jsx(me.TextCell,{className:"text-center",children:f||""})]},c.id)})]})}const Qrs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Oa,{})]})})}),Yrs=()=>{const e=We();return Rn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new l_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw De.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},Xrs=({toolId:e})=>{const{canExecute:t}=il(),n=t("tools"),{data:r={}}=km(),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}=frr(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=Yrs(),{requestContext:p}=_s();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";De.error(`Error loading tool: ${v}`)}},[l]);const h=async(v,y)=>{if(!c)return;const b={...p??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?cm(om(gx(c?.inputSchema))):Ss({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(Xje,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:h,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function Krs({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}){const{data:c={},isLoading:u,isError:d,error:f}=ZN(),{data:p={},isLoading:h,isError:m,error:v}=km(),{navigate:y,paths:b}=yn();g.useEffect(()=>{if(d){const _=f instanceof Error?f.message:"Failed to load tools";De.error(`Error loading tools: ${_}`)}},[d,f]),g.useEffect(()=>{if(m){const _=v instanceof Error?v.message:"Failed to load agents";De.error(`Error loading agents: ${_}`)}},[m,v]);const S=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(C=>{S.has(C.id)||S.set(C.id,C)})}),Object.values(c).forEach(_=>{S.has(_.id)||S.set(_.id,_)});const w=Array.from(S.values()).map(_=>({label:_.id,value:_.id})),k=_=>{t?t(_):_&&_!==e&&y(b.toolLink(_))};return o.jsx(Jl,{options:w,value:e,onValueChange:k,placeholder:u||h?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||u||h||d||m,variant:l})}const Jrs=({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(Sy,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 font-medium py-20 text-center",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(Sy,{isDivided:!0,children:[o.jsxs("div",{className:"px-8 py-12 mx-auto max-w-2xl w-full",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 font-medium pb-4",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-6",children:[o.jsx(dn,{icon:o.jsx(ySt,{className:"text-neutral6"}),className:"rounded-r-sm text-neutral4!",children:"Version"}),o.jsx(dn,{className:"rounded-l-sm text-neutral4!",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:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"rounded-lg border border-border1 bg-surface3 p-4",children:[o.jsx(dn,{icon:o.jsx("span",{className:"font-mono w-6 text-accent1 font-medium mr-1",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:"px-2 py-1 bg-surface4 rounded-lg",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(ka,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"h-full overflow-y-scroll border-l border-border1",children:o.jsx(ess,{server:t})})]})},ess=({server:e})=>{const{data:t={},isLoading:n}=oLt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"p-5 overflow-y-scroll",children:[o.jsxs("div",{className:"text-neutral6 flex gap-2 items-center",children:[o.jsx(Ue,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(P_,{})}),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(nss,{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 nss=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=yn(),a=P6t[e.toolType||"tool"],i=tss(e._meta);return o.jsxs(Nf,{onClick:()=>n.current?.click(),children:[o.jsx(BCt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Af,{children:[o.jsx(If,{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(dn,{className:"text-[10px] py-0",children:"App"})]})}),o.jsx(eh,{children:e.description})]})]})},rss=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=LZ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(Jrs,{isLoading:n,server:r})})};function sss(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}=il(),r=n("tools"),s=We(),{data:a,isLoading:i,error:l}=wje(t,e),{mutateAsync:c,isPending:u,data:d}=vBr(t,e),f=a?sss(a._meta):void 0,{data:p}=St({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),h=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";De.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(xt,{className:"h-8 w-48 mb-4"}),o.jsx(xt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"py-12 text-center px-6",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=cm(om(a.inputSchema))}catch(y){console.error("Error processing input schema:",y),De.error("Failed to process tool input schema."),v=Ss({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[p&&o.jsx("div",{className:"border-b border-border1 p-4",children:o.jsx(iLt,{html:p,toolName:a.name??a.id,onToolCall:h})}),o.jsx(Xje,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},iss=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=wje(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})})},fFt=[{label:"Agent",entityType:Os.AGENT},{label:"Workflow",entityType:Os.WORKFLOW_RUN},{label:"Scorer",entityType:Os.SCORER},{label:"Ingest",entityType:Os.RAG_INGESTION}],uN="rootEntityType",dN={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"},nG=Object.keys(dN),RTe="mastra:metrics:saved-filters";function oss(e){const t=fss(e);try{localStorage.setItem(RTe,t.toString())}catch{}}function lss(){try{localStorage.removeItem(RTe)}catch{}}function pFt(){try{const e=localStorage.getItem(RTe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function css(e){if(e.has(uN))return!0;for(const t of nG)if(e.has(dN[t]))return!0;return!1}function uss({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:fFt.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 dss(e){const t=[],n=new Map([[uN,"rootEntityType"]]);for(const s of nG)n.set(dN[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(uN);for(const r of n)t.append(uN,r);for(const r of nG){const s=dN[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function pss(e,t){e.delete(uN);for(const n of nG)e.delete(dN[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?uN:dN[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 hss="Any";function XQe(e){const t=e.trim();return t===""||t===hss}const mss=new Set(fFt.map(e=>e.entityType));function KQe(e){const t=e.trim();return mss.has(t)?t:void 0}function gss(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=>!XQe(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?KQe(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(XQe(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=KQe(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const hFt=[{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(hFt.map(e=>e.value));function yss(e){return typeof e=="string"&&(vss.has(e)||e==="custom")}const mFt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function rG(){return g.useContext(mFt)}function bss(e,t){return e!=="custom"?hFt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${er(t.from,"MMM d, yyyy")} – ${er(t.to,"MMM d, yyyy")}`:er(t.from,"MMM d, yyyy"):"Custom range"}function xss({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(()=>gss(d),[d]),p=g.useMemo(()=>JSON.stringify(f),[f]),h=bss(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:h,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:p,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,h,d,s,f,p,l,c]);return o.jsx(mFt.Provider,{value:m,children:e})}const wss=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function Sss(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 kss(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 Oss(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=rG(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(dTe,{preset:Sss(e),onPresetChange:i=>{const l=kss(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:wss})}const Kve=1440*60*1e3,_ss={"24h":Kve,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function Css(e,t,n){if(e!=="custom"){const r=_ss[e]??Kve;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-Kve),end:t?.to??new Date(n)}}function jm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=rG(),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(()=>Css(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 gFt(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function K4({href:e,LinkComponent:t="a"}){return o.jsx(de,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(TOn,{})})}function Ess({href:e,LinkComponent:t="a"}){return o.jsx(de,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(d_n,{})})}const jss=[{dataKey:"p50",label:"p50",color:Pp.blue,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p50,0)/e.length)}`:"0",suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Pp.yellow,aggregate:e=>({value:e.length>0?`${Math.round(e.reduce((t,n)=>t+n.p95,0)/e.length)}`:"0",suffix:"avg ms"})}];function Tss(e){return e==="agents"||e==="workflows"||e==="tools"}function cse({data:e,onPointClick:t}){return e.length===0?o.jsx(Ut.NoData,{message:"No latency data yet"}):o.jsx(LU,{data:e,series:jss,onPointClick:t?n=>{const r=n;typeof r?.tsMs=="number"&&Number.isFinite(r.tsMs)&&t(r)}:void 0})}function Nss({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"),p=c[d]?d:u,h=typeof s=="function"?s(p):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,S)=>b+S,0)/v.length)}ms`:"—";return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Ut.Summary,{value:y,label:"Avg p50"}),h?o.jsx(Ut.Actions,{children:h}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load latency data"}):o.jsx(Ut.Content,{children:m?o.jsxs(Ic,{value:p,onValueChange:b=>{Tss(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(Ar,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(Ar,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:o.jsx(cse,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Xr,{value:"workflows",children:o.jsx(cse,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Xr,{value:"tools",children:o.jsx(cse,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Ut.NoData,{message:"No latency data yet"})})]})}function Iss(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 Ass(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 vFt(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=Iss(s);l&&e.set(t,l)}function To(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function yFt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function JQe({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/observability"}){const a=new URLSearchParams;a.set(bw,"branches"),vFt(a,xw,ww,Sw,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Rx,i),r.status&&a.set(Px,r.status),To(a,Ol.entityName,r.entityName??n.entityName),To(a,Ol.threadId,r.threadId??n.threadId),To(a,Ol.resourceId,r.resourceId??n.resourceId),To(a,Ol.entityId,n.entityId),To(a,Ol.runId,n.runId),To(a,Ol.sessionId,n.sessionId),To(a,Ol.requestId,n.requestId),To(a,Ol.userId,n.userId),To(a,Ol.organizationId,n.organizationId),To(a,Ol.experimentId,n.experimentId),To(a,Ol.serviceName,n.serviceName),To(a,Ol.environment,n.environment),yFt(a,Ol.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function Rss({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;vFt(a,qb,Vb,Hb,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set($x,i),To(a,_l.entityName,r.entityName??n.entityName),To(a,_l.threadId,r.threadId??n.threadId),To(a,_l.resourceId,r.resourceId??n.resourceId),To(a,_l.runId,n.runId),To(a,_l.sessionId,n.sessionId),To(a,_l.requestId,n.requestId),To(a,_l.userId,n.userId),To(a,_l.organizationId,n.organizationId),To(a,_l.experimentId,n.experimentId),To(a,_l.serviceName,n.serviceName),To(a,_l.environment,n.environment),yFt(a,_l.tags,n.tags),r.status==="error"&&a.append(_l.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function _I(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=rG(),a=g.useCallback((c={})=>JQe({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>Rss({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=Ass(u,d);return JQe({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const bFt="1h";async function use(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:bFt,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 Pss(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([use(e,"mastra_agent_duration_ms",t),use(e,"mastra_workflow_duration_ms",t),use(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:bFt}}})}const eYe={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function $ss(){const{data:e,isLoading:t,isError:n}=Pss(),{getTracesHref:r,getBucketTracesHref:s}=_I(),{Link:a}=yn(),i=bs();return o.jsx(Nss,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:eYe[l]},c.tsMs,"1h"))},actions:l=>o.jsx(K4,{href:r({rootEntityType:eYe[l]}),LinkComponent:a})})}function Mss(e){return e==="threads"||e==="resources"}function dse(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function Dss({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,p=e.data?.reduce((y,b)=>y+b.runs,0)??0,h=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(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Ut.Summary,{value:p.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Ut.Summary,{value:h.toLocaleString(),label:"Total threads"}),v?o.jsx(Ut.Actions,{children:v}):null]}),m.isLoading?o.jsx(Ut.Loading,{}):m.isError?o.jsx(Ut.Error,{message:"Failed to load memory data"}):o.jsx(Ut.Content,{children:o.jsxs(Ic,{defaultTab:"threads",value:i,onValueChange:y=>{Mss(y)&&l(y)},className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"threads",children:"Threads"}),o.jsx(Ar,{value:"resources",children:"Resources"})]}),o.jsx(Xr,{value:"threads",children:d?o.jsxs(me,{columns:"auto auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:dse(y.threadId)}),o.jsx(me.NumberCell,{children:y.resourceId?dse(y.resourceId):"—"}),o.jsx(me.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?xc(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?wg(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(me.RowStatic,{children:S},y.key)})]}):o.jsx(Ut.NoData,{message:"No thread activity yet"})}),o.jsx(Xr,{value:"resources",children:f?o.jsxs(me,{columns:"auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),S=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:dse(y.resourceId)}),o.jsx(me.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(me.NumberCell,{children:y.tokens>0?xc(y.tokens):"—"}),o.jsx(me.NumberCell,{children:y.cost!=null?wg(y.cost,y.costUnit):"—"})]});return b?o.jsx(me.RowLink,{to:b,LinkComponent:a,children:S},y.key):o.jsx(me.RowStatic,{children:S},y.key)})]}):o.jsx(Ut.NoData,{message:"No resource activity yet"})})]})})]})}function J4(e,t,n){const r=e.get(t);if(r!==void 0)return r;const s=n();return e.set(t,s),s}const fse=20;function Lss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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:fse}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:fse}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:fse})]),l=new Map,c=d=>J4(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.threadId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,p=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}const pse=20;function Fss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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:pse}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:pse}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:pse})]),l=new Map,c=d=>J4(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const p=f.dimensions.resourceId;if(!p)continue;const h=c(p);h.tokens+=f.value,f.estimatedCost!=null&&(h.cost=(h.cost??0)+f.estimatedCost,f.costUnit&&(h.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,p=l.get(f);return{resourceId:f,threadCount:d.value,tokens:p?.tokens??0,cost:p?.cost??null,costUnit:p?.costUnit??null}})}})}function zss(){const e=Lss(),t=Fss(),{getTracesHref:n}=_I(),{Link:r}=yn();return o.jsx(Dss,{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 e5({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 Bss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Uss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 qss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Vss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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 Hss(){const{data:e,isLoading:t,isError:n}=gFt();return o.jsx(e5,{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 Wss(){const{data:e,isLoading:t,isError:n}=qss();return o.jsx(e5,{label:"Total Model Cost",value:e?.cost!=null?wg(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?wg(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function Zss(){const{data:e,isLoading:t,isError:n}=Vss();return o.jsx(e5,{label:"Total Tokens",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Gss(){const{data:e,isLoading:t,isError:n}=Uss();return o.jsx(e5,{label:"Total Threads",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Qss(){const{data:e,isLoading:t,isError:n}=Bss();return o.jsx(e5,{label:"Total Resources",value:e?.value!=null?xc(e.value):null,prevValue:e?.previousValue!=null?xc(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function Yss({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=>Xss(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(hTe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(fTe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Xss(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 Kss({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.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?wg(l):"—":c.size===1?u=l>0?wg(l,[...c][0]):"—":u="Mixed",o.jsx(Ut.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Ut.Actions,{children:s}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load model usage data"}):o.jsx(Ut.Content,{children:i?o.jsxs(me,{columns:"auto auto auto auto auto auto",...Zve,children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{sticky:"start",children:"Model"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(me.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(me.RowHeaderCell,{height:"compact",className:"text-ui-sm",children:l.model}),o.jsx(me.NumberCell,{children:l.input}),o.jsx(me.NumberCell,{children:l.output}),o.jsx(me.NumberCell,{children:l.cacheRead}),o.jsx(me.NumberCell,{children:l.cacheWrite}),o.jsx(me.NumberCell,{highlight:!0,children:l.cost!=null?wg(l.cost,l.costUnit):"—"})]});return c?o.jsx(me.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(me.RowStatic,{children:u},l.model)})]}):o.jsx(Ut.NoData,{message:"No model usage data yet"})})]})}function Jss(){const e=We(),{filters:t,filterKey:n}=jm();return St({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=>J4(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",p=c(f);p.input=d.value,u(p,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",p=c(f);p.output=d.value,u(p,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",p=c(f);p.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:xc(f.input),output:xc(f.output),cacheRead:xc(f.cacheRead),cacheWrite:xc(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function eas(){const{data:e,isLoading:t,isError:n}=Jss(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(Kss,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Os.AGENT}),actions:o.jsx(K4,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function tas(e){return e==="tokens"||e==="cost"}function nas({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,S)=>b+S.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),p=new Set(f.map(b=>b.costUnit??"usd")),h=p.size<=1,m=h?[...p][0]??"usd":null,v=h?f.reduce((b,S)=>b+(S.cost??0),0):0,y=h&&v>0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Ut.Summary,{value:wg(v,m),label:"Total cost"}):o.jsx(Ut.Summary,{value:xc(d),label:"Total tokens"})),u&&s?o.jsx(Ut.Actions,{children:s}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load token usage data"}):o.jsx(Ut.Content,{children:u?o.jsxs(Ic,{defaultTab:"tokens",value:i,onValueChange:b=>{tas(b)&&l(b)},className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(cN,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Pp.blueDark},{label:"Output",color:Pp.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:xc})}),o.jsx(Xr,{value:"cost",children:y?o.jsx(cN,{LinkComponent:a,data:f.slice().sort((b,S)=>(S.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Pp.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>wg(b,m)}):o.jsx(Ut.NoData,{message:"No cost data yet"})})]}):o.jsx(Ut.NoData,{message:"No token usage data yet"})})]})}function ras(){const e=We(),{filters:t,filterKey:n}=jm();return St({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=>J4(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 sas(){const{data:e,isLoading:t,isError:n}=ras(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(nas,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Os.AGENT,entityName:a.name}),actions:o.jsx(K4,{href:r({rootEntityType:Os.AGENT}),LinkComponent:s})})}function Jve(e,t=xc){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const aas=[{dataKey:"input",label:"Input tokens",color:Pp.blue,aggregate:Jve("input")},{dataKey:"output",label:"Output tokens",color:Pp.yellow,aggregate:Jve("output")}];function ias(e){return e==="tokens"||e==="cost"}function oas({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,_)=>k+_.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),p=f.map(k=>({...k})),h=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=h.size===1&&f.every(k=>k.costUnit!=null),v=m?[...h][0]??null:null,y=m?f.reduce((k,_)=>k+(_.cost??0),0):0,b=m&&y>0,S=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Pp.purple,aggregate:Jve("cost",k=>wg(k,v))}];return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Token usage over time",description:S}),u&&(a==="cost"&&b?o.jsx(Ut.Summary,{value:wg(y,v),label:"Total cost"}):o.jsx(Ut.Summary,{value:xc(d),label:"Total tokens"})),u&&s?o.jsx(Ut.Actions,{children:s}):null]}),n?o.jsx(Ut.Loading,{}):r?o.jsx(Ut.Error,{message:"Failed to load token usage timeline"}):o.jsx(Ut.Content,{children:u?o.jsxs(Ic,{defaultTab:"tokens",value:a,onValueChange:k=>{ias(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"tokens",children:"Tokens"}),o.jsx(Ar,{value:"cost",children:"Cost"})]}),o.jsx(Xr,{value:"tokens",children:o.jsx(LU,{data:c,series:aas})}),o.jsx(Xr,{value:"cost",children:b?o.jsx(LU,{data:p,series:w}):o.jsx(Ut.NoData,{message:"No cost data yet"})})]}):o.jsx(Ut.NoData,{message:"No token usage data yet"})})]})}function las(e){return e==="24h"?"1h":"1d"}function cas(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 tYe(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 uas(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function das(){const e=We(),{datePreset:t,filters:n,filterKey:r}=jm(),s=las(t);return St({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 tYe(l,a.series[0],"input"),tYe(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:cas(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:uas(u)}}),interval:s}}})}function fas(){const{data:e,isLoading:t,isError:n}=das(),{getTracesHref:r}=_I(),{Link:s}=yn();return o.jsx(oas,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(K4,{href:r(),LinkComponent:s})})}function hse({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(cN,{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:Pp.blueDark},{label:"Errors",color:Pp.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:xc})}function pas({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,p=m=>r?v=>r(m,v):void 0,h=m=>s?v=>s(m,v):void 0;return o.jsxs(Ut,{children:[o.jsxs(Ut.TopBar,{children:[o.jsx(Ut.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Ut.Summary,{value:xc(f),label:"Total runs"}),u?o.jsx(Ut.Actions,{children:u}):null]}),t?o.jsx(Ut.Loading,{}):n?o.jsx(Ut.Error,{message:"Failed to load trace volume data"}):o.jsx(Ut.Content,{children:d?o.jsxs(Ic,{value:l,onValueChange:c,defaultTab:"agents",className:"grid grid-rows-[auto_1fr] overflow-y-auto h-full",children:[o.jsxs(Nc,{children:[o.jsx(Ar,{value:"agents",children:"Agents"}),o.jsx(Ar,{value:"workflows",children:"Workflows"}),o.jsx(Ar,{value:"tools",children:"Tools"})]}),o.jsx(Xr,{value:"agents",children:e.agentData.length>0?o.jsx(hse,{data:e.agentData,rowHrefs:p("agents"),errorHrefs:h("agents"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No agent data yet"})}),o.jsx(Xr,{value:"workflows",children:e.workflowData.length>0?o.jsx(hse,{data:e.workflowData,rowHrefs:p("workflows"),errorHrefs:h("workflows"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No workflow data yet"})}),o.jsx(Xr,{value:"tools",children:e.toolData.length>0?o.jsx(hse,{data:e.toolData,rowHrefs:p("tools"),errorHrefs:h("tools"),LinkComponent:i}):o.jsx(Ut.NoData,{message:"No tool data yet"})})]}):o.jsx(Ut.NoData,{message:"No trace volume data yet"})})]})}async function mse(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=J4(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 has(){const e=We(),{filters:t,filterKey:n}=jm();return St({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mse(e,"mastra_agent_duration_ms",t),mse(e,"mastra_workflow_duration_ms",t),mse(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const lF={agents:Os.AGENT,workflows:Os.WORKFLOW_RUN,tools:Os.TOOL};function mas(){const{data:e,isLoading:t,isError:n}=has(),{getTracesHref:r,getLogsHref:s}=_I(),{Link:a}=yn();return o.jsx(pas,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:lF[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:lF[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(K4,{href:r({rootEntityType:lF[i]}),LinkComponent:a}),o.jsx(Ess,{href:s({rootEntityType:lF[i],status:"error"}),LinkComponent:a})]})})}const gas=new Set(["ObservabilityStorageClickhouseVNext","ObservabilityStorageDuckDB","ObservabilityInMemory","ObservabilitySpanner","ObservabilityStoragePostgresVNext"]),gse="period",cF="dateFrom",uF="dateTo";function vas(){const[e,t]=ga(),n=e.get(gse),r=yss(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=h=>{if(!h)return;const m=new Date(h);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(cF)),p=d(e.get(uF));if(!(!f&&!p))return{from:f,to:p}},[r,e.toString()]),a=g.useMemo(()=>dss(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d==="24h"?p.delete(gse):p.set(gse,d),d!=="custom"&&(p.delete(cF),p.delete(uF)),p},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return d?.from?p.set(cF,d.from.toISOString()):p.delete(cF),d?.to?p.set(uF,d.to.toISOString()):p.delete(uF),p},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const p=new URLSearchParams(f);return pss(p,d),p},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,css(e)))return;const d=pFt();d&&t(f=>{const p=new URLSearchParams(f);for(const[h,m]of d)p.append(h,m);return p},{replace:!0})},[]),o.jsx(xss,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(yas,{})})}function yas(){const[e]=ga(),{error:t,isLoading:n}=gFt(),{filterTokens:r,setFilterTokens:s}=rG(),[a,i]=g.useState(),{data:l,isLoading:c}=L3(),u=l?.observabilityStorageType,d=u?gas.has(u):!1,f=u==="ObservabilityInMemory",{data:p,isLoading:h}=STe(),{data:m,isLoading:v}=bTe(),{data:y,isLoading:b}=wTe(),{data:S,isLoading:w}=xTe(),k=g.useMemo(()=>uss({availableTags:p??[],availableEntityNames:m??[],availableServiceNames:y??[],availableEnvironments:S??[],loading:{tags:h,entityNames:v,serviceNames:b,environments:w}}),[p,m,y,S,h,v,b,w]),[_,C]=g.useState(()=>pFt()!==null),j=g.useCallback(()=>{oss(e),C(!0),De.success("Filters setting for Metrics saved")},[e]),E=g.useCallback(()=>{lss(),C(!1),De.success("Filters setting for Metrics cleared up")},[]),N=g.useCallback(()=>{s([])},[s]),I=g.useCallback(()=>{const A=r.map(P=>{const F=k.find(D=>D.id===P.fieldId);return F?F.kind==="text"?{fieldId:P.fieldId,value:""}:F.kind==="pick-multi"?F.multi?{fieldId:P.fieldId,value:[]}:{fieldId:P.fieldId,value:"Any"}:F.kind==="multi-select"?{fieldId:P.fieldId,value:[]}:P:P});s(A)},[k,r,s]);return t&&gs(t)?o.jsx(lr,{children:o.jsx(Vs,{})}):t&&ys(t)?o.jsx(lr,{children:o.jsx(Ds,{resource:"metrics"})}):t?o.jsx(lr,{children:o.jsx(zi,{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(Oss,{}),o.jsx(mTe,{fields:k,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(Yss,{isLoading:n,filterFields:k,filterTokens:r,onFilterTokensChange:s,onClear:I,onRemoveAll:N,onSave:j,onRemoveSaved:_?E:void 0,autoFocusFilterFieldId:a})]}),c?null:d?o.jsxs("div",{className:"grid gap-8 content-start pb-10",children:[f&&o.jsx(In,{variant:"info",title:"Metrics are not persisted",children:o.jsx(In.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(Gve,{children:[o.jsx(Hss,{}),o.jsx(Wss,{}),o.jsx(Zss,{}),o.jsx(Gss,{}),o.jsx(Qss,{})]}),o.jsxs(Gve,{children:[o.jsx(eas,{}),o.jsx(sas,{}),o.jsx(fas,{}),o.jsx(zss,{}),o.jsx(mas,{}),o.jsx($ss,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Cr,{iconSlot:o.jsx(Of,{}),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(de,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Oa,{})]})})})]})}function bas(){const{paths:e}=yn(),{data:t,isLoading:n,error:r}=M6t(),{isCmsAvailable:s}=Z1(),[a,i]=g.useState(""),l=t?.promptBlocks??[];return r&&gs(r)?o.jsx(lr,{children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx(lr,{children:o.jsx(Ds,{resource:"prompt blocks"})}):r?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load prompt blocks",message:r.message})}):l.length===0&&!n?o.jsx(lr,{children:o.jsx(WGr,{})}):o.jsxs(Lt,{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(jf,{onSearch:i,label:"Filter prompts",placeholder:"Filter by name or description"})}),s&&o.jsxs(de,{as:Ma,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Hr,{}),"Create Prompt"]})]})}),o.jsx(HGr,{promptBlocks:l,isLoading:n,search:a})]})}function xas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(ZBr,{children:o.jsx(xve,{})})})})}const was=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:bun,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Dlt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Oa,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:Qj,href:"https://discord.gg/BTYqqHKUrf",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Hlt,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:Llt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Sas(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-3xl",children:was.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group flex flex-col gap-3 rounded-lg border border-border1 bg-surface2 p-5 transition-colors hover:border-accent1 hover:bg-surface3",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"h-5 w-5 text-icon3 group-hover:text-accent1 transition-colors"}),o.jsx("span",{className:"text-ui-md font-medium text-text1",children:e.title}),e.external&&o.jsx(Oa,{className:"h-3.5 w-3.5 text-icon3 ml-auto opacity-0 group-hover:opacity-100 transition-opacity"})]}),o.jsx("p",{className:"text-ui-sm text-text3 leading-relaxed",children:e.description})]},e.href))})})})}function kas(){const{data:e={},isLoading:t,error:n}=ih(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&gs(n))return o.jsx(lr,{children:o.jsx(Vs,{})});if(n&&ys(n))return o.jsx(lr,{children:o.jsx(Ds,{resource:"scorers"})});if(n)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(lr,{children:o.jsx(aZr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(oZr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(sZr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}function Oas(){const{scorerId:e}=ur(),[t,n]=ga(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:c,error:u}=$Wr(e),{data:d={},isLoading:f,error:p}=km(),{isLoading:h,error:m}=zy(),{data:v=[],isLoading:y,error:b,isFetchingNextPage:S,hasNextPage:w,setEndOfListElement:k}=PWr({scorerId:e,entityId:i?.value==="all"?void 0:i?.value,entityType:i?.type==="ALL"?void 0:i?.type}),_=g.useMemo(()=>c?.agentIds?.filter(B=>d[B]).map(B=>({value:B,label:d[B].name,type:"AGENT"}))||[],[c?.agentIds,d]),C=g.useMemo(()=>c?.workflowIds?.map(B=>({value:B,label:B,type:"WORKFLOW"}))||[],[c?.workflowIds]),j=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},..._,...C],[_,C]),E=t.get("entity")??"all",N=j.find(B=>B.value===E);N&&N.value!==i?.value&&l(N),g.useEffect(()=>{if(u){const B=u instanceof Error?u.message:"Failed to load scorer";De.error(`Error loading scorer: ${B}`)}},[u]),g.useEffect(()=>{if(p){const B=p instanceof Error?p.message:"Failed to load agents";De.error(`Error loading agents: ${B}`)}},[p]),g.useEffect(()=>{if(m){const B=m instanceof Error?m.message:"Failed to load workflows";De.error(`Error loading workflows: ${B}`)}},[m]);const I=B=>{B?.value&&n(M=>{const G=new URLSearchParams(M);return G.set("entity",B.value),G})};g.useEffect(()=>{const B=t.get("scoreId")??void 0;if(B===s)return;if(!B){a(void 0);return}v.find(G=>G.id===B)&&a(B)},[t,v]);const A=g.useCallback(B=>{a(B||void 0),n(M=>{const G=new URLSearchParams(M);return B?G.set("scoreId",B):G.delete("scoreId"),G})},[n]);if(!c)return null;const P=gs(u)||gs(p)||gs(m),F=u&&ys(u),D=!P&&!F&&(u||p||m),V=!y&&v.length===0,H=i?.value!=="all",L=c?.scorer?.source==="stored"?o.jsx(Iy,{owner:"scorer-detail",children:o.jsxs(de,{variant:"default",as:Ma,to:`/cms/scorers/${e}/edit`,size:"sm",children:[o.jsx(sm,{})," Edit"]})}):null;if(P||F||D||V&&!H){const B=(u instanceof Error?u.message:void 0)??(p instanceof Error?p.message:void 0)??(m instanceof Error?m.message:void 0)??"An unexpected error occurred";return o.jsxs(Lt,{width:"wide",height:"full",children:[L,o.jsx(Lt.MainArea,{isCentered:!0,children:P?o.jsx(Vs,{}):F?o.jsx(Ds,{resource:"scorers"}):D?o.jsx(zi,{title:"Failed to load scorer",message:B}):o.jsx(TWr,{})})]})}return o.jsxs(Lt,{width:"wide",children:[L,o.jsx(Lt.TopArea,{children:o.jsx(NWr,{selectedEntity:i,entityOptions:j,onEntityChange:I,onReset:()=>{n(B=>{const M=new URLSearchParams(B);return M.set("entity","all"),M})},isLoading:y||f||h})}),o.jsx(jWr,{scores:v,isLoading:y,selectedScoreId:s,isFetchingNextPage:S,hasNextPage:w,setEndOfListElement:k,onScoreClick:A,errorMsg:b?.message})]})}function _as({label:e,description:t,htmlFor:n,className:r,children:s}){return o.jsxs("div",{className:K("flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",r),"data-slot":"settings-row",children:[o.jsxs("div",{children:[n?o.jsx(Rt,{htmlFor:n,className:"text-sm font-medium",children:e}):o.jsx("p",{className:"text-sm font-medium",children:e}),t&&o.jsx("p",{className:"text-sm text-neutral3",children:t})]}),s]})}const xFt=[{value:"dark",label:"Dark",Icon:Gdn},{value:"light",label:"Light",Icon:opn},{value:"system",label:"System",Icon:tct}],Cas=e=>xFt.some(t=>t.value===e);function Eas({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex min-w-0 max-w-full 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 jas=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=Xq(),{theme:r,setTheme:s}=RN();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"flex flex-col gap-5 mt-6",children:[o.jsx(age,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(_as,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(da,{value:r,onValueChange:a=>{Cas(a)&&s(a)},children:[o.jsx(pa,{id:"theme",className:"w-full sm:w-48",children:o.jsx(fa,{className:"inline-flex min-w-0 max-w-full items-center"})}),o.jsx(ha,{children:xFt.map(a=>o.jsx(Fr,{value:a.value,children:o.jsx(Eas,{option:a})},a.value))})]})})}),o.jsx(age,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(tjt,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function Tas(){const[e]=ga(),t=bs(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(uFt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}const wFt=e=>o.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 15 15",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("g",{clipPath:"url(#clip0_21999_22095)",children:o.jsx("path",{d:"M7.5 0.75C3.6325 0.75 0.5 3.8825 0.5 7.75C0.5 10.8475 2.50375 13.4637 5.28625 14.3912C5.63625 14.4525 5.7675 14.2425 5.7675 14.0587C5.7675 13.8925 5.75875 13.3412 5.75875 12.755C4 13.0787 3.545 12.3262 3.405 11.9325C3.32625 11.7312 2.985 11.11 2.6875 10.9437C2.4425 10.8125 2.0925 10.4887 2.67875 10.48C3.23 10.4712 3.62375 10.9875 3.755 11.1975C4.385 12.2562 5.39125 11.9587 5.79375 11.775C5.855 11.32 6.03875 11.0137 6.24 10.8387C4.6825 10.6637 3.055 10.06 3.055 7.3825C3.055 6.62125 3.32625 5.99125 3.7725 5.50125C3.7025 5.32625 3.4575 4.60875 3.8425 3.64625C3.8425 3.64625 4.42875 3.4625 5.7675 4.36375C6.3275 4.20625 6.9225 4.1275 7.5175 4.1275C8.1125 4.1275 8.7075 4.20625 9.2675 4.36375C10.6062 3.45375 11.1925 3.64625 11.1925 3.64625C11.5775 4.60875 11.3325 5.32625 11.2625 5.50125C11.7087 5.99125 11.98 6.6125 11.98 7.3825C11.98 10.0687 10.3438 10.6637 8.78625 10.8387C9.04 11.0575 9.25875 11.4775 9.25875 12.1337C9.25875 13.07 9.25 13.8225 9.25 14.0587C9.25 14.2425 9.38125 14.4612 9.73125 14.3912C11.1209 13.9221 12.3284 13.029 13.1839 11.8377C14.0393 10.6463 14.4996 9.21668 14.5 7.75C14.5 3.8825 11.3675 0.75 7.5 0.75Z",fill:"currentColor"})}),o.jsx("defs",{children:o.jsx("clipPath",{id:"clip0_21999_22095",children:o.jsx("rect",{width:"14",height:"14",fill:"currentColor",transform:"translate(0.5 0.75)"})})})]});function Nas(e){return e.replace(/\/$/,"").split("/").pop()}function sG({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 Ias({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:"h-16 bg-surface3 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:"w-full h-full bg-cover thumb transition-scale 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:"hidden 2xl:flex text-neutral3 text-ui-md flex-wrap items-center gap-4 mt-3",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(al,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Jp,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(nct,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(mD,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(P_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"flex items-center text-neutral3 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:"flex items-center gap-2 px-2 py-1 rounded bg-surface1 group-hover:bg-surface2 text-neutral3 transition-colors group-hover:text-neutral5",children:[o.jsx(wFt,{})," ",Nas(a.githubUrl)]})})]},a.slug)})})}function Aas({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(jT,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(wc,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(wc,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(de,{onClick:c,children:["Reset ",o.jsx(vs,{})]})]})}function Ras(){const{data:e,isLoading:t}=tXn(),{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(S=>{f.push({value:S,label:S})});const p=[{value:"all",label:"Any provider"}];(s||[]).forEach(S=>{p.push({value:S,label:S})});const h=(S,w)=>{w==="tag"?i(S):w==="provider"&&c(S)},m=S=>{d(S)},v=()=>{i("all"),c("all"),d("")},y=n.filter(S=>!(u&&!S.title.toLowerCase().includes(u)&&!S.description.toLowerCase().includes(u)||a!=="all"&&!S.tags.includes(a)||l!=="all"&&!S.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(cs,{children:[o.jsx(a0e,{children:o.jsxs(Gpt,{children:[o.jsx(Ue,{children:o.jsx(Gv,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(Aas,{selectedTag:a,onTagChange:S=>h(S,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:S=>h(S,"provider"),providerOptions:p,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(Ias,{templates:y,linkComponent:Ma,className:"max-w-[80rem] mx-auto",isLoading:t})]})]})}const Pas="1.50.1";function $as({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(Ep,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Gun,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(sG,{className:"space-y-4 text-neutral3 mb-8 content-center",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:"text-center space-y-2",children:[o.jsx("p",{className:"text-ui-md font-medium text-neutral5",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:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs overflow-auto max-h-60 text-left space-y-2",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-xs font-mono text-gray-700 dark:text-gray-300 mt-1 whitespace-pre-wrap wrap-break-word",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"cursor-pointer text-neutral3 hover:text-neutral4 select-none text-center",children:"Show Details"}),o.jsx("div",{className:"mt-4 p-3 bg-gray-100 dark:bg-gray-800 rounded text-xs font-mono overflow-auto max-h-60 text-left",children:o.jsx("div",{className:"whitespace-pre-wrap wrap-break-word",children:n})})]})]})}function Mas({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(sG,{children:o.jsxs("div",{className:"max-w-[40rem] my-4 p-4 lg:p-8 mx-auto gap-8 grid",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(rct,{})]}),o.jsx(wc,{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] gap-4 items-start",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(Gt,{})," Loading variables..."]}):Object.entries(r).map(([p,h])=>o.jsxs(g.Fragment,{children:[o.jsx(gO,{name:`env-${p}`,labelIsHidden:!0,label:"Key",value:p,disabled:!0,className:"w-full"}),o.jsx(gO,{name:p,labelIsHidden:!0,label:"Value",value:h,onChange:i,errorMsg:s.includes(p)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},p))}),o.jsxs("div",{className:"border-t border-border1 pt-12 mt-3.5 relative",children:[o.jsx("div",{className:"absolute w-8 h-8 rounded-full bg-surface2 top-0 left-1/2 -translate-x-1/2 -translate-y-4 text-ui-sm text-neutral3 flex items-center justify-center",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(p6t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(de,{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(Gt,{className:"w-4 h-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(gm,{})]})})]})})}function Das({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(Gv,{}),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 lg:grid-cols-[1fr_1fr] gap-x-24",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:"shrink-0 mt-0.5",children:o.jsx(Dx,{className:"w-[1.1em] h-[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(ube,{className:"w-[1em] h-[1em] text-neutral4"}),o.jsx("span",{className:"text-ui-md font-medium text-neutral5",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 px-1.5 py-0.5 rounded text-ui-sm 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:"flex items-center gap-2 mt-auto text-neutral3 text-ui-md hover:text-neutral5",children:[o.jsx(wFt,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Zje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Las(e){switch(e){case"running":return o.jsx(Gt,{});case"success":return o.jsx(mx,{});case"failed":return o.jsx(Fu,{});default:return null}}function Fas({stepId:e,step:t,isActive:n,position:r}){const s=a=>a.charAt(0).toUpperCase()+a.slice(1).replace(/-/g," ");return o.jsxs("div",{className:K("grid gap-6 grid-cols-[1fr_auto] py-3 px-4 rounded-lg",ms.all,{"border border-dashed border-neutral2 bg-surface3":n}),children:[o.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("text-ui-md min-w-6 flex justify-end",ms.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:[r,"."]}),o.jsxs("div",{children:[o.jsx("h4",{className:K("text-ui-md",ms.colors,{"text-neutral5":n||t.status==="success","text-neutral3":!n&&t.status!=="success"}),children:s(e)}),t.description&&o.jsx("p",{className:"text-ui-md text-neutral2 -mt-0.5",children:t.description})]})]}),o.jsx("div",{className:K("w-[1.75rem] h-[1.75rem] rounded-full flex items-center justify-center self-center",ms.all,{"border border-neutral2 border-dashed":t.status==="pending","[&>svg]:text-white [&>svg]:w-4 [&>svg]:h-4":t.status!=="running","w-[1.75rem] h-[1.75rem]":t.status==="running","bg-accent1Dark shadow-glow-accent1":t.status==="success","bg-accent2Dark shadow-glow-accent2":t.status==="failed","scale-110":t.status==="success"||t.status==="failed"}),children:Las(t.status)})]})}function zas({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(Fas,{stepId:r.id,step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function Bas({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex justify-center flex-col gap-4 content-center w-full",children:[o.jsx("div",{className:"grid grid-cols-[0_repeat(9,1fr)] w-full",children:e.map((r,s)=>o.jsx("div",{className:K("flex justify-end items-center relative h-[2rem]",ms.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("w-[2rem] h-[2rem] rounded-full flex items-center justify-center self-center absolute right-0 translate-x-[50%] bg-surface3 z-10 text-neutral3 font-bold text-ui-sm",ms.all,{"border border-neutral2 border-dashed":r.status==="pending","[&>svg]:text-surface1 [&>svg]:w-[1.1rem] [&>svg]:h-[1.1rem]":r.status!=="running","bg-accent1Dark text-white shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-white shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Gt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-xs text-neutral3 text-center",ms.colors),children:[n," of ",t," steps completed"]})]})}function Uas({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)),p=f.length,h=()=>{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(sG,{className:"space-y-6 text-neutral3 mb-8 content-center",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-lg font-semibold text-neutral5",children:h()}),(t?.runId||n)&&o.jsxs("div",{className:"mt-2 text-ui-sm text-neutral3",children:["Run ID: ",t?.runId??n]})]}),u&&p>0&&!["error"].includes(s)&&o.jsx("div",{className:"max-w-[30rem] w-full mx-auto px-6",children:o.jsx(Bas,{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(sfn,{}),l||"Something went wrong"]}),u&&o.jsx(zas,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-center text-sm text-neutral3 grid gap-4 justify-items-center",children:[o.jsx(Gt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function qas({name:e,installedEntities:t}){return o.jsxs(sG,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(rct,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-center text-neutral3 ",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(Zje,{data:t})]})}function Vas(){const{templateSlug:e}=ur(),[t,n]=ga(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,p]=g.useState([]),[h,m]=g.useState(null),[v,y]=g.useState(!1),[b,S]=g.useState(""),[w,k]=g.useState(!1),[_,C]=g.useState(!1),[j,E]=g.useState([]),{data:N,isLoading:I}=nXn({repoOrSlug:e,owner:"mastra-ai"}),P=Pas?.includes("beta")??!1?"beta":"main",{data:F,isLoading:D}=rXn({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:P}),{data:V,isLoading:H}=sXn(),{mutateAsync:L,isPending:z}=aXn(),{mutateAsync:B}=iXn(),{streamInstall:M,streamResult:G,isStreaming:q}=lXn(V),{observeInstall:$,streamResult:U,isStreaming:Z}=cXn(V);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!h&&!q&&!Z&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),S(ne),B({runId:ne}).then(ue=>{const pe=ue.snapshot;if(pe?.status==="success"&&pe?.result?.success)y(!0);else if(pe?.result?.success===!1)if(pe?.result?.validationResults&&!pe?.result?.validationResults?.valid&&pe?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ve,errors:ye}=pe.result.validationResults,Se=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Se),E(ye||[])}else{const ve=pe?.result?.message||pe?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(ue=>{console.error("❌ Failed to fetch run details:",ue),m("Failed to retrieve installation status after reload")}))},[t,v,h,q,Z,B]),g.useEffect(()=>{const ne=t.get("runId"),ue=t.get("resume"),pe=t.get("provider");if(ne&&ue==="true"&&pe&&!q&&!Z&&!w&&!_&&V){S(ne),k(!0);try{B({runId:ne}).then(oe=>{if(oe.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(oe=>{const ve=new URLSearchParams(oe);return ve.delete("resume"),ve})}).catch(oe=>{console.error("❌ Failed to resume template installation:",oe),oe.message?.includes("404")||oe.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(oe){console.error("❌ Auto-resume failed with error:",oe),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,q,Z,w,_,V,B,$,n]);const X=[{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(Jp,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(al,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(mD,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Pv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(xN,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{F&&d(F)},[F]),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 ee=ne=>{s(ne)},ae=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ce=async()=>{const ne=Object.entries(u).reduce((ue,[pe,oe])=>(oe===""&&ue.push(pe),ue),[]);if(ne.length>0){p(ne);return}if(N){m(null),y(!1),S(""),C(!0);try{const pe={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:P,slug:N.slug,variables:u},{runId:oe}=await L({});S(oe),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",oe),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await M.mutateAsync({inputData:pe,selectedModel:{provider:a,modelId:l},runId:oe})}catch(ue){C(!1),m(ue?.message||"Template installation failed"),console.error("Template installation failed",ue)}}},Y=ne=>{const{name:ue,value:pe}=ne.target;pe.trim()===""?p(oe=>[...oe,ue]):p(oe=>oe.filter(ve=>ve!==ue)),d(oe=>({...oe,[ue]:pe}))};return o.jsx(cs,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"p-6 w-full max-w-[80rem] mx-auto grid gap-y-4",children:[o.jsx(Das,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(q||Z)&&o.jsx(Uas,{name:N.title,streamResult:Z?U:G,runId:b,workflowInfo:V}),v&&o.jsx(qas,{name:N.title,installedEntities:J,linkComponent:Ma}),h&&o.jsx($as,{errorMsg:h,validationErrors:j.length>0?j:G?.validationResults?.errors||U?.validationResults?.errors}),!q&&!Z&&!v&&!h&&o.jsx(Mas,{providerOptions:X,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:p,handleInstallTemplate:ce,handleVariableChange:Y,isLoadingEnvVars:D||H,isInstalling:z,defaultModelProvider:a,defaultModelId:l,onModelUpdate:ae})]})]})})})}const Has=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(cGr,{toolId:e,agentId:t})})},Was=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(Xrs,{toolId:e})})};function Zas(){const{traceId:e}=ur(),[t,n]=ga(),r=bs(),s=t.get("spanId")||void 0,a=t.get("tab"),i=a==="scoring"?"scoring":a==="feedback"?"feedback":"details",l=t.get("scoreId")||void 0,[c,u]=g.useState(s??null),[d,f]=g.useState(),[p,h]=g.useState(i),[m,v]=g.useState(0),[y,b]=g.useState(!1),{data:S,isLoading:w,error:k}=sH(e),_=g.useMemo(()=>S?.spans??[],[S?.spans]),C=g.useMemo(()=>_.find(ae=>ae.parentSpanId==null),[_]),{data:j,isLoading:E}=HN(e,c??"");g.useEffect(()=>v(0),[e,c]);const{data:N,isLoading:I}=ih(),{data:A,isLoading:P}=I6t({traceId:e,spanId:c??void 0,page:m}),[F,D]=g.useState(0);g.useEffect(()=>D(0),[e,c]);const{data:V,isLoading:H}=J9t({traceId:e,page:F});g.useEffect(()=>{if(l&&A?.scores&&!d){const ae=A.scores.find(ce=>ce.id===l);ae&&f(ae)}},[l,A?.scores,d]);const L=g.useCallback(ae=>{const ce=new URLSearchParams(t);for(const[Y,ne]of Object.entries(ae))ne===null||ne===""?ce.delete(Y):ce.set(Y,ne);n(ce,{replace:!0})},[t,n]),z=g.useCallback(ae=>{const ce=ae??null,Y=ce===c;u(ce),Y||(f(void 0),h("details"),L({spanId:ce,tab:null,scoreId:null}))},[c,L]),B=g.useCallback(()=>{u(null),f(void 0),h("details"),L({spanId:null,tab:null,scoreId:null})},[L]),M=g.useCallback(ae=>{u(ae),f(void 0),h("details"),L({spanId:ae,tab:null,scoreId:null})},[L]),{handlePreviousSpan:G,handleNextSpan:q}=aH(_,c,M),$=g.useCallback(ae=>{const ce=ae;h(ce),f(void 0),L({tab:ce==="details"?null:ce,scoreId:null})},[L]),U=g.useCallback(ae=>{f(ae),L({scoreId:ae.id})},[L]),Z=g.useCallback(()=>{f(void 0),L({scoreId:null})},[L]),X=g.useCallback(()=>{r("/observability")},[r]),te=g.useCallback(()=>{h("scoring"),C&&c!==C.spanId?(u(C.spanId),f(void 0),L({spanId:C.spanId,tab:"scoring",scoreId:null})):L({tab:"scoring"})},[C,c,L]),J=C?o.jsx(Iy,{owner:"trace-detail",children:o.jsxs(Dr,{children:[o.jsxs(de,{tooltip:"Evaluate Trace","aria-label":"Evaluate Trace",onClick:te,children:[o.jsx(Bcn,{}),"Evaluate"]}),o.jsxs(de,{tooltip:"Save as Dataset Item","aria-label":"Save as Dataset Item",onClick:()=>b(!0),children:[o.jsx(gd,{}),"Save"]})]})}):null,ee=C?o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(U9t,{rootSpan:C,numOfCol:3})})}):null;return k?o.jsxs(Lt,{height:"full",children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(q9t,{error:k,resource:"traces",errorTitle:"Failed to load trace"})})]}):o.jsxs(Lt,{children:[J,ee&&o.jsx(Lt.TopArea,{children:ee}),o.jsx(G9t,{rootSpanId:C?.spanId,traceId:e,isOpen:y,onClose:()=>b(!1)}),o.jsxs("div",{className:K("grid h-full min-h-0 gap-4 overflow-hidden items-start mt-4",c?"grid-cols-[2fr_3fr]":"grid-cols-[1fr]"),children:[o.jsx(gTe,{traceId:e,spans:_,isLoading:w,onClose:X,onSpanSelect:z,onEvaluateTrace:te,initialSpanId:c,placement:"trace-page",timelineChartWidth:c?"default":"wide"}),c&&!w&&o.jsxs("div",{className:K("grid gap-4 max-h-full min-h-0 overflow-auto",d?"grid-rows-[1fr_1fr]":"grid-rows-[1fr]"),children:[o.jsx(rH,{traceId:e,spanId:c,span:j?.span,isLoading:E,onClose:B,onPrevious:G,onNext:q,activeTab:p,onTabChange:$,feedbackTabBadge:V?.pagination?.total??void 0,feedbackTabSlot:()=>o.jsx(Y9t,{feedbackData:V,onPageChange:D,isLoadingFeedbackData:H}),scoringTabBadge:A?.pagination?.total??void 0,scoringTabSlot:({span:ae,traceId:ce,spanId:Y})=>o.jsxs("div",{className:"grid gap-6",children:[o.jsx(K9t,{traceId:ce,isTopLevelSpan:!ae.parentSpanId,spanId:Y,entityType:ae.attributes?.agentId||ae.entityType===Os.AGENT?"Agent":ae.attributes?.workflowId||ae.entityType===Os.WORKFLOW_RUN?"Workflow":void 0,scorers:N,isLoadingScorers:I}),o.jsx(X9t,{scoresData:A,onPageChange:v,isLoadingScoresData:P,onScoreSelect:U})]})}),d&&o.jsx(Wje,{score:d,onClose:Z})]})]})]})}function Gas(){const{data:e,isLoading:t,error:n}=zy(),[r,s]=g.useState("");return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"workflows"})}):n?o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(lr,{children:o.jsx(x3r,{})}):o.jsxs(Lt,{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(jf,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(de,{as:Ma,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(fD,{}),"Schedules"]})]})}),o.jsx(b3r,{workflows:e||{},isLoading:t,search:r})]})}const Qas={active:"bg-accent1",paused:"bg-accent3"},Yas={active:"text-accent1",paused:"text-accent3"},SFt=({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 ${Qas[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Yas[e]}`,children:e})]}),Dj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),cP=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 kFt({status:e}){const{icon:t,color:n}=Xas(e);return o.jsxs("span",{className:`inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function Xas(e){switch(e){case"success":return{icon:o.jsx(ea,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(vs,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Gt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(lq,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Of,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(Gj,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const nYe="auto auto auto auto 1fr";function Kas(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 Jas(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 eis=3e4,tis=5*6e4;function nis({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=yn();return t?o.jsx(nl,{columns:nYe}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(me,{columns:nYe,className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Run"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Started"}),o.jsx(me.TopCell,{children:"Duration"}),o.jsx(me.TopCell,{children:" "})]}),e.map(c=>{const u=c.actualFireAt-c.scheduledFireAt,d=Jas(u),f=`Scheduled ${Dj(c.scheduledFireAt)} — published ${Dj(c.actualFireAt)} (drift ${d})`,p=c.outcome==="failed",h=p?c.error:c.run?.error,m=Math.abs(u),v=!p&&m>eis&&m<=tis,y=`${c.scheduleId}-${c.runId}-${c.actualFireAt}`,b=!!(n&&c.runId&&!p),S=o.jsx("span",{className:b?"text-accent1 font-mono text-ui-sm whitespace-nowrap":"text-neutral3 font-mono text-ui-sm whitespace-nowrap",children:c.runId}),w=o.jsxs(o.Fragment,{children:[o.jsx(me.Cell,{height:"compact",children:S}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[p?o.jsxs("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-accent2",children:[o.jsx(Ep,{size:14}),"publish failed"]}):c.run?o.jsx(kFt,{status:c.run.status}):o.jsx("span",{className:"inline-flex items-center gap-1.5 whitespace-nowrap text-ui-sm text-neutral3",children:"pending"}),h?o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Ep,{size:14})})}),o.jsx(Ln,{children:h})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:f,children:cP(c.actualFireAt)}),v?o.jsxs(Un,{children:[o.jsx(Dn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Ep,{size:14})})}),o.jsxs(Ln,{children:["Published ",d," after the scheduled fire time"]})]}):null]})}),o.jsx(me.Cell,{height:"compact",children:c.run?o.jsx("span",{children:Kas(c.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(me.Cell,{height:"compact",children:" "})]});return b?o.jsx(me.RowLink,{to:l.workflowRunLink(n,c.runId),LinkComponent:i,children:w},y):o.jsx(me.RowStatic,{children:w},y)}),o.jsx(me.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const ris=e=>{const t=We();return St({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},rYe=25,sis=e=>{const t=We(),{inView:n,setRef:r}=N_(),s=P1({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:rYe,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<rYe))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(p=>p.triggers)??[]).some(p=>p.run?p.run.status==="pending"||p.run.status==="running"||p.run.status==="waiting":p.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}},ais=e=>{const t=We(),n=Br();return Rn({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"]}),De.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{De.error(r.message)}})};function dF({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 uppercase tracking-wide",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function iis(){const{scheduleId:e}=ur(),{paths:t}=yn(),{data:n,error:r}=ris(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=sis(e),d=ais(e);if(r&&gs(r))return o.jsx(lr,{children:o.jsx(Vs,{})});if(r&&ys(r))return o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})});if(r)return o.jsx(lr,{children:o.jsx(zi,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,p=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(de,{as:Ma,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(Tc,{}),"Back to schedules"]}),f?o.jsx(de,{as:Ma,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(de,{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(sct,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Lp,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid gap-6 h-full overflow-hidden grid-cols-[minmax(0,20rem)_1fr]",children:[o.jsxs("div",{className:"flex flex-col gap-4 border border-border1 rounded-md p-4 h-fit",children:[o.jsx(dF,{label:p?"Agent":"Workflow",children:f?o.jsx(Ma,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):p?o.jsx(Ma,{to:t.agentLink(p),className:"text-accent1 hover:underline",children:p}):"—"}),o.jsxs(dF,{label:"Cron",children:[o.jsx("code",{className:"font-mono text-ui-md",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 ml-2 text-ui-sm",children:n.timezone}):null]}),o.jsx(dF,{label:"Status",children:o.jsx(SFt,{status:n.status})}),o.jsx(dF,{label:"Next fire",children:o.jsx("span",{title:Dj(n.nextFireAt),children:cP(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(zi,{title:"Failed to load trigger history",message:i.message}):o.jsx(nis,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const sYe="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function ois({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=yn(),a=g.useMemo(()=>{const i=n.toLowerCase();return i?e.filter(l=>l.id.toLowerCase().includes(i)||(l.workflowId??l.agentId??"").toLowerCase().includes(i)):e},[e,n]);return t?o.jsx(nl,{columns:sYe}):o.jsxs(me,{columns:sYe,variant:"striped",className:"min-w-0",children:[o.jsxs(me.Top,{children:[o.jsx(me.TopCell,{children:"Target"}),o.jsx(me.TopCell,{children:"Schedule ID"}),o.jsx(me.TopCell,{children:"Cron"}),o.jsx(me.TopCell,{children:"Status"}),o.jsx(me.TopCell,{children:"Next fire"}),o.jsx(me.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(me.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(me.NoMatch,{message:"No schedules configured"}):null,a.map(i=>o.jsxs(me.RowLink,{to:r.scheduleLink(i.id),LinkComponent:s,children:[o.jsx(me.NameCell,{children:i.workflowId??i.agentId}),o.jsx(me.Cell,{height:"compact",className:"min-w-0",children:o.jsx("span",{className:"block truncate font-mono text-ui-smd text-neutral3",title:i.id,children:i.id})}),o.jsx(me.Cell,{height:"compact",children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"font-mono text-ui-sm",children:i.cron}),i.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:i.timezone}):null]})}),o.jsx(me.Cell,{height:"compact",children:o.jsx(SFt,{status:i.status})}),o.jsx(me.Cell,{height:"compact",children:o.jsx("span",{className:"whitespace-nowrap",title:Dj(i.nextFireAt),children:cP(i.nextFireAt)})}),o.jsx(me.Cell,{height:"compact",children:i.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(kFt,{status:i.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Dj(i.lastFireAt),children:i.lastFireAt?cP(i.lastFireAt):""})]}):i.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Dj(i.lastFireAt),children:cP(i.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},i.id))]})}function lis({workflowId:e}={}){const{data:t,isLoading:n,error:r}=r0e(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(zi,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid grid-rows-[auto_1fr] gap-4 h-full overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(jf,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(ois,{schedules:t??[],isLoading:n,search:s})})]})}function cis(){const[e]=ga(),t=e.get("workflowId")??void 0,{error:n}=r0e(t?{workflowId:t}:{});return n&&gs(n)?o.jsx(lr,{children:o.jsx(Vs,{})}):n&&ys(n)?o.jsx(lr,{children:o.jsx(Ds,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(lis,{workflowId:t})})})}function uis({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=$1e({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=Ewt(r),[d]=jwt(s),{edgeTypes:f,nodeTypes:p,styledEdges:h}=sPt({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:"w-full h-full relative bg-surface1",children:a?o.jsxs(Cwt,{nodes:l,edges:h,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:p,onNodesChange:u,children:[o.jsx(K_e,{position:"bottom-left"}),o.jsx(Nwt,{variant:ty.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"w-full h-full flex items-center justify-center",children:o.jsx(Gt,{})})})}function dis(){const{stepDetail:e,closeStepDetail:t}=ZV();return e?o.jsxs("div",{className:"flex flex-col h-full","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border1 bg-surface1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(afe,{className:"w-4 h-4",style:{color:Cu.map}}),e.type==="nested-graph"&&o.jsx(jd,{className:"w-4 h-4",style:{color:Cu.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:"p-1 hover:bg-surface3 rounded transition-colors","aria-label":"Close",children:o.jsx(vs,{className:"w-4 h-4 text-neutral3"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(sP,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(P1e,{children:o.jsx(uis,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function fis(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function pis(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 his({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"space-y-5 rounded-lg border border-border1 bg-surface4 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:"flex items-center gap-2 text-neutral6 font-semibold",children:[o.jsx(Ue,{children:o.jsx(lq,{})}),"Step suspended"]}),o.jsx(dn,{variant:"warning",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?cm(om(gx(i.resumeSchema))):op(dr(),lT());return o.jsx(mis,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function mis({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 font-medium truncate",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:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Ydn,{})}),"The step is asking"]}),o.jsxs(xf,{open:a,onOpenChange:i,children:[o.jsxs(Od,{className:"flex w-full items-center justify-between gap-2 rounded-lg border border-border1 bg-surface3 px-3 py-2.5",children:[o.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[o.jsx(Ue,{children:o.jsx(la,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:pis(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:fis(e.suspendPayload)})]}),o.jsx(_d,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Yr,{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:"flex items-center gap-2 text-neutral3",children:[o.jsx(Ue,{children:o.jsx(Jdn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(B7,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Lp,{}),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 gis(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext($l),{runId:a}=ur(),i=Dwt(e,r??""),l=yGn(),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:"absolute top-2 right-2 z-20 w-[380px] max-w-[calc(100%-1rem)] max-h-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 duration-300",children:o.jsx(his,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const vis=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"})]}),yis=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"})]}),bis=e=>e.includes("."),xis=e=>e==="input"||e.endsWith(".input"),wis=1;function Sis(e){return`${Number((e/1e3).toPrecision(3))}s`}function kis(e,t){const n=Object.entries(e).filter(([i])=>!xis(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,p=Math.max(d/a*100,wis);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:p,durationMs:d,isRunning:c,isNestedEntry:bis(i)}})}const Ois=({status:e})=>o.jsxs(Ue,{children:[e==="success"&&o.jsx(vis,{className:"text-accent1"}),e==="failed"&&o.jsx(yis,{className:"text-accent2"}),e==="suspended"&&o.jsx(lq,{className:"text-accent3"}),e==="waiting"&&o.jsx(sfe,{className:"text-accent5"}),e==="skipped"&&o.jsx(sfe,{className:"text-icon3"}),e==="running"&&o.jsx(Ks,{className:"text-accent6 animate-spin"})]}),_is={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function OFt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const aYe=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},Cis=e=>{const t=e;return Q2t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},Eis=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=Cis(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(Ois,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(de,{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(tpn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(hU,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"block min-w-0 max-w-full justify-self-stretch overflow-hidden text-ellipsis whitespace-nowrap text-left text-neutral6",children:OFt(e.stepId)}),o.jsx("div",{className:"relative h-2 min-w-0 rounded bg-surface4",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 ${_is[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(de,{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(Jfn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"w-20 justify-self-end text-right text-neutral3 tabular-nums",children:Sis(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function jis(){const{steps:e}=u4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=sV(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);d0e(f,{enabled:!l});const p=kis(e,a),h=p.some(m=>m.isRunning);return g.useEffect(()=>{if(!h)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[h]),g.useEffect(()=>{if(l||p.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,p.length]),p.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:"pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden rounded-studio-panel border border-border1/50 bg-surface3 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:"rounded-md p-1 text-neutral3 transition-colors hover:bg-surface4 hover:text-neutral6",children:o.jsx(Aa,{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:p.map((m,v)=>o.jsx(Eis,{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:aYe(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:aYe(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(br,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(Fwt,{data:u.data,title:`${OFt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const Tis=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=ZV();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(fPt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(gis,{}),o.jsx(jis,{})]})}),r&&o.jsx("div",{className:"w-[420px] min-h-0 overflow-hidden border-l border-border1",children:o.jsx(dis,{})})]})},iYe=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=w3(e);return r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vs,{})}):r&&ys(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ds,{resource:"workflows"})}):o.jsx(K1e,{children:o.jsx(Tis,{workflowId:e,workflow:t??void 0,isLoading:n})})};function Nis(e,t){if(e==null)return{};var n,r,s=qbt(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 eye(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 Iis(e){if(Array.isArray(e))return eye(e)}function Ais(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Ris(e,t){if(e){if(typeof e=="string")return eye(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)?eye(e,t):void 0}}function Pis(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
729
729
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tye(e){return Iis(e)||Ais(e)||Ris(e)||Pis()}function tD(e){"@babel/helpers - typeof";return tD=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},tD(e)}function $is(e,t){if(tD(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(tD(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Mis(e){var t=$is(e,"string");return tD(t)=="symbol"?t:t+""}function _Ft(e,t,n){return(t=Mis(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function oYe(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 nj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?oYe(Object(n),!0).forEach(function(r){_Ft(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):oYe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function Dis(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 vse={};function Lis(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return vse[t]||(vse[t]=Dis(e)),vse[t]}function Fis(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=Lis(r);return s.reduce(function(a,i){return nj(nj({},a),n[i])},t)}function lYe(e){return e.join(" ")}function zis(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return CFt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function CFt(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=zis(n,a),p;if(!a)p=nj(nj({},l),{},{className:lYe(l.className)});else{var h=Object.keys(n).reduce(function(b,S){return S.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!h.includes(b)}));p=nj(nj({},l),{},{className:lYe(v)||void 0,style:Fis(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return Le.createElement(u,AO({key:i},p),y)}}const Bis=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var Uis=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function cYe(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 kw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?cYe(Object(n),!0).forEach(function(r){_Ft(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):cYe(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var qis=/\n/g;function Vis(e){return e.match(qis)}function His(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return Le.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
730
730
|
`))})}function Wis(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 Le.createElement("code",{style:Object.assign({},n,s)},His({lines:t.replace(/\n$/,"").split(`
|
|
731
731
|
`),style:i,startingLineNumber:l}))}function Zis(e){return"".concat(e.toString().length,".25em")}function EFt(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 jFt(e,t,n){var r={display:"inline-block",minWidth:Zis(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=kw(kw({},r),s);return a}function j8(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,p=e.wrapLines,h=p===void 0?!1:p,m=h?kw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(tye(m.className.trim().split(/\s+/)),tye(u)):u,n&&a){var v=jFt(r,n,s);t.unshift(EFt(n,v))}return f&d&&(m.style=kw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function TFt(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(j8({children:[s],className:tye(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);TFt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function Gis(e,t,n,r,s,a,i,l,c){var u,d=TFt(e.value),f=[],p=-1,h=0;function m(_,C){var j=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return j8({children:_,lineNumber:C,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:j,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(_,C){if(r&&C&&s){var j=jFt(l,C,i);_.unshift(EFt(C,j))}return _}function y(_,C){var j=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||j.length>0?m(_,C,j):v(_,C)}for(var b=function(){var C=d[h],j=C.children[0].value,E=Vis(j);if(E){var N=j.split(`
|