next-workflow-builder 0.7.4 → 0.7.6
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 +25 -0
- package/dist/chunk-4FVH6K2Q.js +1 -0
- package/dist/{chunk-CI7FTYZR.js → chunk-MG2CZJRC.js} +1 -1
- package/dist/client/index.js +70 -80
- package/dist/{handler-67JKCHM5.js → handler-77P4SE7Q.js} +1 -1
- package/dist/merge-LQKF2JKM.js +1 -0
- package/dist/{run-workflow-VFZV5YLI.js → run-workflow-EAXBE7Z5.js} +1 -1
- package/dist/{run-workflows-in-sequence-3APONBOX.js → run-workflows-in-sequence-X4A77MVY.js} +1 -1
- package/dist/server/api/index.js +7 -7
- package/dist/styles.css +16 -1
- package/dist/switch-V4UFKFL5.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-WT4BSMUD.js +0 -1
- package/dist/merge-HYBHX22D.js +0 -1
- package/dist/switch-ZPVREROE.js +0 -1
package/dist/client/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use client";import{a as
|
|
2
|
-
`);n.buffer=r.pop()||"";for(let s of r)Kc(s,o,n)}var jc={generate:(e,t)=>ge("/api/ai/generate",{method:"POST",body:JSON.stringify({prompt:e,existingWorkflow:t})}),generateStream:async(e,t,o)=>{let n=await fetch("/api/ai/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e,existingWorkflow:o})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("No response body");let r=n.body.getReader(),s=new TextDecoder,a={buffer:"",currentData:o?{nodes:o.nodes||[],edges:o.edges||[],name:o.name}:{nodes:[],edges:[]}};try{for(;;){let{done:d,value:i}=await r.read();if(d)break;qc(i,s,t,a)}return a.currentData}finally{r.releaseLock()}}},Jc={getAll:e=>ge(`/api/integrations${e?`?type=${e}`:""}`),get:e=>ge(`/api/integrations/${e}`),create:e=>ge("/api/integrations",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ge(`/api/integrations/${e}`,{method:"PUT",body:JSON.stringify(t)}),delete:e=>ge(`/api/integrations/${e}`,{method:"DELETE"}),testConnection:e=>ge(`/api/integrations/${e}/test`,{method:"POST"}),testCredentials:e=>ge("/api/integrations/test",{method:"POST",body:JSON.stringify(e)})},Yc={get:()=>ge("/api/user"),update:e=>ge("/api/user",{method:"PATCH",body:JSON.stringify(e)})},mr={getAll:()=>ge("/api/workflows"),getById:e=>ge(`/api/workflows/${e}`),create:e=>ge("/api/workflows/create",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ge(`/api/workflows/${e}`,{method:"PATCH",body:JSON.stringify(t)}),delete:e=>ge(`/api/workflows/${e}`,{method:"DELETE"}),duplicate:e=>ge(`/api/workflows/${e}/duplicate`,{method:"POST"}),getCurrent:()=>ge("/api/workflows/current"),saveCurrent:(e,t)=>ge("/api/workflows/current",{method:"POST",body:JSON.stringify({nodes:e,edges:t})}),execute:(e,t={})=>ge(`/api/workflow/${e}/execute`,{method:"POST",body:JSON.stringify({input:t})}),triggerWebhook:(e,t={})=>ge(`/api/workflows/${e}/webhook`,{method:"POST",body:JSON.stringify(t)}),getCode:e=>ge(`/api/workflows/${e}/code`),getExecutions:e=>ge(`/api/workflows/${e}/executions`),deleteExecutions:e=>ge(`/api/workflows/${e}/executions`,{method:"DELETE"}),getExecutionLogs:e=>ge(`/api/workflows/executions/${e}/logs`),getExecutionStatus:e=>ge(`/api/workflows/executions/${e}/status`),cancelExecution:e=>ge(`/api/workflows/executions/${e}/cancel`,{method:"POST"}),download:e=>ge(`/api/workflows/${e}/download`),autoSaveCurrent:(()=>{let e=null,t=2e3;return(o,n)=>{e&&clearTimeout(e),e=setTimeout(()=>{mr.saveCurrent(o,n).catch(r=>{console.error("Auto-save failed:",r)})},t)}})(),autoSaveWorkflow:(()=>{let e=null,t=2e3;return(o,n,r=!0)=>{if(!r)return mr.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{mr.update(o,n).catch(s=>{console.error("Auto-save failed:",s)})},t)}})()},Xc={getStatus:()=>ge("/api/ai-gateway/status"),getTeams:()=>ge("/api/ai-gateway/teams"),consent:(e,t)=>ge("/api/ai-gateway/consent",{method:"POST",body:JSON.stringify({teamId:e,teamName:t})}),revokeConsent:()=>ge("/api/ai-gateway/consent",{method:"DELETE"})},q={ai:jc,aiGateway:Xc,integration:Jc,user:Yc,workflow:mr};import{atom as Fn}from"jotai";var ft=Fn([]),pr=Fn(!1),lh=Fn(null),Rt=Fn(0),ei=Fn(e=>{let t=e(ft);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as Qc,applyNodeChanges as Zc}from"@xyflow/react";import{atom as ae}from"jotai";var ne=ae([]),ue=ae([]),ke=ae(null),_e=ae(null),ni=ae(!1),ti=ae(!1),Nt=ae(!1),Ue=ae(null),gt=ae(""),fr=ae("private"),oo=ae(!0),jo=ae({snapToGrid:!0,edgeStyle:"smoothstep"}),Bt=ae("properties"),gr=ae(!1),no=ae(null),yr=ae(null),vr=ae(!1),hr=ae(!1),ri=ae(!1),br=ae(!1),wr=ae(new Set),to=ae(null),xr=ae(!1),Jo=ae({}),Aa=null,eu=1e3,Wt=ae(null,async(e,t,o)=>{let n=e(Ue),r=e(ne),s=e(ue);if(!n)return;let a=async()=>{try{await q.workflow.update(n,{nodes:r,edges:s}),t(nt,!1)}catch(d){console.error("Autosave failed:",d)}};o?.immediate?await a():(Aa&&clearTimeout(Aa),Aa=setTimeout(a,eu))}),ai=ae(null,(e,t,o)=>{let n=e(ne),r=o.filter(l=>l.type==="remove"?n.find(u=>u.id===l.id)?.data.type!=="trigger":!0),s=Zc(r,n);t(ne,s);let a=s.find(l=>l.selected);if(a){t(ke,a.id),t(_e,null);let l=e(to);l&&l!==a.id&&t(to,null)}else if(e(ke)){let l=e(ke);s.find(u=>u.id===l)||t(ke,null),t(to,null)}if(r.some(l=>l.type==="remove")){t(Wt,{immediate:!0});return}r.some(l=>l.type==="position"&&l.dragging===!1)&&t(Wt)}),si=ae(null,(e,t,o)=>{let n=e(ue),r=Qc(o,n);t(ue,r);let s=r.find(d=>d.selected);if(s)t(_e,s.id),t(ke,null);else if(e(_e)){let d=e(_e);r.find(l=>l.id===d)||t(_e,null)}o.some(d=>d.type==="remove")&&t(Wt,{immediate:!0})}),Yo=ae(null,(e,t,o)=>{let n=e(ne),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]),t(zt,[]);let a=n.map(l=>({...l,selected:!1})),d={...o,selected:!0},i=[...a,d];t(ne,i),t(ke,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(to,o.id),t(nt,!0),t(Wt,{immediate:!0})}),ro=ae(null,(e,t,{id:o,data:n})=>{let r=e(ne),a=r.find(c=>c.id===o)?.data.label,d=n.label,i=d!==void 0&&a!==d,l=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(i&&a){let u=ii(c.data.config||{},o,a,d);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(ne,l),n.status||(t(nt,!0),t(Wt))});function ii(e,t,o,n){let r=!1,s={};for(let[a,d]of Object.entries(e))if(typeof d=="string"){let i=new RegExp(`\\{\\{@${oi(t)}:${oi(o)}(\\.[^}]+)?\\}\\}`,"g"),l=d.replace(i,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));s[a]=l}else if(typeof d=="object"&&d!==null&&!Array.isArray(d)){let i=ii(d,t,o,n);i!==d&&(r=!0),s[a]=i}else s[a]=d;return r?s:e}function oi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var ao=ae(null,(e,t,o)=>{let n=e(ne);if(n.find(l=>l.id===o)?.data.type==="trigger")return;let s=e(ue),a=e(ot);t(ot,[...a,{nodes:n,edges:s}]),t(zt,[]);let d=n.filter(l=>l.id!==o),i=s.filter(l=>l.source!==o&&l.target!==o);t(ne,d),t(ue,i),e(ke)===o&&t(ke,null),t(nt,!0),t(Wt,{immediate:!0})}),so=ae(null,(e,t,o)=>{let n=e(ne),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]),t(zt,[]);let a=r.filter(d=>d.id!==o);t(ue,a),e(_e)===o&&t(_e,null),t(nt,!0),t(Wt,{immediate:!0})}),li=ae(null,(e,t)=>{let o=e(ne),n=e(ue),r=e(ot);t(ot,[...r,{nodes:o,edges:n}]),t(zt,[]);let s=o.filter(i=>i.selected&&i.data.type!=="trigger").map(i=>i.id),a=o.filter(i=>i.data.type==="trigger"?!0:!i.selected),d=n.filter(i=>!(i.selected||s.includes(i.source)||s.includes(i.target)));t(ne,a),t(ue,d),t(ke,null),t(_e,null),t(nt,!0),t(Wt,{immediate:!0})}),Nr=ae(null,(e,t)=>{let o=e(ne),n=e(ue),r=e(ot);t(ot,[...r,{nodes:o,edges:n}]),t(zt,[]),t(ne,[]),t(ue,[]),t(ke,null),t(_e,null),t(nt,!0)}),ph=ae(null,async(e,t)=>{try{t(ti,!0);let o=await q.workflow.getCurrent();t(ne,o.nodes),t(ue,o.edges),o.id&&t(Ue,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t(ti,!1)}}),fh=ae(null,async(e,t,{name:o,description:n})=>{let r=e(ne),s=e(ue);try{return await q.workflow.create({name:o,description:n,nodes:r,edges:s})}catch(a){throw console.error("Failed to save workflow:",a),a}}),di=ae(!1),ci=ae(!1),kr=ae(!1),nt=ae(!1),ui=ae(!1),ot=ae([]),zt=ae([]),mi=ae(null,(e,t)=>{let o=e(ot);if(o.length===0)return;let n=e(ne),r=e(ue),s=e(zt);t(zt,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(ot,a),t(ne,d.nodes),t(ue,d.edges),t(nt,!0))}),pi=ae(null,(e,t)=>{let o=e(zt);if(o.length===0)return;let n=e(ne),r=e(ue),s=e(ot);t(ot,[...s,{nodes:n,edges:r}]);let a=[...o],d=a.pop();d&&(t(zt,a),t(ne,d.nodes),t(ue,d.edges),t(nt,!0))}),fi=ae(e=>e(ot).length>0),gi=ae(e=>e(zt).length>0),Cr=ae(null,(e,t)=>{let n=e(ne).map(r=>({...r,data:{...r.data,status:"idle"}}));t(ne,n)});import*as Tr from"react";var Sa=768;function Vt(){let[e,t]=Tr.useState(void 0);return Tr.useEffect(()=>{let o=window.matchMedia(`(max-width: ${Sa-1}px)`),n=()=>{t(window.innerWidth<Sa)};return o.addEventListener("change",n),t(window.innerWidth<Sa),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as tu}from"radix-ui";import{cva as ou}from"class-variance-authority";import{jsx as nu}from"react/jsx-runtime";var Ar=ou("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function D({className:e,variant:t,size:o,asChild:n=!1,...r}){let s=n?tu.Slot:"button";return nu(s,{"data-slot":"button",className:x(Ar({variant:t,size:o,className:e})),...r})}var ru={"Database Query":"database"};function au(e){return fe(e)?.integration||ru[e]}function yi(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=au(n);if(!r)return null;let s=e.data.config?.integrationId;if(s&&o.has(s))return null;let d=t.filter(i=>i.type===r);return d.length===1?{nodeId:e.id,newIntegrationId:d[0].id}:d.length===0&&s?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as po,useAtomValue as as,useSetAtom as fo}from"jotai";import{Copy as Wl,Eraser as ss,Eye as ef,EyeOff as tf,FileCode as zl,RefreshCw as Bl,Trash2 as oa}from"lucide-react";import{useCallback as of,useEffect as Vl,useMemo as nf,useRef as Gl,useState as Xn}from"react";import{toast as ta}from"sonner";import{AlertDialog as io}from"radix-ui";import{jsx as Ot,jsxs as lu}from"react/jsx-runtime";function Xo({...e}){return Ot(io.Root,{"data-slot":"alert-dialog",...e})}function su({...e}){return Ot(io.Portal,{"data-slot":"alert-dialog-portal",...e})}function iu({className:e,...t}){return Ot(io.Overlay,{"data-slot":"alert-dialog-overlay",className:x("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Qo({className:e,...t}){return lu(su,{children:[Ot(iu,{}),Ot(io.Content,{"data-slot":"alert-dialog-content",className:x("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function Zo({className:e,...t}){return Ot("div",{"data-slot":"alert-dialog-header",className:x("flex flex-col gap-2 text-center sm:text-left",e),...t})}function en({className:e,...t}){return Ot("div",{"data-slot":"alert-dialog-footer",className:x("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function tn({className:e,...t}){return Ot(io.Title,{"data-slot":"alert-dialog-title",className:x("text-lg font-semibold",e),...t})}function on({className:e,...t}){return Ot(io.Description,{"data-slot":"alert-dialog-description",className:x("text-muted-foreground text-sm",e),...t})}function nn({className:e,...t}){return Ot(io.Action,{className:x(Ar(),e),...t})}function rn({className:e,...t}){return Ot(io.Cancel,{className:x(Ar({variant:"outline"}),e),...t})}import du from"@monaco-editor/react";import{useTheme as cu}from"next-themes";var vi={base:"vs-dark",inherit:!0,rules:[{token:"",foreground:"ededed"},{token:"comment",foreground:"a1a1a1",fontStyle:"italic"},{token:"keyword",foreground:"ff4d8d"},{token:"keyword.operator",foreground:"ff4d8d"},{token:"string",foreground:"00ca50"},{token:"string.escape",foreground:"00ca50"},{token:"number",foreground:"ffffff"},{token:"type",foreground:"47a8ff"},{token:"type.identifier",foreground:"47a8ff"},{token:"identifier",foreground:"ededed"},{token:"parameter",foreground:"ededed"},{token:"variable",foreground:"ededed"},{token:"variable.parameter",foreground:"ededed"},{token:"function",foreground:"c472fb"},{token:"identifier.function",foreground:"c472fb"},{token:"member.function",foreground:"c472fb"},{token:"constant.language",foreground:"47a8ff"},{token:"keyword.json",foreground:"47a8ff"},{token:"variable.predefined",foreground:"ededed"},{token:"support.variable",foreground:"ededed"},{token:"support.constant",foreground:"ededed"},{token:"delimiter",foreground:"ededed"},{token:"delimiter.bracket",foreground:"ededed"},{token:"delimiter.parenthesis",foreground:"ededed"},{token:"delimiter.curly",foreground:"ededed"},{token:"delimiter.array",foreground:"ededed"},{token:"punctuation",foreground:"ededed"},{token:"operator",foreground:"ededed"},{token:"string.key.json",foreground:"47a8ff"},{token:"string.value.json",foreground:"00ca50"},{token:"number.json",foreground:"ffffff"},{token:"keyword.json",foreground:"47a8ff"}],colors:{"editor.background":"#000000","editor.foreground":"#ededed","editorLineNumber.foreground":"#444444","editorLineNumber.activeForeground":"#888888","editor.lineHighlightBackground":"#0A0A0A","editor.selectionBackground":"#264F78","editor.inactiveSelectionBackground":"#1A1A1A","editorCursor.foreground":"#FFFFFF","editorWhitespace.foreground":"#333333","editorIndentGuide.background":"#1A1A1A","editorIndentGuide.activeBackground":"#333333","editorBracketMatch.background":"#0A0A0A","editorBracketMatch.border":"#444444"}};import{jsx as uu}from"react/jsx-runtime";function yt(e){let{resolvedTheme:t}=cu();return uu(du,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",vi),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as mu}from"react/jsx-runtime";function se({className:e,type:t,...o}){return mu("input",{type:t,"data-slot":"input",className:x("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent border-input h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...o})}import{Label as pu}from"radix-ui";import{jsx as fu}from"react/jsx-runtime";function M({className:e,...t}){return fu(pu.Root,{"data-slot":"label",className:x("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}import{Tabs as Sr}from"radix-ui";import{jsx as Ir}from"react/jsx-runtime";function Ia({className:e,...t}){return Ir(Sr.Root,{"data-slot":"tabs",className:x("flex flex-col gap-2",e),...t})}function Pa({className:e,...t}){return Ir(Sr.List,{"data-slot":"tabs-list",className:x("bg-muted text-muted-foreground inline-flex h-10 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function No({className:e,...t}){return Ir(Sr.Trigger,{"data-slot":"tabs-trigger",className:x("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function ko({className:e,...t}){return Ir(Sr.Content,{"data-slot":"tabs-content",className:x("flex-1 outline-none",e),...t})}import{useAtomValue as ul,useSetAtom as Km}from"jotai";import{HelpCircle as qm,Plus as jm,Settings as Jm}from"lucide-react";import{useEffect as Ym,useMemo as Hr,useState as Xm}from"react";import{Select as rt}from"radix-ui";import{CheckIcon as gu,ChevronDownIcon as hi,ChevronUpIcon as yu}from"lucide-react";import{jsx as Be,jsxs as Ea}from"react/jsx-runtime";function ve({...e}){return Be(rt.Root,{"data-slot":"select",...e})}function bi({...e}){return Be(rt.Group,{"data-slot":"select-group",...e})}function we({...e}){return Be(rt.Value,{"data-slot":"select-value",...e})}function he({className:e,size:t="default",children:o,...n}){return Ea(rt.Trigger,{"data-slot":"select-trigger","data-size":t,className:x("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-transparent hover:bg-accent/50 flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,Be(rt.Icon,{asChild:!0,children:Be(hi,{className:"size-4 opacity-50"})})]})}function be({className:e,children:t,position:o="popper",align:n="center",...r}){return Be(rt.Portal,{children:Ea(rt.Content,{"data-slot":"select-content",className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",o==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:o,align:n,...r,children:[Be(vu,{}),Be(rt.Viewport,{className:x("p-1",o==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),Be(hu,{})]})})}function wi({className:e,...t}){return Be(rt.Label,{"data-slot":"select-label",className:x("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function te({className:e,children:t,...o}){return Ea(rt.Item,{"data-slot":"select-item",className:x("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...o,children:[Be("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:Be(rt.ItemIndicator,{children:Be(gu,{className:"size-4"})})}),Be(rt.ItemText,{children:t})]})}function Pr({className:e,...t}){return Be(rt.Separator,{"data-slot":"select-separator",className:x("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function vu({className:e,...t}){return Be(rt.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:Be(yu,{className:"size-4"})})}function hu({className:e,...t}){return Be(rt.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:Be(hi,{className:"size-4"})})}import{useAtom as ki}from"jotai";import{useEffect as Da,useRef as Ra,useState as an}from"react";import{useAtom as xi}from"jotai";import{Check as bu}from"lucide-react";import{useEffect as Er,useRef as wu,useState as Ni}from"react";import{createPortal as xu}from"react-dom";import{Fragment as Tu,jsx as Wn,jsxs as Dr}from"react/jsx-runtime";var Nu=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=fe(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},zn=(e,t="")=>{let o=[];for(let n of e){let r=t?`${t}.${n.name}`:n.name,s=n.type==="array"?`${n.itemType}[]`:n.type,a=n.description||`${s}`;if(o.push({field:r,description:a}),n.type==="object"&&n.fields&&n.fields.length>0&&o.push(...zn(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let d=`${r}[0]`;o.push(...zn(n.fields,d))}}return o},ku=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,Cu=e=>{let t=e.data.config?.actionType;if(t==="HTTP Request")return[{field:"data",description:"Response data"},{field:"status",description:"HTTP status code"}];if(t==="Database Query"){let o=e.data.config?.dbSchema;if(o)try{let n=JSON.parse(o);if(n.length>0)return zn(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(ku(t,"Generate Text","ai-gateway/generate-text")){let o=e.data.config?.aiFormat,n=e.data.config?.aiSchema;if(o==="object"&&n)try{let r=JSON.parse(n);if(r.length>0)return zn(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=fe(t);if(o?.outputFields&&o.outputFields.length>0)return o.outputFields}if(e.data.type==="trigger"){let o=e.data.config?.triggerType,n=e.data.config?.webhookSchema;if(o==="Webhook"&&n)try{let r=JSON.parse(n);if(r.length>0)return zn(r)}catch{}return[{field:"triggered",description:"Trigger status"},{field:"timestamp",description:"Trigger timestamp"},{field:"input",description:"Input data"}]}return[{field:"data",description:"Output data"}]};function Rr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:s=""}){let[a]=xi(ne),[d]=xi(ue),[i,l]=Ni(0),c=wu(null),[u,f]=Ni(!1);Er(()=>(f(!0),()=>f(!1)),[]);let k=(()=>{if(!r)return[];let g=new Set,C=[],I=A=>{if(g.has(A))return;g.add(A);let w=d.filter(m=>m.target===A);for(let m of w)C.push(m.source),I(m.source)};return I(r),a.filter(A=>C.includes(A.id))})(),b=[];for(let g of k){let C=Nu(g),I=Cu(g);b.push({type:"node",nodeId:g.id,nodeName:C,template:`{{@${g.id}:${C}}}`});for(let A of I)b.push({type:"field",nodeId:g.id,nodeName:C,field:A.field,description:A.description,template:`{{@${g.id}:${C}.${A.field}}}`})}let y=s?b.filter(g=>g.nodeName.toLowerCase().includes(s.toLowerCase())||g.field&&g.field.toLowerCase().includes(s.toLowerCase())):b;if(Er(()=>{l(0)},[s]),Er(()=>{let g=C=>{if(e)switch(C.key){case"ArrowDown":C.preventDefault(),l(I=>I<y.length-1?I+1:I);break;case"ArrowUp":C.preventDefault(),l(I=>I>0?I-1:I);break;case"Enter":C.preventDefault(),y[i]&&o(y[i].template);break;case"Escape":C.preventDefault(),n();break}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e,y,i,o,n]),Er(()=>{if(c.current){let g=c.current.children[i];g&&g.scrollIntoView({block:"nearest"})}},[i]),!e||y.length===0||!u)return null;let p={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},v=Wn("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${p.top}px`,left:`${p.left}px`},children:Wn("div",{className:"max-h-60 overflow-y-auto",children:y.map((g,C)=>Dr("div",{className:x("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",C===i?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(g.template),onMouseEnter:()=>l(C),children:[Dr("div",{className:"flex-1",children:[Wn("div",{className:"font-medium",children:g.type==="node"?g.nodeName:Dr(Tu,{children:[Dr("span",{className:"text-muted-foreground",children:[g.nodeName,"."]}),g.field]})}),g.description&&Wn("div",{className:"text-muted-foreground text-xs",children:g.description})]}),C===i&&Wn(bu,{className:"h-4 w-4"})]},`${g.nodeId}-${g.field||"root"}`))})});return xu(v,document.body)}import{Fragment as Iu,jsx as Oa,jsxs as Pu}from"react/jsx-runtime";function Au(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Su(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=fe(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function De({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s}){let[a,d]=an(!1),i=Ra(null),[l,c]=an(e),u=Ra(!0),[f]=ki(ke),[h]=ki(ne),[k,b]=an(!1),[y,p]=an({top:0,left:0}),[v,g]=an(""),[C,I]=an(null),A=Ra(null);Da(()=>{e!==l&&!a&&(c(e),u.current=!0)},[e,a,l]),Da(()=>{!a&&l&&(u.current=!0)},[h,a,l]);let w=()=>{if(!i.current)return null;let V=window.getSelection();if(!V||V.rangeCount===0)return null;let J=V.getRangeAt(0),F=J.cloneRange();F.selectNodeContents(i.current),F.setEnd(J.endContainer,J.endOffset);let K=0,T=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),z,N=!1;for(;(z=T.nextNode())&&!N;)if(z.nodeType===Node.TEXT_NODE)if(z===J.endContainer)K+=J.endOffset,N=!0;else{let R=(z.textContent||"").length;K+=R}else if(z.nodeType===Node.ELEMENT_NODE){let R=z,G=R.getAttribute("data-template");G&&(R.contains(J.endContainer)||R===J.endContainer?(K+=G.length,N=!0):K+=G.length)}return{offset:K}},m=V=>{if(!i.current||!V)return;let J=0,F=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),K,T=null,z=0;for(;K=F.nextNode();)if(K.nodeType===Node.TEXT_NODE){let N=(K.textContent||"").length;if(J+N>=V.offset){T=K,z=V.offset-J;break}J+=N}else if(K.nodeType===Node.ELEMENT_NODE){let N=K,R=N.getAttribute("data-template");if(R){if(J+R.length>=V.offset){T=N.nextSibling,z=0,!T&&N.parentNode&&(T=document.createTextNode(""),N.parentNode.appendChild(T));break}J+=R.length}}if(T){let N=document.createRange(),R=window.getSelection();try{let G=Math.min(z,T.textContent?.length||0);N.setStart(T,G),N.collapse(!0),R?.removeAllRanges(),R?.addRange(N),i.current.focus()}catch{i.current.focus()}}},S=()=>{if(!i.current||!u.current)return;let V=i.current,J=l||"",F=a?w():null;if(A.current!==null&&(F={offset:A.current},A.current=null),V.innerHTML="",!J&&!a){V.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let K=/\{\{@([^:]+):([^}]+)\}\}/g,T=0,z;for(;(z=K.exec(J))!==null;){let[N]=z,R=z.index;if(R>T){let de=J.slice(T,R),B=document.createTextNode(de);V.appendChild(B)}let G=document.createElement("span"),oe=Au(N,h);G.className=oe?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",G.contentEditable="false",G.setAttribute("data-template",N),G.textContent=Su(N,h),V.appendChild(G),T=K.lastIndex}if(T<J.length){let N=J.slice(T),R=document.createTextNode(N);V.appendChild(R)}V.innerHTML===""&&a&&(V.innerHTML="<br>"),u.current=!1,F&&requestAnimationFrame(()=>m(F))},X=()=>{if(!i.current)return"";let V="",J=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),F;for(;F=J.nextNode();)if(F.nodeType===Node.TEXT_NODE){let K=F.parentElement,T=!1;for(;K&&K!==i.current;){if(K.getAttribute("data-template")){T=!0;break}K=K.parentElement}T||(V+=F.textContent)}else if(F.nodeType===Node.ELEMENT_NODE){let T=F.getAttribute("data-template");T&&(V+=T)}return V},le=()=>{let V=X();if(V===l)return;let J=(l.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,F=(V.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(F>J){c(V),t?.(V),u.current=!0,b(!1),requestAnimationFrame(()=>S());return}if(F===J&&F>0){c(V),t?.(V);let T=V.lastIndexOf("@");if(T!==-1){let z=V.slice(T+1);if(z.includes(" "))b(!1);else{if(g(z),I(T),i.current){let N=i.current.getBoundingClientRect(),R={top:N.bottom+window.scrollY+4,left:N.left+window.scrollX};p(R)}b(!0)}}else b(!1);return}if(F<J){c(V),t?.(V),u.current=!0,requestAnimationFrame(()=>S());return}c(V),t?.(V);let K=V.lastIndexOf("@");if(K!==-1){let T=V.slice(K+1);if(T.includes(" "))b(!1);else{if(g(T),I(K),i.current){let z=i.current.getBoundingClientRect(),N={top:z.bottom+window.scrollY+4,left:z.left+window.scrollX};p(N)}b(!0)}}else b(!1)},L=V=>{if(!i.current||C===null)return;let J=X(),F=J.slice(0,C),K=J.slice(C+1+v.length),T=F+V+K,z=F.length+V.length;c(T),t?.(T),u.current=!0,b(!1),I(null),A.current=z,i.current.focus()},W=()=>{d(!0),u.current=!0},$=()=>{setTimeout(()=>{document.activeElement!==i.current&&(d(!1),u.current=!0,b(!1))},200)},P=V=>{V.preventDefault();let J=V.clipboardData.getData("text/plain");document.execCommand("insertText",!1,J)};return Da(()=>{u.current&&S()},[l,a]),Pu(Iu,{children:[Oa("div",{className:x("flex min-h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),children:Oa("div",{className:"w-full outline-none",contentEditable:!n,id:s,onBlur:$,onFocus:W,onInput:le,onPaste:P,ref:i,role:"textbox",suppressContentEditableWarning:!0})}),Oa(Rr,{currentNodeId:f||void 0,filter:v,isOpen:k,onClose:()=>b(!1),onSelect:L,position:y})]})}import{jsx as at,jsxs as Co}from"react/jsx-runtime";function Ci({config:e,onUpdateConfig:t,disabled:o}){let n=e?.dataType||"string",r=e?.operator||ur[n][0].value,s=ur[n],d=s.find(l=>l.value===r)?.unary??!1;function i(l){t("dataType",l);let c=ur[l];c?.[0]&&t("operator",c[0].value)}return Co("div",{className:"space-y-4",children:[Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"leftValue",children:"Value to Test"}),at(De,{disabled:o,id:"leftValue",onChange:l=>t("leftValue",l),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),at("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"dataType",children:"Data Type"}),Co(ve,{disabled:o,onValueChange:i,value:n,children:[at(he,{id:"dataType",children:at(we,{placeholder:"Select data type"})}),at(be,{children:Zs.map(l=>at(te,{value:l.value,children:l.label},l.value))})]})]}),Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"operator",children:"Operator"}),Co(ve,{disabled:o,onValueChange:l=>t("operator",l),value:r,children:[at(he,{id:"operator",children:at(we,{placeholder:"Select operator"})}),at(be,{children:s.map(l=>at(te,{value:l.value,children:l.label},l.value))})]})]}),!d&&Co("div",{className:"space-y-2",children:[at(M,{htmlFor:"rightValue",children:"Compare Value"}),at(De,{disabled:o,id:"rightValue",onChange:l=>t("rightValue",l),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as Eu,Trash2 as Du}from"lucide-react";import{nanoid as Ru}from"nanoid";import{jsx as Ce,jsxs as ct}from"react/jsx-runtime";function lo({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:Ru(),name:"",type:"string"}])},s=(c,u)=>{let f={...c};return u!=="array"&&(f.itemType=void 0),u!=="object"&&(f.fields=void 0),u==="array"&&!f.itemType&&(f.itemType="string"),u==="object"&&!f.fields&&(f.fields=[]),f},a=(c,u)=>{let f=[...e];f[c]={...f[c],...u},u.type&&(f[c]=s(f[c],u.type)),t(f)},d=c=>{t(e.filter((u,f)=>f!==c))},i=(c,u)=>{let f=[...e];f[c].fields=u,t(f)},l=n>0?"ml-4 border-l-2 border-muted pl-4":"";return ct("div",{className:`space-y-3 ${l}`,children:[e.map((c,u)=>{let f=c.id||`field-${n}-${u}`;return ct("div",{className:"space-y-2 rounded-md border p-3",children:[ct("div",{className:"flex gap-2",children:[ct("div",{className:"flex-1 space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),Ce(se,{disabled:o,id:`field-name-${n}-${u}`,onChange:h=>a(u,{name:h.target.value}),placeholder:"propertyName",value:c.name})]}),ct("div",{className:"flex-1 space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),ct(ve,{disabled:o,onValueChange:h=>a(u,{type:h}),value:c.type,children:[Ce(he,{className:"w-full",id:`field-type-${n}-${u}`,children:Ce(we,{})}),ct(be,{children:[Ce(te,{value:"string",children:"String"}),Ce(te,{value:"number",children:"Number"}),Ce(te,{value:"boolean",children:"Boolean"}),Ce(te,{value:"array",children:"Array"}),Ce(te,{value:"object",children:"Object"})]})]})]}),Ce("div",{className:"flex items-end",children:Ce(D,{disabled:o,onClick:()=>d(u),size:"icon",variant:"ghost",children:Ce(Du,{className:"h-4 w-4"})})})]}),c.type==="array"&&ct("div",{className:"space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),ct(ve,{disabled:o,onValueChange:h=>a(u,{itemType:h}),value:c.itemType||"string",children:[Ce(he,{className:"w-full",id:`field-item-type-${n}-${u}`,children:Ce(we,{})}),ct(be,{children:[Ce(te,{value:"string",children:"String"}),Ce(te,{value:"number",children:"Number"}),Ce(te,{value:"boolean",children:"Boolean"}),Ce(te,{value:"object",children:"Object"})]})]})]}),c.type==="object"&&ct("div",{className:"mt-2",children:[Ce(M,{className:"mb-2 block",children:"Object Properties"}),Ce(lo,{disabled:o,level:n+1,onChange:h=>i(u,h),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&&ct("div",{className:"mt-2",children:[Ce(M,{className:"mb-2 block",children:"Array Item Properties"}),Ce(lo,{disabled:o,level:n+1,onChange:h=>i(u,h),schema:c.fields||[]})]}),ct("div",{className:"space-y-2",children:[Ce(M,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),Ce(se,{disabled:o,id:`field-desc-${n}-${u}`,onChange:h=>a(u,{description:h.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},f)}),ct(D,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[Ce(Eu,{className:"size-4"}),"Add Property"]})]})}import{Fragment as Ou,jsx as sn,jsxs as La}from"react/jsx-runtime";function Ti({config:e,onUpdateConfig:t,disabled:o}){return La(Ou,{children:[La("div",{className:"space-y-2",children:[sn(M,{htmlFor:"dbQuery",children:"SQL Query"}),sn("div",{className:"overflow-hidden rounded-md border",children:sn(yt,{defaultLanguage:"sql",height:"150px",onChange:n=>t("dbQuery",n||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.dbQuery||""})}),sn("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),La("div",{className:"space-y-2",children:[sn(M,{children:"Schema (Optional)"}),sn(lo,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as Lu,jsx as Ke,jsxs as To}from"react/jsx-runtime";function Ai({config:e,onUpdateConfig:t,disabled:o}){return To(Lu,{children:[To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpMethod",children:"HTTP Method"}),To(ve,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[Ke(he,{className:"w-full",id:"httpMethod",children:Ke(we,{placeholder:"Select method"})}),To(be,{children:[Ke(te,{value:"GET",children:"GET"}),Ke(te,{value:"POST",children:"POST"}),Ke(te,{value:"PUT",children:"PUT"}),Ke(te,{value:"PATCH",children:"PATCH"}),Ke(te,{value:"DELETE",children:"DELETE"})]})]})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"endpoint",children:"URL"}),Ke(De,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),Ke("div",{className:"overflow-hidden rounded-md border",children:Ke(yt,{defaultLanguage:"json",height:"100px",onChange:n=>t("httpHeaders",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.httpHeaders||"{}"})})]}),To("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpBody",children:"Body (JSON)"}),Ke("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:Ke(yt,{defaultLanguage:"json",height:"120px",onChange:n=>t("httpBody",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:e?.httpMethod==="GET"||o,domReadOnly:e?.httpMethod==="GET"||o,wordWrap:"off"},value:e?.httpBody||"{}"})}),e?.httpMethod==="GET"&&Ke("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as ln,jsxs as Ma}from"react/jsx-runtime";function Si({config:e,onUpdateConfig:t,disabled:o}){return Ma("div",{className:"space-y-4",children:[Ma("div",{className:"space-y-2",children:[ln(M,{htmlFor:"items",children:"Items to Iterate"}),ln(De,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),ln("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),Ma("div",{className:"space-y-2",children:[ln(M,{htmlFor:"batchSize",children:"Batch Size (optional)"}),ln(De,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),ln("p",{className:"text-muted-foreground text-xs",children:"Number of items per batch. Default is 1 (process one item at a time)."})]})]})}import{Fragment as Mu,jsx as ye,jsxs as Xe}from"react/jsx-runtime";function Ii({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append";return Xe("div",{className:"space-y-4",children:[Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"mode",children:"Mode"}),Xe(ve,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[ye(he,{id:"mode",children:ye(we,{placeholder:"Select mode"})}),Xe(be,{children:[ye(te,{value:"append",children:"Append"}),ye(te,{value:"combineByPosition",children:"Combine by Position"}),ye(te,{value:"combineByFields",children:"Combine by Fields"})]})]}),Xe("p",{className:"text-muted-foreground text-xs",children:[n==="append"&&"Concatenate both lists into one.",n==="combineByPosition"&&"Merge items at the same index from both inputs.",n==="combineByFields"&&"Match and merge items based on a common field."]})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"input1",children:"Input 1"}),ye(De,{disabled:o,id:"input1",onChange:r=>t("input1",r),placeholder:"e.g., {{PreviousNode.rows}}",value:e?.input1||""}),ye("p",{className:"text-muted-foreground text-xs",children:"First array to merge. Use @ to reference outputs from previous nodes."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"input2",children:"Input 2"}),ye(De,{disabled:o,id:"input2",onChange:r=>t("input2",r),placeholder:"e.g., {{AnotherNode.results}}",value:e?.input2||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Second array to merge. Use @ to reference outputs from previous nodes."})]}),n==="combineByPosition"&&Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),Xe(ve,{disabled:o,onValueChange:r=>t("unmatchedHandling",r),value:e?.unmatchedHandling||"useNull",children:[ye(he,{id:"unmatchedHandling",children:ye(we,{})}),Xe(be,{children:[ye(te,{value:"useNull",children:"Fill with null"}),ye(te,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&Xe(Mu,{children:[Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"matchField1",children:"Match Field (Input 1)"}),ye(De,{disabled:o,id:"matchField1",onChange:r=>t("matchField1",r),placeholder:"e.g., id",value:e?.matchField1||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 1 to match on."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"matchField2",children:"Match Field (Input 2)"}),ye(De,{disabled:o,id:"matchField2",onChange:r=>t("matchField2",r),placeholder:"e.g., id",value:e?.matchField2||""}),ye("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 2 to match on."})]}),Xe("div",{className:"space-y-2",children:[ye(M,{htmlFor:"joinType",children:"Join Type"}),Xe(ve,{disabled:o,onValueChange:r=>t("joinType",r),value:e?.joinType||"inner",children:[ye(he,{id:"joinType",children:ye(we,{})}),Xe(be,{children:[ye(te,{value:"inner",children:"Inner Join"}),ye(te,{value:"leftOuter",children:"Left Outer Join"}),ye(te,{value:"rightOuter",children:"Right Outer Join"}),ye(te,{value:"fullOuter",children:"Full Outer Join"})]})]}),ye("p",{className:"text-muted-foreground text-xs",children:"Inner keeps only matches. Left/Right keeps all items from that input. Full keeps everything."})]})]})]})}import{Loader2 as Fu}from"lucide-react";import{useEffect as Wu,useState as Pi}from"react";import{jsx as Gt,jsxs as Bn}from"react/jsx-runtime";function Ei({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Pi([]),[s,a]=Pi(!0);Wu(()=>{async function i(){try{let l=await fetch("/api/workflow-builder/workflows");if(l.ok){let c=await l.json();r((c.workflows||c||[]).map(u=>({id:u.id,name:u.name})))}}catch{}finally{a(!1)}}i()},[]);let d=e?.workflowId||"";return Bn("div",{className:"space-y-4",children:[Bn("div",{className:"space-y-2",children:[Gt(M,{htmlFor:"workflowId",children:"Workflow"}),s?Bn("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Gt(Fu,{className:"size-4 animate-spin"}),"Loading workflows..."]}):Bn(ve,{disabled:o||n.length===0,onValueChange:i=>t("workflowId",i),value:d||void 0,children:[Gt(he,{className:"w-full",id:"workflowId",children:Gt(we,{placeholder:n.length===0?"No workflows found":"Select a workflow"})}),Gt(be,{children:n.map(i=>Gt(te,{value:i.id,children:i.name},i.id))})]}),Gt("p",{className:"text-muted-foreground text-xs",children:"The workflow to execute. It will run inline and wait for completion."})]}),Bn("div",{className:"space-y-2",children:[Gt(M,{htmlFor:"input",children:"Input (optional JSON)"}),Gt(De,{disabled:o,id:"input",onChange:i=>t("input",i),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Gt("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to the sub-workflow."})]})]})}import{ArrowDown as zu,ArrowUp as Bu,Loader2 as Vu,Plus as Gu,Trash2 as Hu}from"lucide-react";import{useEffect as $u,useState as Di}from"react";import{jsx as Re,jsxs as kt}from"react/jsx-runtime";function Ri({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Di([]),[s,a]=Di(!0);$u(()=>{async function p(){try{let v=await fetch("/api/workflow-builder/workflows");if(v.ok){let g=await v.json();r((g.workflows||g||[]).map(C=>({id:C.id,name:C.name})))}}catch{}finally{a(!1)}}p()},[]);let d=e?.workflowIds||"[]",i=[];try{let p=JSON.parse(d);Array.isArray(p)&&(i=p)}catch{i=d.split(",").map(p=>p.trim()).filter(Boolean)}let l=p=>{t("workflowIds",JSON.stringify(p))},c=p=>{p&&!i.includes(p)&&l([...i,p])},u=p=>{let v=[...i];v.splice(p,1),l(v)},f=p=>{if(p===0)return;let v=[...i];[v[p-1],v[p]]=[v[p],v[p-1]],l(v)},h=p=>{if(p===i.length-1)return;let v=[...i];[v[p],v[p+1]]=[v[p+1],v[p]],l(v)},k=p=>n.find(v=>v.id===p)?.name||p,b=n.filter(p=>!i.includes(p.id)),y=e?.continueOnFailure||"false";return kt("div",{className:"space-y-4",children:[kt("div",{className:"space-y-2",children:[Re(M,{children:"Workflows (executed in order)"}),s?kt("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Re(Vu,{className:"size-4 animate-spin"}),"Loading workflows..."]}):kt("div",{className:"space-y-1",children:[i.map((p,v)=>kt("div",{className:"flex items-center gap-1 rounded-md border bg-muted/30 px-2 py-1.5 text-sm",children:[kt("span",{className:"w-5 shrink-0 text-center text-muted-foreground text-xs",children:[v+1,"."]}),Re("span",{className:"min-w-0 flex-1 truncate",children:k(p)}),Re(D,{className:"size-6",disabled:o||v===0,onClick:()=>f(v),size:"icon",variant:"ghost",children:Re(Bu,{className:"size-3"})}),Re(D,{className:"size-6",disabled:o||v===i.length-1,onClick:()=>h(v),size:"icon",variant:"ghost",children:Re(zu,{className:"size-3"})}),Re(D,{className:"size-6 text-destructive hover:text-destructive",disabled:o,onClick:()=>u(v),size:"icon",variant:"ghost",children:Re(Hu,{className:"size-3"})})]},`${p}-${v}`)),b.length>0&&kt(ve,{disabled:o,onValueChange:c,value:"",children:[Re(he,{className:x("w-full",i.length>0&&"border-dashed"),children:kt("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[Re(Gu,{className:"size-3.5"}),Re("span",{children:"Add workflow..."})]})}),Re(be,{children:b.map(p=>Re(te,{value:p.id,children:p.name},p.id))})]}),!s&&n.length===0&&Re("p",{className:"text-muted-foreground text-xs",children:"No workflows found."})]})]}),kt("div",{className:"space-y-2",children:[Re(M,{htmlFor:"continueOnFailure",children:"On failure"}),kt(ve,{disabled:o,onValueChange:p=>t("continueOnFailure",p),value:y,children:[Re(he,{className:"w-full",id:"continueOnFailure",children:Re(we,{})}),kt(be,{children:[Re(te,{value:"false",children:"Stop sequence"}),Re(te,{value:"true",children:"Continue with next workflow"})]})]})]}),kt("div",{className:"space-y-2",children:[Re(M,{htmlFor:"sequenceInput",children:"Input (optional JSON, passed to all workflows)"}),Re(De,{disabled:o,id:"sequenceInput",onChange:p=>t("input",p),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Re("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to every workflow in the sequence."})]})]})}import{jsx as st,jsxs as Lt}from"react/jsx-runtime";function Oi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules";return Lt("div",{className:"space-y-4",children:[Lt("div",{className:"space-y-2",children:[st(M,{htmlFor:"mode",children:"Mode"}),Lt(ve,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[st(he,{id:"mode",children:st(we,{placeholder:"Select mode"})}),Lt(be,{children:[st(te,{value:"rules",children:"Rules"}),st(te,{value:"expression",children:"Expression"})]})]}),Lt("p",{className:"text-muted-foreground text-xs",children:[n==="rules"&&"Each route has a condition. The first route whose condition is true wins.",n==="expression"&&"Compare a value against each route's case value. First match wins."]})]}),n==="expression"&&Lt("div",{className:"space-y-2",children:[st(M,{htmlFor:"switchValue",children:"Value to Switch On"}),st(De,{disabled:o,id:"switchValue",onChange:r=>t("switchValue",r),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),st("p",{className:"text-muted-foreground text-xs",children:"The value to compare against each route's case value. Use @ to reference previous node outputs."})]}),[0,1,2,3].map(r=>Lt("div",{className:"space-y-3 rounded-md border p-3",children:[Lt("p",{className:"font-medium text-sm",children:["Route ",r+1]}),Lt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeName${r}`,children:"Name (optional)"}),st(se,{disabled:o,id:`routeName${r}`,onChange:s=>t(`routeName${r}`,s.target.value),placeholder:`Route ${r+1}`,value:e?.[`routeName${r}`]||""})]}),n==="rules"&&Lt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeCondition${r}`,children:"Condition"}),st(De,{disabled:o,id:`routeCondition${r}`,onChange:s=>t(`routeCondition${r}`,s),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${r}`]||""})]}),n==="expression"&&Lt("div",{className:"space-y-2",children:[st(M,{htmlFor:`routeCaseValue${r}`,children:"Case Value"}),st(De,{disabled:o,id:`routeCaseValue${r}`,onChange:s=>t(`routeCaseValue${r}`,s),placeholder:`e.g., ${r===0?"200":r===1?"404":r===2?"500":"default"}`,value:e?.[`routeCaseValue${r}`]||""})]})]},r)),st("p",{className:"text-muted-foreground text-xs",children:'Routes are evaluated in order. The first matching route wins. If no route matches, the result falls back to "Default".'})]})}import{atom as Or}from"jotai";var Lr=Or(null),Li=Or([]),Mi=Or(!1),hw=Or(!1);import{useAtomValue as Ji,useSetAtom as Va}from"jotai";import{Search as am}from"lucide-react";import{useCallback as sm,useMemo as im,useState as mn}from"react";import{toast as Io}from"sonner";import{atom as Vn,useSetAtom as _u}from"jotai";import*as Wi from"react";var Fi=null;var Ao=Vn(null),Mr=Vn([]),Fr=Vn(!1),zi=Vn(!1),Kt=Vn(null);function Bi(){let e=_u(Kt);Wi.useEffect(()=>{Fi&&e(Fi)},[e])}import{Database as Uu,HelpCircle as Ku}from"lucide-react";import{jsx as Gn}from"react/jsx-runtime";function qu({className:e}){return Gn("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Gn("path",{d:"m577.3 0 577.4 1000H0z"})})}var ju={database:Uu,vercel:qu};function Mt({integration:e,className:t="h-3 w-3"}){let o=ju[e];if(o)return Gn(o,{className:x("text-foreground",t)});let n=Dt(e);if(n?.icon){let r=n.icon;return Gn(r,{className:x("text-foreground",t)})}return Gn(Ku,{className:x("text-foreground",t)})}import{AlertTriangleIcon as nm}from"lucide-react";import{Loader2 as Ju}from"lucide-react";import{jsx as dn,jsxs as Wa}from"react/jsx-runtime";function Fa({action:e}){return Wa(D,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&dn(Ju,{className:"mr-2 size-4 animate-spin"}),e.label]})}function Vi({actions:e,className:t,children:o}){if(o)return dn("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row sm:justify-end",t),children:o});if(!e||e.length===0)return null;let n=e.filter(i=>i.variant==="ghost"),r=e.filter(i=>i.variant==="outline"||i.variant==="secondary"),s=e.filter(i=>!i.variant||i.variant==="default"||i.variant==="destructive"),a=n.length>0,d=r.length>0||s.length>0;return Wa("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&d?"sm:justify-between":"sm:justify-end",t),children:[a&&dn("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(i=>dn(Fa,{action:i},i.label))}),d&&Wa("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(i=>dn(Fa,{action:i},i.label)),s.map(i=>dn(Fa,{action:i},i.label))]})]})}import{ChevronLeftIcon as Zu,XIcon as em}from"lucide-react";import{createContext as Hi,useCallback as cn,useContext as $i,useMemo as Yu,useRef as Xu,useState as Qu}from"react";import{jsx as Gi}from"react/jsx-runtime";var _i=Hi(null),Ui=Hi([]);function za(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Ki({children:e}){let[t,o]=Qu([]),n=Xu([]);t.length>0&&(n.current=t);let r=cn((u,f,h)=>{let k=za();return o([{id:k,component:u,props:f??{},options:h??{}}]),k},[]),s=cn((u,f,h)=>{let k=za(),b={id:k,component:u,props:f??{},options:h??{}};return o(y=>[...y,b]),k},[]),a=cn(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),d=cn((u,f,h)=>{let k=za(),b={id:k,component:u,props:f??{},options:h??{}};return o(y=>y.length===0?[b]:(y[y.length-1]?.options.onClose?.(),[...y.slice(0,-1),b])),k},[]),i=cn(()=>{o(u=>{for(let f of u)f.options.onClose?.();return[]})},[]),l=cn(u=>{o(f=>{let h=f.findIndex(k=>k.id===u);if(h===-1)return f;for(let k=h;k<f.length;k++)f[k].options.onClose?.();return f.slice(0,h)})},[]),c=Yu(()=>({stack:t,open:r,push:s,pop:a,replace:d,closeAll:i,close:l,hasOverlays:t.length>0,depth:t.length}),[t,r,s,a,d,i,l]);return Gi(_i.Provider,{value:c,children:Gi(Ui.Provider,{value:n.current,children:e})})}function re(){let e=$i(_i);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function qi(e){let{stack:t}=re(),o=$i(Ui),n=t.length>0?t:o,r=n.findIndex(s=>s.id===e);return{index:r,isFirst:r===0,isLast:r===n.length-1,depth:n.length,showBackButton:r>0}}import{jsx as So,jsxs as ji}from"react/jsx-runtime";function tm({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:s,className:a}){let{pop:d,closeAll:i}=re(),l=o??!1,c=()=>{r?r():d()},u=()=>{s?s():i()};return ji("div",{className:x("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[ji("div",{className:"flex min-h-8 items-center gap-2",children:[l&&So(D,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:So(Zu,{className:"size-5"})}),e&&So("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&So(D,{"aria-label":"Close",className:"absolute top-4 right-4 size-8 shrink-0 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",onClick:u,size:"icon",variant:"ghost",children:So(em,{className:"size-4"})})]}),t&&So("p",{className:"text-muted-foreground text-sm",children:t})]})}function un({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=qi(e);return So(tm,{...o,showBackButton:t??n})}import{jsx as Ba,jsxs as om}from"react/jsx-runtime";function Oe({overlayId:e,title:t,description:o,actions:n,children:r,className:s}){return om("div",{className:x("flex flex-col",s),children:[(t||o)&&Ba(un,{description:o,overlayId:e,title:t}),r&&Ba("div",{className:"flex-1 overflow-y-auto p-6",children:r}),Ba(Vi,{actions:n})]})}import{jsx as Wr,jsxs as rm}from"react/jsx-runtime";function Me({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:s="default",destructive:a=!1,onConfirm:d,onCancel:i}){let{pop:l}=re();return Wr(Oe,{actions:[{label:r,variant:"outline",onClick:()=>{i?.(),l()}},{label:n,variant:a?"destructive":s,onClick:async()=>{await d(),l()}}],overlayId:e,title:t,children:rm("div",{className:"flex gap-4",children:[a&&Wr("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Wr(nm,{className:"size-5 text-destructive"})}),Wr("p",{className:x("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{jsx as Ge,jsxs as vt}from"react/jsx-runtime";var lm=["database"],dm={database:"Database"},cm={database:"Connect to PostgreSQL databases"},um=()=>[...Xs(),...lm],Ga=e=>eo()[e]||dm[e]||e,mm=e=>Ys()[e]||cm[e]||"";function Xi({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=re(),[r,s]=mn(""),a=Vt(),d=Ji(Kt),i=Ji(Ao),l=Va(Ao),c=Va(Mr),u=Va(Fr),f=um(),h=im(()=>{if(!r.trim())return f;let y=r.toLowerCase();return f.filter(p=>Ga(p).toLowerCase().includes(y))},[f,r]),k=sm(()=>{d&&o(d.ConsentOverlay,{onConsent:y=>{t?.(y),n()}})},[d,o,n,t]),b=y=>{let p=d?.integrationType===y;if(p&&i?.enabled&&i?.isVercelUser){k();return}if(p&&i===null){d.api.getStatus().then(g=>{l(g),g?.enabled&&g?.isVercelUser?(u(!0),d.api.getTeams().then(C=>{c(C.teams)}).finally(()=>{u(!1),k()})):o(co,{type:y,onSuccess:t})});return}o(co,{type:y,onSuccess:t})};return vt(Oe,{overlayId:e,title:"Add Connection",children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),vt("div",{className:"space-y-3",children:[vt("div",{className:"relative",children:[Ge(am,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ge(se,{autoFocus:!a,className:"pl-9",onChange:y=>s(y.target.value),placeholder:"Search services...",value:r})]}),Ge("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:h.length===0?Ge("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):h.map(y=>{let p=mm(y);return vt("button",{className:"flex w-full items-center gap-3 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted/50",onClick:()=>b(y),type:"button",children:[Ge(Mt,{className:"size-5 shrink-0",integration:y==="ai-gateway"?"vercel":y}),vt("span",{className:"min-w-0 flex-1 truncate",children:[Ge("span",{className:"font-medium",children:Ga(y)}),p&&vt("span",{className:"text-muted-foreground text-xs",children:[" ","- ",p]})]})]},y)})})]})]})}function Yi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:d}){return vt("div",{className:"space-y-2",children:[Ge(M,{htmlFor:e,children:t}),Ge(se,{className:"flex-1",id:e,onChange:i=>d(o,i.target.value),placeholder:n,type:"password",value:a}),(r||s)&&vt("p",{className:"text-muted-foreground text-xs",children:[r,s&&Ge("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]})}function co({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=re(),[s,a]=mn(!1),[d,i]=mn(!1),[l,c]=mn(null),[u,f]=mn(""),[h,k]=mn({}),b=(A,w)=>{k(m=>({...m,[A]:w}))},y=async()=>{try{a(!0);let A=await q.integration.create({name:u.trim(),type:t,config:h});Io.success("Connection created"),o?.(A.id),r()}catch(A){console.error("Failed to save integration:",A),Io.error("Failed to save connection")}finally{a(!1)}},p=async()=>{if(!Object.values(h).some(w=>w&&w.length>0)){Io.error("Please enter credentials");return}try{a(!0),c(null);let w=await q.integration.testCredentials({type:t,config:h});if(w.status==="error"){n(Me,{title:"Connection Test Failed",message:`The test failed: ${w.message}
|
|
1
|
+
"use client";import{a as qo,b as jo,c as Jo}from"../chunk-NI6U7PHC.js";import{i as gr}from"../chunk-VUDOAZ3W.js";import{a as oi,b as yr}from"../chunk-3YVRTDK2.js";import{a as N}from"../chunk-6UXAINJQ.js";import{d as Js,h as Rt,i as Ys,k as Xs,l as Qs,m as ge,n as to,o as Zs,p as ei,v as ti,w as Aa,y as Ko}from"../chunk-QRG4O4PE.js";import{AuthView as Af}from"@daveyplate/better-auth-ui";import{useParams as If}from"next/navigation";import{useAtom as Ut,useAtomValue as pf,useSetAtom as At}from"jotai";import{ChevronLeft as ff,ChevronRight as gf}from"lucide-react";import yf from"next/link";import{useSearchParams as vf}from"next/navigation";import{useCallback as yo,useEffect as It,useRef as Fo,useState as us}from"react";import{toast as ms}from"sonner";var Ia=class extends Error{status;constructor(t,o){super(o),this.status=t,this.name="ApiError"}};async function ye(e,t){let o=await fetch(e,{...t,headers:{"Content-Type":"application/json",...t?.headers}});if(!o.ok){let n=await o.json().catch(()=>({error:"Unknown error"}));throw new Ia(o.status,n.error||"Request failed")}return o.json()}function Bc(e,t){e?.name&&(t.currentData.name=e.name)}function Vc(e,t){e?.description&&(t.currentData.description=e.description)}function Hc(e,t){e?.node&&(t.currentData.nodes=[...t.currentData.nodes,e.node])}function Gc(e,t){e?.edge&&(t.currentData.edges=[...t.currentData.edges,e.edge])}function $c(e,t){e?.nodeId&&(t.currentData.nodes=t.currentData.nodes.filter(o=>o.id!==e.nodeId),t.currentData.edges=t.currentData.edges.filter(o=>o.source!==e.nodeId&&o.target!==e.nodeId))}function _c(e,t){e?.edgeId&&(t.currentData.edges=t.currentData.edges.filter(o=>o.id!==e.edgeId))}function Uc(e,t){e?.nodeId&&e.updates&&(t.currentData.nodes=t.currentData.nodes.map(o=>o.id===e.nodeId?{...o,...e.updates?.position?{position:e.updates.position}:{},...e.updates?.data?{data:{...o.data,...e.updates.data}}:{}}:o))}var Kc={setName:Bc,setDescription:Vc,addNode:Hc,addEdge:Gc,removeNode:$c,removeEdge:_c,updateNode:Uc};function qc(e,t){if(!e?.op)return;let o=Kc[e.op];o&&o(e,t)}function jc(e,t,o){if(e.trim())try{let n=JSON.parse(e);if(n.type==="operation"&&n.operation)qc(n.operation,o),t({...o.currentData});else if(n.type==="error")throw console.error("[API Client] Error:",n.error),new Error(n.error)}catch(n){console.error("[API Client] Failed to parse JSONL line:",n)}}function Jc(e,t,o,n){n.buffer+=t.decode(e,{stream:!0});let r=n.buffer.split(`
|
|
2
|
+
`);n.buffer=r.pop()||"";for(let i of r)jc(i,o,n)}var Yc={generate:(e,t)=>ye("/api/ai/generate",{method:"POST",body:JSON.stringify({prompt:e,existingWorkflow:t})}),generateStream:async(e,t,o)=>{let n=await fetch("/api/ai/generate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:e,existingWorkflow:o})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);if(!n.body)throw new Error("No response body");let r=n.body.getReader(),i=new TextDecoder,a={buffer:"",currentData:o?{nodes:o.nodes||[],edges:o.edges||[],name:o.name}:{nodes:[],edges:[]}};try{for(;;){let{done:l,value:s}=await r.read();if(l)break;Jc(s,i,t,a)}return a.currentData}finally{r.releaseLock()}}},Xc={getAll:e=>ye(`/api/integrations${e?`?type=${e}`:""}`),get:e=>ye(`/api/integrations/${e}`),create:e=>ye("/api/integrations",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ye(`/api/integrations/${e}`,{method:"PUT",body:JSON.stringify(t)}),delete:e=>ye(`/api/integrations/${e}`,{method:"DELETE"}),testConnection:e=>ye(`/api/integrations/${e}/test`,{method:"POST"}),testCredentials:e=>ye("/api/integrations/test",{method:"POST",body:JSON.stringify(e)})},Qc={get:()=>ye("/api/user"),update:e=>ye("/api/user",{method:"PATCH",body:JSON.stringify(e)})},vr={getAll:()=>ye("/api/workflows"),getById:e=>ye(`/api/workflows/${e}`),create:e=>ye("/api/workflows/create",{method:"POST",body:JSON.stringify(e)}),update:(e,t)=>ye(`/api/workflows/${e}`,{method:"PATCH",body:JSON.stringify(t)}),delete:e=>ye(`/api/workflows/${e}`,{method:"DELETE"}),duplicate:e=>ye(`/api/workflows/${e}/duplicate`,{method:"POST"}),getCurrent:()=>ye("/api/workflows/current"),saveCurrent:(e,t)=>ye("/api/workflows/current",{method:"POST",body:JSON.stringify({nodes:e,edges:t})}),execute:(e,t={})=>ye(`/api/workflow/${e}/execute`,{method:"POST",body:JSON.stringify({input:t})}),triggerWebhook:(e,t={})=>ye(`/api/workflows/${e}/webhook`,{method:"POST",body:JSON.stringify(t)}),getCode:e=>ye(`/api/workflows/${e}/code`),getExecutions:e=>ye(`/api/workflows/${e}/executions`),deleteExecutions:e=>ye(`/api/workflows/${e}/executions`,{method:"DELETE"}),getExecutionLogs:e=>ye(`/api/workflows/executions/${e}/logs`),getExecutionStatus:e=>ye(`/api/workflows/executions/${e}/status`),cancelExecution:e=>ye(`/api/workflows/executions/${e}/cancel`,{method:"POST"}),download:e=>ye(`/api/workflows/${e}/download`),autoSaveCurrent:(()=>{let e=null,t=2e3;return(o,n)=>{e&&clearTimeout(e),e=setTimeout(()=>{vr.saveCurrent(o,n).catch(r=>{console.error("Auto-save failed:",r)})},t)}})(),autoSaveWorkflow:(()=>{let e=null,t=2e3;return(o,n,r=!0)=>{if(!r)return vr.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{vr.update(o,n).catch(i=>{console.error("Auto-save failed:",i)})},t)}})()},Zc={getStatus:()=>ye("/api/ai-gateway/status"),getTeams:()=>ye("/api/ai-gateway/teams"),consent:(e,t)=>ye("/api/ai-gateway/consent",{method:"POST",body:JSON.stringify({teamId:e,teamName:t})}),revokeConsent:()=>ye("/api/ai-gateway/consent",{method:"DELETE"})},j={ai:Yc,aiGateway:Zc,integration:Xc,user:Qc,workflow:vr};import{atom as Hn}from"jotai";var ft=Hn([]),hr=Hn(!1),uh=Hn(null),Ot=Hn(0),ni=Hn(e=>{let t=e(ft);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as eu,applyNodeChanges as tu}from"@xyflow/react";import{atom as ie}from"jotai";var re=ie([]),ce=ie([]),Ce=ie(null),_e=ie(null),si=ie(!1),ri=ie(!1),kt=ie(!1),Ue=ie(null),gt=ie(""),br=ie("private"),no=ie(!0),Yo=ie({snapToGrid:!0,edgeStyle:"smoothstep"}),Ht=ie("properties"),wr=ie(!1),ro=ie(null),xr=ie(null),Nr=ie(!1),kr=ie(!1),ii=ie(!1),Cr=ie(!1),Tr=ie(new Set),oo=ie(null),Sr=ie(!1),Xo=ie({}),Pa=null,ou=1e3,Lt=ie(null,async(e,t,o)=>{let n=e(Ue),r=e(re),i=e(ce);if(!n)return;let a=async()=>{try{await j.workflow.update(n,{nodes:r,edges:i}),t(rt,!1)}catch(l){console.error("Autosave failed:",l)}};o?.immediate?await a():(Pa&&clearTimeout(Pa),Pa=setTimeout(a,ou))}),li=ie(null,(e,t,o)=>{let n=e(re),r=o.filter(d=>d.type==="remove"?n.find(u=>u.id===d.id)?.data.type!=="trigger":!0),i=tu(r,n);t(re,i);let a=i.find(d=>d.selected);if(a){t(Ce,a.id),t(_e,null);let d=e(oo);d&&d!==a.id&&t(oo,null)}else if(e(Ce)){let d=e(Ce);i.find(u=>u.id===d)||t(Ce,null),t(oo,null)}if(r.some(d=>d.type==="remove")){t(Lt,{immediate:!0});return}r.some(d=>d.type==="position"&&d.dragging===!1)&&t(Lt)}),di=ie(null,(e,t,o)=>{let n=e(ce),r=eu(o,n);t(ce,r);let i=r.find(l=>l.selected);if(i)t(_e,i.id),t(Ce,null);else if(e(_e)){let l=e(_e);r.find(d=>d.id===l)||t(_e,null)}o.some(l=>l.type==="remove")&&t(Lt,{immediate:!0})}),Qo=ie(null,(e,t,o)=>{let n=e(re),r=e(ce),i=e(nt);t(nt,[...i,{nodes:n,edges:r}]),t(Vt,[]);let a=n.map(d=>({...d,selected:!1})),l={...o,selected:!0},s=[...a,l];t(re,s),t(Ce,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(oo,o.id),t(rt,!0),t(Lt,{immediate:!0})}),ao=ie(null,(e,t,{id:o,data:n})=>{let r=e(re),a=r.find(c=>c.id===o)?.data.label,l=n.label,s=l!==void 0&&a!==l,d=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(s&&a){let u=ci(c.data.config||{},o,a,l);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(re,d),n.status||(t(rt,!0),t(Lt))});function ci(e,t,o,n){let r=!1,i={};for(let[a,l]of Object.entries(e))if(typeof l=="string"){let s=new RegExp(`\\{\\{@${ai(t)}:${ai(o)}(\\.[^}]+)?\\}\\}`,"g"),d=l.replace(s,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));i[a]=d}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let s=ci(l,t,o,n);s!==l&&(r=!0),i[a]=s}else i[a]=l;return r?i:e}function ai(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var so=ie(null,(e,t,o)=>{let n=e(re);if(n.find(d=>d.id===o)?.data.type==="trigger")return;let i=e(ce),a=e(nt);t(nt,[...a,{nodes:n,edges:i}]),t(Vt,[]);let l=n.filter(d=>d.id!==o),s=i.filter(d=>d.source!==o&&d.target!==o);t(re,l),t(ce,s),e(Ce)===o&&t(Ce,null),t(rt,!0),t(Lt,{immediate:!0})}),io=ie(null,(e,t,o)=>{let n=e(re),r=e(ce),i=e(nt);t(nt,[...i,{nodes:n,edges:r}]),t(Vt,[]);let a=r.filter(l=>l.id!==o);t(ce,a),e(_e)===o&&t(_e,null),t(rt,!0),t(Lt,{immediate:!0})}),ui=ie(null,(e,t)=>{let o=e(re),n=e(ce),r=e(nt);t(nt,[...r,{nodes:o,edges:n}]),t(Vt,[]);let i=o.filter(s=>s.selected&&s.data.type!=="trigger").map(s=>s.id),a=o.filter(s=>s.data.type==="trigger"?!0:!s.selected),l=n.filter(s=>!(s.selected||i.includes(s.source)||i.includes(s.target)));t(re,a),t(ce,l),t(Ce,null),t(_e,null),t(rt,!0),t(Lt,{immediate:!0})}),Zo=ie(null,(e,t)=>{let o=e(re),n=e(ce),r=e(nt);t(nt,[...r,{nodes:o,edges:n}]),t(Vt,[]);let i=o.filter(a=>a.data.type==="trigger");t(re,i),t(ce,[]),t(Ce,null),t(_e,null),t(rt,!0),t(Lt,{immediate:!0})}),yh=ie(null,async(e,t)=>{try{t(ri,!0);let o=await j.workflow.getCurrent();t(re,o.nodes),t(ce,o.edges),o.id&&t(Ue,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t(ri,!1)}}),vh=ie(null,async(e,t,{name:o,description:n})=>{let r=e(re),i=e(ce);try{return await j.workflow.create({name:o,description:n,nodes:r,edges:i})}catch(a){throw console.error("Failed to save workflow:",a),a}}),Ar=ie(!1),rt=ie(!1),mi=ie(!1),nt=ie([]),Vt=ie([]),pi=ie(null,(e,t)=>{let o=e(nt);if(o.length===0)return;let n=e(re),r=e(ce),i=e(Vt);t(Vt,[...i,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(nt,a),t(re,l.nodes),t(ce,l.edges),t(rt,!0))}),fi=ie(null,(e,t)=>{let o=e(Vt);if(o.length===0)return;let n=e(re),r=e(ce),i=e(nt);t(nt,[...i,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(Vt,a),t(re,l.nodes),t(ce,l.edges),t(rt,!0))}),gi=ie(e=>e(nt).length>0),yi=ie(e=>e(Vt).length>0),Ir=ie(null,(e,t)=>{let n=e(re).map(r=>({...r,data:{...r.data,status:"idle"}}));t(re,n)});import*as Pr from"react";var Ea=768;function Gt(){let[e,t]=Pr.useState(void 0);return Pr.useEffect(()=>{let o=window.matchMedia(`(max-width: ${Ea-1}px)`),n=()=>{t(window.innerWidth<Ea)};return o.addEventListener("change",n),t(window.innerWidth<Ea),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as nu}from"radix-ui";import{cva as ru}from"class-variance-authority";import{jsx as au}from"react/jsx-runtime";var Er=ru("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function E({className:e,variant:t,size:o,asChild:n=!1,...r}){let i=n?nu.Slot:"button";return au(i,{"data-slot":"button",className:N(Er({variant:t,size:o,className:e})),...r})}var su={"Database Query":"database"};function iu(e){return ge(e)?.integration||su[e]}function vi(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=iu(n);if(!r)return null;let i=e.data.config?.integrationId;if(i&&o.has(i))return null;let l=t.filter(s=>s.type===r);return l.length===1?{nodeId:e.id,newIntegrationId:l[0].id}:l.length===0&&i?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as fo,useAtomValue as ls,useSetAtom as Wo}from"jotai";import{Copy as Vl,Eraser as ds,Eye as rf,EyeOff as af,FileCode as Hl,RefreshCw as Gl,Trash2 as na}from"lucide-react";import{useCallback as sf,useEffect as $l,useMemo as lf,useRef as _l,useState as or}from"react";import{toast as Tn}from"sonner";import{AlertTriangleIcon as yu}from"lucide-react";import{Loader2 as lu}from"lucide-react";import{jsx as en,jsxs as Ra}from"react/jsx-runtime";function Da({action:e}){return Ra(E,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&en(lu,{className:"mr-2 size-4 animate-spin"}),e.label]})}function hi({actions:e,className:t,children:o}){if(o)return en("div",{className:N("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row sm:justify-end",t),children:o});if(!e||e.length===0)return null;let n=e.filter(s=>s.variant==="ghost"),r=e.filter(s=>s.variant==="outline"||s.variant==="secondary"),i=e.filter(s=>!s.variant||s.variant==="default"||s.variant==="destructive"),a=n.length>0,l=r.length>0||i.length>0;return Ra("div",{className:N("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&l?"sm:justify-between":"sm:justify-end",t),children:[a&&en("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(s=>en(Da,{action:s},s.label))}),l&&Ra("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(s=>en(Da,{action:s},s.label)),i.map(s=>en(Da,{action:s},s.label))]})]})}import{ChevronLeftIcon as mu,XIcon as pu}from"lucide-react";import{createContext as wi,useCallback as tn,useContext as xi,useMemo as du,useRef as cu,useState as uu}from"react";import{jsx as bi}from"react/jsx-runtime";var Ni=wi(null),ki=wi([]);function Oa(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Ci({children:e}){let[t,o]=uu([]),n=cu([]);t.length>0&&(n.current=t);let r=tn((u,f,v)=>{let C=Oa();return o([{id:C,component:u,props:f??{},options:v??{}}]),C},[]),i=tn((u,f,v)=>{let C=Oa(),h={id:C,component:u,props:f??{},options:v??{}};return o(y=>[...y,h]),C},[]),a=tn(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),l=tn((u,f,v)=>{let C=Oa(),h={id:C,component:u,props:f??{},options:v??{}};return o(y=>y.length===0?[h]:(y[y.length-1]?.options.onClose?.(),[...y.slice(0,-1),h])),C},[]),s=tn(()=>{o(u=>{for(let f of u)f.options.onClose?.();return[]})},[]),d=tn(u=>{o(f=>{let v=f.findIndex(C=>C.id===u);if(v===-1)return f;for(let C=v;C<f.length;C++)f[C].options.onClose?.();return f.slice(0,v)})},[]),c=du(()=>({stack:t,open:r,push:i,pop:a,replace:l,closeAll:s,close:d,hasOverlays:t.length>0,depth:t.length}),[t,r,i,a,l,s,d]);return bi(Ni.Provider,{value:c,children:bi(ki.Provider,{value:n.current,children:e})})}function oe(){let e=xi(Ni);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function Ti(e){let{stack:t}=oe(),o=xi(ki),n=t.length>0?t:o,r=n.findIndex(i=>i.id===e);return{index:r,isFirst:r===0,isLast:r===n.length-1,depth:n.length,showBackButton:r>0}}import{jsx as Co,jsxs as Si}from"react/jsx-runtime";function fu({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:i,className:a}){let{pop:l,closeAll:s}=oe(),d=o??!1,c=()=>{r?r():l()},u=()=>{i?i():s()};return Si("div",{className:N("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[Si("div",{className:"flex min-h-8 items-center gap-2",children:[d&&Co(E,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:Co(mu,{className:"size-5"})}),e&&Co("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&Co(E,{"aria-label":"Close",className:"absolute top-4 right-4 size-8 shrink-0 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",onClick:u,size:"icon",variant:"ghost",children:Co(pu,{className:"size-4"})})]}),t&&Co("p",{className:"text-muted-foreground text-sm",children:t})]})}function on({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=Ti(e);return Co(fu,{...o,showBackButton:t??n})}import{jsx as La,jsxs as gu}from"react/jsx-runtime";function Re({overlayId:e,title:t,description:o,actions:n,children:r,className:i}){return gu("div",{className:N("flex flex-col",i),children:[(t||o)&&La(on,{description:o,overlayId:e,title:t}),r&&La("div",{className:"flex-1 overflow-y-auto p-6",children:r}),La(hi,{actions:n})]})}import{jsx as Dr,jsxs as vu}from"react/jsx-runtime";function Pe({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:i="default",destructive:a=!1,onConfirm:l,onCancel:s}){let{pop:d}=oe();return Dr(Re,{actions:[{label:r,variant:"outline",onClick:()=>{s?.(),d()}},{label:n,variant:a?"destructive":i,onClick:async()=>{await l(),d()}}],overlayId:e,title:t,children:vu("div",{className:"flex gap-4",children:[a&&Dr("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Dr(yu,{className:"size-5 text-destructive"})}),Dr("p",{className:N("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{AlertDialog as lo}from"radix-ui";import{jsx as Mt,jsxs as wu}from"react/jsx-runtime";function nn({...e}){return Mt(lo.Root,{"data-slot":"alert-dialog",...e})}function hu({...e}){return Mt(lo.Portal,{"data-slot":"alert-dialog-portal",...e})}function bu({className:e,...t}){return Mt(lo.Overlay,{"data-slot":"alert-dialog-overlay",className:N("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function rn({className:e,...t}){return wu(hu,{children:[Mt(bu,{}),Mt(lo.Content,{"data-slot":"alert-dialog-content",className:N("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...t})]})}function an({className:e,...t}){return Mt("div",{"data-slot":"alert-dialog-header",className:N("flex flex-col gap-2 text-center sm:text-left",e),...t})}function sn({className:e,...t}){return Mt("div",{"data-slot":"alert-dialog-footer",className:N("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function ln({className:e,...t}){return Mt(lo.Title,{"data-slot":"alert-dialog-title",className:N("text-lg font-semibold",e),...t})}function dn({className:e,...t}){return Mt(lo.Description,{"data-slot":"alert-dialog-description",className:N("text-muted-foreground text-sm",e),...t})}function cn({className:e,...t}){return Mt(lo.Action,{className:N(Er(),e),...t})}function un({className:e,...t}){return Mt(lo.Cancel,{className:N(Er({variant:"outline"}),e),...t})}import xu from"@monaco-editor/react";import{useTheme as Nu}from"next-themes";var Ai={base:"vs-dark",inherit:!0,rules:[{token:"",foreground:"ededed"},{token:"comment",foreground:"a1a1a1",fontStyle:"italic"},{token:"keyword",foreground:"ff4d8d"},{token:"keyword.operator",foreground:"ff4d8d"},{token:"string",foreground:"00ca50"},{token:"string.escape",foreground:"00ca50"},{token:"number",foreground:"ffffff"},{token:"type",foreground:"47a8ff"},{token:"type.identifier",foreground:"47a8ff"},{token:"identifier",foreground:"ededed"},{token:"parameter",foreground:"ededed"},{token:"variable",foreground:"ededed"},{token:"variable.parameter",foreground:"ededed"},{token:"function",foreground:"c472fb"},{token:"identifier.function",foreground:"c472fb"},{token:"member.function",foreground:"c472fb"},{token:"constant.language",foreground:"47a8ff"},{token:"keyword.json",foreground:"47a8ff"},{token:"variable.predefined",foreground:"ededed"},{token:"support.variable",foreground:"ededed"},{token:"support.constant",foreground:"ededed"},{token:"delimiter",foreground:"ededed"},{token:"delimiter.bracket",foreground:"ededed"},{token:"delimiter.parenthesis",foreground:"ededed"},{token:"delimiter.curly",foreground:"ededed"},{token:"delimiter.array",foreground:"ededed"},{token:"punctuation",foreground:"ededed"},{token:"operator",foreground:"ededed"},{token:"string.key.json",foreground:"47a8ff"},{token:"string.value.json",foreground:"00ca50"},{token:"number.json",foreground:"ffffff"},{token:"keyword.json",foreground:"47a8ff"}],colors:{"editor.background":"#000000","editor.foreground":"#ededed","editorLineNumber.foreground":"#444444","editorLineNumber.activeForeground":"#888888","editor.lineHighlightBackground":"#0A0A0A","editor.selectionBackground":"#264F78","editor.inactiveSelectionBackground":"#1A1A1A","editorCursor.foreground":"#FFFFFF","editorWhitespace.foreground":"#333333","editorIndentGuide.background":"#1A1A1A","editorIndentGuide.activeBackground":"#333333","editorBracketMatch.background":"#0A0A0A","editorBracketMatch.border":"#444444"}};import{jsx as ku}from"react/jsx-runtime";function yt(e){let{resolvedTheme:t}=Nu();return ku(xu,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",Ai),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as Cu}from"react/jsx-runtime";function ae({className:e,type:t,...o}){return Cu("input",{type:t,"data-slot":"input",className:N("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground bg-transparent border-input h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",e),...o})}import{Label as Tu}from"radix-ui";import{jsx as Su}from"react/jsx-runtime";function M({className:e,...t}){return Su(Tu.Root,{"data-slot":"label",className:N("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...t})}import{Tabs as Rr}from"radix-ui";import{jsx as Or}from"react/jsx-runtime";function Ma({className:e,...t}){return Or(Rr.Root,{"data-slot":"tabs",className:N("flex flex-col gap-2",e),...t})}function Wa({className:e,...t}){return Or(Rr.List,{"data-slot":"tabs-list",className:N("bg-muted text-muted-foreground inline-flex h-10 w-fit items-center justify-center rounded-lg p-[3px]",e),...t})}function To({className:e,...t}){return Or(Rr.Trigger,{"data-slot":"tabs-trigger",className:N("data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-sm border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function So({className:e,...t}){return Or(Rr.Content,{"data-slot":"tabs-content",className:N("flex-1 outline-none",e),...t})}import{useAtomValue as fl,useSetAtom as Ym}from"jotai";import{HelpCircle as Xm,Plus as Qm,Settings as Zm}from"lucide-react";import{useEffect as ep,useMemo as Kr,useState as tp}from"react";import{Select as at}from"radix-ui";import{CheckIcon as Au,ChevronDownIcon as Ii,ChevronUpIcon as Iu}from"lucide-react";import{jsx as Be,jsxs as Fa}from"react/jsx-runtime";function ve({...e}){return Be(at.Root,{"data-slot":"select",...e})}function Pi({...e}){return Be(at.Group,{"data-slot":"select-group",...e})}function xe({...e}){return Be(at.Value,{"data-slot":"select-value",...e})}function he({className:e,size:t="default",children:o,...n}){return Fa(at.Trigger,{"data-slot":"select-trigger","data-size":t,className:N("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive bg-transparent hover:bg-accent/50 flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,Be(at.Icon,{asChild:!0,children:Be(Ii,{className:"size-4 opacity-50"})})]})}function be({className:e,children:t,position:o="popper",align:n="center",...r}){return Be(at.Portal,{children:Fa(at.Content,{"data-slot":"select-content",className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",o==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:o,align:n,...r,children:[Be(Pu,{}),Be(at.Viewport,{className:N("p-1",o==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),Be(Eu,{})]})})}function Ei({className:e,...t}){return Be(at.Label,{"data-slot":"select-label",className:N("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function Z({className:e,children:t,...o}){return Fa(at.Item,{"data-slot":"select-item",className:N("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...o,children:[Be("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:Be(at.ItemIndicator,{children:Be(Au,{className:"size-4"})})}),Be(at.ItemText,{children:t})]})}function Lr({className:e,...t}){return Be(at.Separator,{"data-slot":"select-separator",className:N("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function Pu({className:e,...t}){return Be(at.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:N("flex cursor-default items-center justify-center py-1",e),...t,children:Be(Iu,{className:"size-4"})})}function Eu({className:e,...t}){return Be(at.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:N("flex cursor-default items-center justify-center py-1",e),...t,children:Be(Ii,{className:"size-4"})})}import{useAtom as Oi}from"jotai";import{useEffect as za,useRef as Ba,useState as mn}from"react";import{useAtom as Di}from"jotai";import{Check as Du}from"lucide-react";import{useEffect as Mr,useRef as Ru,useState as Ri}from"react";import{createPortal as Ou}from"react-dom";import{Fragment as Fu,jsx as Gn,jsxs as Wr}from"react/jsx-runtime";var Lu=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=ge(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},$n=(e,t="")=>{let o=[];for(let n of e){let r=t?`${t}.${n.name}`:n.name,i=n.type==="array"?`${n.itemType}[]`:n.type==="enum"?`enum<${(n.enumValues||[]).join(" | ")||n.enumItemType||"string"}>`:n.type,a=n.description||`${i}`;if(o.push({field:r,description:a}),n.type==="object"&&n.fields&&n.fields.length>0&&o.push(...$n(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let l=`${r}[0]`;o.push(...$n(n.fields,l))}}return o},Mu=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,Wu=e=>{let t=e.data.config?.actionType;if(t==="HTTP Request")return[{field:"data",description:"Response data"},{field:"status",description:"HTTP status code"}];if(t==="Database Query"){let o=e.data.config?.dbSchema;if(o)try{let n=JSON.parse(o);if(n.length>0)return $n(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(Mu(t,"Generate Text","ai-gateway/generate-text")){let o=e.data.config?.aiFormat,n=e.data.config?.aiSchema;if(o==="object"&&n)try{let r=JSON.parse(n);if(r.length>0)return $n(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=ge(t);if(o?.outputFields&&o.outputFields.length>0)return o.outputFields}if(e.data.type==="trigger"){let o=e.data.config?.triggerType,n=e.data.config?.webhookSchema;if(o==="Webhook"&&n)try{let r=JSON.parse(n);if(r.length>0)return $n(r)}catch{}return[{field:"triggered",description:"Trigger status"},{field:"timestamp",description:"Trigger timestamp"},{field:"input",description:"Input data"}]}return[{field:"data",description:"Output data"}]};function Fr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:i=""}){let[a]=Di(re),[l]=Di(ce),[s,d]=Ri(0),c=Ru(null),[u,f]=Ri(!1);Mr(()=>(f(!0),()=>f(!1)),[]);let C=(()=>{if(!r)return[];let g=new Set,S=[],D=I=>{if(g.has(I))return;g.add(I);let x=l.filter(p=>p.target===I);for(let p of x)S.push(p.source),D(p.source)};return D(r),a.filter(I=>S.includes(I.id))})(),h=[];for(let g of C){let S=Lu(g),D=Wu(g);h.push({type:"node",nodeId:g.id,nodeName:S,template:`{{@${g.id}:${S}}}`});for(let I of D)h.push({type:"field",nodeId:g.id,nodeName:S,field:I.field,description:I.description,template:`{{@${g.id}:${S}.${I.field}}}`})}let y=i?h.filter(g=>g.nodeName.toLowerCase().includes(i.toLowerCase())||g.field&&g.field.toLowerCase().includes(i.toLowerCase())):h;if(Mr(()=>{d(0)},[i]),Mr(()=>{let g=S=>{if(e)switch(S.key){case"ArrowDown":S.preventDefault(),d(D=>D<y.length-1?D+1:D);break;case"ArrowUp":S.preventDefault(),d(D=>D>0?D-1:D);break;case"Enter":S.preventDefault(),y[s]&&o(y[s].template);break;case"Escape":S.preventDefault(),n();break}};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[e,y,s,o,n]),Mr(()=>{if(c.current){let g=c.current.children[s];g&&g.scrollIntoView({block:"nearest"})}},[s]),!e||y.length===0||!u)return null;let m={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},b=Gn("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${m.top}px`,left:`${m.left}px`},children:Gn("div",{className:"max-h-60 overflow-y-auto",children:y.map((g,S)=>Wr("div",{className:N("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",S===s?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(g.template),onMouseEnter:()=>d(S),children:[Wr("div",{className:"flex-1",children:[Gn("div",{className:"font-medium",children:g.type==="node"?g.nodeName:Wr(Fu,{children:[Wr("span",{className:"text-muted-foreground",children:[g.nodeName,"."]}),g.field]})}),g.description&&Gn("div",{className:"text-muted-foreground text-xs",children:g.description})]}),S===s&&Gn(Du,{className:"h-4 w-4"})]},`${g.nodeId}-${g.field||"root"}`))})});return Ou(b,document.body)}import{Fragment as Vu,jsx as Va,jsxs as Hu}from"react/jsx-runtime";function zu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Bu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],i=t.find(d=>d.id===n);if(!i)return r;let a=i.data.label;if(!a&&i.data.type==="action"){let d=i.data.config?.actionType;d&&(a=ge(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let s=r.substring(l+1);return a?`${a}.${s}`:r}function Le({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:i}){let[a,l]=mn(!1),s=Ba(null),[d,c]=mn(e),u=Ba(!0),[f]=Oi(Ce),[v]=Oi(re),[C,h]=mn(!1),[y,m]=mn({top:0,left:0}),[b,g]=mn(""),[S,D]=mn(null),I=Ba(null);za(()=>{e!==d&&!a&&(c(e),u.current=!0)},[e,a,d]),za(()=>{!a&&d&&(u.current=!0)},[v,a,d]);let x=()=>{if(!s.current)return null;let H=window.getSelection();if(!H||H.rangeCount===0)return null;let X=H.getRangeAt(0),z=X.cloneRange();z.selectNodeContents(s.current),z.setEnd(X.endContainer,X.endOffset);let q=0,A=document.createTreeWalker(s.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),B,k=!1;for(;(B=A.nextNode())&&!k;)if(B.nodeType===Node.TEXT_NODE)if(B===X.endContainer)q+=X.endOffset,k=!0;else{let R=(B.textContent||"").length;q+=R}else if(B.nodeType===Node.ELEMENT_NODE){let R=B,_=R.getAttribute("data-template");_&&(R.contains(X.endContainer)||R===X.endContainer?(q+=_.length,k=!0):q+=_.length)}return{offset:q}},p=H=>{if(!s.current||!H)return;let X=0,z=document.createTreeWalker(s.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),q,A=null,B=0;for(;q=z.nextNode();)if(q.nodeType===Node.TEXT_NODE){let k=(q.textContent||"").length;if(X+k>=H.offset){A=q,B=H.offset-X;break}X+=k}else if(q.nodeType===Node.ELEMENT_NODE){let k=q,R=k.getAttribute("data-template");if(R){if(X+R.length>=H.offset){A=k.nextSibling,B=0,!A&&k.parentNode&&(A=document.createTextNode(""),k.parentNode.appendChild(A));break}X+=R.length}}if(A){let k=document.createRange(),R=window.getSelection();try{let _=Math.min(B,A.textContent?.length||0);k.setStart(A,_),k.collapse(!0),R?.removeAllRanges(),R?.addRange(k),s.current.focus()}catch{s.current.focus()}}},w=()=>{if(!s.current||!u.current)return;let H=s.current,X=d||"",z=a?x():null;if(I.current!==null&&(z={offset:I.current},I.current=null),H.innerHTML="",!X&&!a){H.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let q=/\{\{@([^:]+):([^}]+)\}\}/g,A=0,B;for(;(B=q.exec(X))!==null;){let[k]=B,R=B.index;if(R>A){let le=X.slice(A,R),V=document.createTextNode(le);H.appendChild(V)}let _=document.createElement("span"),ne=zu(k,v);_.className=ne?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",_.contentEditable="false",_.setAttribute("data-template",k),_.textContent=Bu(k,v),H.appendChild(_),A=q.lastIndex}if(A<X.length){let k=X.slice(A),R=document.createTextNode(k);H.appendChild(R)}H.innerHTML===""&&a&&(H.innerHTML="<br>"),u.current=!1,z&&requestAnimationFrame(()=>p(z))},G=()=>{if(!s.current)return"";let H="",X=document.createTreeWalker(s.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),z;for(;z=X.nextNode();)if(z.nodeType===Node.TEXT_NODE){let q=z.parentElement,A=!1;for(;q&&q!==s.current;){if(q.getAttribute("data-template")){A=!0;break}q=q.parentElement}A||(H+=z.textContent)}else if(z.nodeType===Node.ELEMENT_NODE){let A=z.getAttribute("data-template");A&&(H+=A)}return H},te=()=>{let H=G();if(H===d)return;let X=(d.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,z=(H.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(z>X){c(H),t?.(H),u.current=!0,h(!1),requestAnimationFrame(()=>w());return}if(z===X&&z>0){c(H),t?.(H);let A=H.lastIndexOf("@");if(A!==-1){let B=H.slice(A+1);if(B.includes(" "))h(!1);else{if(g(B),D(A),s.current){let k=s.current.getBoundingClientRect(),R={top:k.bottom+window.scrollY+4,left:k.left+window.scrollX};m(R)}h(!0)}}else h(!1);return}if(z<X){c(H),t?.(H),u.current=!0,requestAnimationFrame(()=>w());return}c(H),t?.(H);let q=H.lastIndexOf("@");if(q!==-1){let A=H.slice(q+1);if(A.includes(" "))h(!1);else{if(g(A),D(q),s.current){let B=s.current.getBoundingClientRect(),k={top:B.bottom+window.scrollY+4,left:B.left+window.scrollX};m(k)}h(!0)}}else h(!1)},O=H=>{if(!s.current||S===null)return;let X=G(),z=X.slice(0,S),q=X.slice(S+1+b.length),A=z+H+q,B=z.length+H.length;c(A),t?.(A),u.current=!0,h(!1),D(null),I.current=B,s.current.focus()},W=()=>{l(!0),u.current=!0},$=()=>{setTimeout(()=>{document.activeElement!==s.current&&(l(!1),u.current=!0,h(!1))},200)},T=H=>{H.preventDefault();let X=H.clipboardData.getData("text/plain");document.execCommand("insertText",!1,X)};return za(()=>{u.current&&w()},[d,a]),Hu(Vu,{children:[Va("div",{className:N("flex min-h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),children:Va("div",{className:"w-full outline-none",contentEditable:!n,id:i,onBlur:$,onFocus:W,onInput:te,onPaste:T,ref:s,role:"textbox",suppressContentEditableWarning:!0})}),Va(Fr,{currentNodeId:f||void 0,filter:b,isOpen:C,onClose:()=>h(!1),onSelect:O,position:y})]})}import{jsx as st,jsxs as Ao}from"react/jsx-runtime";function Li({config:e,onUpdateConfig:t,onUpdateMultipleConfig:o,disabled:n}){let r=e?.dataType||"string",i=e?.operator||yr[r][0].value,a=yr[r],s=a.find(c=>c.value===i)?.unary??!1;function d(c){let f=yr[c]?.[0]?.value??"";o?o({dataType:c,operator:f}):(t("dataType",c),f&&t("operator",f))}return Ao("div",{className:"space-y-4",children:[Ao("div",{className:"space-y-2",children:[st(M,{htmlFor:"leftValue",children:"Value to Test"}),st(Le,{disabled:n,id:"leftValue",onChange:c=>t("leftValue",c),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),st("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),Ao("div",{className:"space-y-2",children:[st(M,{htmlFor:"dataType",children:"Data Type"}),Ao(ve,{disabled:n,onValueChange:d,value:r,children:[st(he,{id:"dataType",children:st(xe,{placeholder:"Select data type"})}),st(be,{children:oi.map(c=>st(Z,{value:c.value,children:c.label},c.value))})]})]}),Ao("div",{className:"space-y-2",children:[st(M,{htmlFor:"operator",children:"Operator"}),Ao(ve,{disabled:n,onValueChange:c=>t("operator",c),value:i,children:[st(he,{id:"operator",children:st(xe,{placeholder:"Select operator"})}),st(be,{children:a.map(c=>st(Z,{value:c.value,children:c.label},c.value))})]})]}),!s&&Ao("div",{className:"space-y-2",children:[st(M,{htmlFor:"rightValue",children:"Compare Value"}),st(Le,{disabled:n,id:"rightValue",onChange:c=>t("rightValue",c),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as Mi,Trash2 as Wi}from"lucide-react";import{nanoid as Gu}from"nanoid";import{jsx as de,jsxs as Me}from"react/jsx-runtime";function co({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:Gu(),name:"",type:"string"}])},i=(c,u)=>{let f={...c};return u!=="array"&&(f.itemType=void 0),u!=="object"&&(f.fields=void 0),u!=="enum"&&(f.enumValues=void 0,f.enumItemType=void 0),u==="array"&&!f.itemType&&(f.itemType="string"),u==="object"&&!f.fields&&(f.fields=[]),u==="enum"&&!f.enumValues&&(f.enumValues=[],f.enumItemType="string"),f},a=(c,u)=>{let f=[...e];f[c]={...f[c],...u},u.type&&(f[c]=i(f[c],u.type)),t(f)},l=c=>{t(e.filter((u,f)=>f!==c))},s=(c,u)=>{let f=[...e];f[c].fields=u,t(f)},d=n>0?"ml-4 border-l-2 border-muted pl-4":"";return Me("div",{className:`space-y-3 ${d}`,children:[e.map((c,u)=>{let f=c.id||`field-${n}-${u}`;return Me("div",{className:"space-y-2 rounded-md border p-3",children:[Me("div",{className:"flex gap-2",children:[Me("div",{className:"flex-1 space-y-2",children:[de(M,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),de(ae,{disabled:o,id:`field-name-${n}-${u}`,onChange:v=>a(u,{name:v.target.value}),placeholder:"propertyName",value:c.name})]}),Me("div",{className:"flex-1 space-y-2",children:[de(M,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),Me(ve,{disabled:o,onValueChange:v=>a(u,{type:v}),value:c.type,children:[de(he,{className:"w-full",id:`field-type-${n}-${u}`,children:de(xe,{})}),Me(be,{children:[de(Z,{value:"string",children:"String"}),de(Z,{value:"number",children:"Number"}),de(Z,{value:"boolean",children:"Boolean"}),de(Z,{value:"enum",children:"Enum"}),de(Z,{value:"array",children:"Array"}),de(Z,{value:"object",children:"Object"})]})]})]}),de("div",{className:"flex items-end",children:de(E,{disabled:o,onClick:()=>l(u),size:"icon",variant:"ghost",children:de(Wi,{className:"h-4 w-4"})})})]}),c.type==="array"&&Me("div",{className:"space-y-2",children:[de(M,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),Me(ve,{disabled:o,onValueChange:v=>a(u,{itemType:v}),value:c.itemType||"string",children:[de(he,{className:"w-full",id:`field-item-type-${n}-${u}`,children:de(xe,{})}),Me(be,{children:[de(Z,{value:"string",children:"String"}),de(Z,{value:"number",children:"Number"}),de(Z,{value:"boolean",children:"Boolean"}),de(Z,{value:"object",children:"Object"})]})]})]}),c.type==="enum"&&Me("div",{className:"space-y-3",children:[Me("div",{className:"space-y-2",children:[de(M,{className:"ml-1",htmlFor:`field-enum-type-${n}-${u}`,children:"Value Type"}),Me(ve,{disabled:o,onValueChange:v=>a(u,{enumItemType:v}),value:c.enumItemType||"string",children:[de(he,{className:"w-full",id:`field-enum-type-${n}-${u}`,children:de(xe,{})}),Me(be,{children:[de(Z,{value:"string",children:"String"}),de(Z,{value:"number",children:"Number"}),de(Z,{value:"boolean",children:"Boolean"})]})]})]}),Me("div",{className:"space-y-2",children:[de(M,{className:"ml-1",children:"Allowed Values"}),(c.enumValues||[]).map((v,C)=>Me("div",{className:"flex gap-2",children:[de(ae,{disabled:o,onChange:h=>{let y=[...c.enumValues||[]];y[C]=h.target.value,a(u,{enumValues:y})},placeholder:c.enumItemType==="boolean"?"true or false":c.enumItemType==="number"?"e.g. 42":"e.g. active",value:v}),de(E,{disabled:o,onClick:()=>{let h=(c.enumValues||[]).filter((y,m)=>m!==C);a(u,{enumValues:h})},size:"icon",variant:"ghost",children:de(Wi,{className:"h-4 w-4"})})]},C)),Me(E,{className:"w-full",disabled:o,onClick:()=>{let v=[...c.enumValues||[],""];a(u,{enumValues:v})},type:"button",variant:"outline",children:[de(Mi,{className:"size-4"}),"Add Value"]})]})]}),c.type==="object"&&Me("div",{className:"mt-2",children:[de(M,{className:"mb-2 block",children:"Object Properties"}),de(co,{disabled:o,level:n+1,onChange:v=>s(u,v),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&&Me("div",{className:"mt-2",children:[de(M,{className:"mb-2 block",children:"Array Item Properties"}),de(co,{disabled:o,level:n+1,onChange:v=>s(u,v),schema:c.fields||[]})]}),Me("div",{className:"space-y-2",children:[de(M,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),de(ae,{disabled:o,id:`field-desc-${n}-${u}`,onChange:v=>a(u,{description:v.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},f)}),Me(E,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[de(Mi,{className:"size-4"}),"Add Property"]})]})}import{Fragment as $u,jsx as pn,jsxs as Ha}from"react/jsx-runtime";function Fi({config:e,onUpdateConfig:t,disabled:o}){return Ha($u,{children:[Ha("div",{className:"space-y-2",children:[pn(M,{htmlFor:"dbQuery",children:"SQL Query"}),pn("div",{className:"overflow-hidden rounded-md border",children:pn(yt,{defaultLanguage:"sql",height:"150px",onChange:n=>t("dbQuery",n||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.dbQuery||""})}),pn("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),Ha("div",{className:"space-y-2",children:[pn(M,{children:"Schema (Optional)"}),pn(co,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as _u,jsx as Ke,jsxs as Io}from"react/jsx-runtime";function zi({config:e,onUpdateConfig:t,disabled:o}){return Io(_u,{children:[Io("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpMethod",children:"HTTP Method"}),Io(ve,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[Ke(he,{className:"w-full",id:"httpMethod",children:Ke(xe,{placeholder:"Select method"})}),Io(be,{children:[Ke(Z,{value:"GET",children:"GET"}),Ke(Z,{value:"POST",children:"POST"}),Ke(Z,{value:"PUT",children:"PUT"}),Ke(Z,{value:"PATCH",children:"PATCH"}),Ke(Z,{value:"DELETE",children:"DELETE"})]})]})]}),Io("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"endpoint",children:"URL"}),Ke(Le,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),Io("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),Ke("div",{className:"overflow-hidden rounded-md border",children:Ke(yt,{defaultLanguage:"json",height:"100px",onChange:n=>t("httpHeaders",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"off"},value:e?.httpHeaders||"{}"})})]}),Io("div",{className:"space-y-2",children:[Ke(M,{htmlFor:"httpBody",children:"Body (JSON)"}),Ke("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:Ke(yt,{defaultLanguage:"json",height:"120px",onChange:n=>t("httpBody",n||"{}"),options:{minimap:{enabled:!1},lineNumbers:"off",scrollBeyondLastLine:!1,fontSize:12,readOnly:e?.httpMethod==="GET"||o,domReadOnly:e?.httpMethod==="GET"||o,wordWrap:"off"},value:e?.httpBody||"{}"})}),e?.httpMethod==="GET"&&Ke("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as fn,jsxs as Ga}from"react/jsx-runtime";function Bi({config:e,onUpdateConfig:t,disabled:o}){return Ga("div",{className:"space-y-4",children:[Ga("div",{className:"space-y-2",children:[fn(M,{htmlFor:"items",children:"Items to Iterate"}),fn(Le,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),fn("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),Ga("div",{className:"space-y-2",children:[fn(M,{htmlFor:"batchSize",children:"Batch Size (optional)"}),fn(Le,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),fn("p",{className:"text-muted-foreground text-xs",children:"Number of items per batch. Default is 1 (process one item at a time)."})]})]})}import{Minus as Uu,Plus as Ku}from"lucide-react";import{Fragment as qu,jsx as Te,jsxs as qe}from"react/jsx-runtime";function Vi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append",r=Number(e?.inputCount)||2,i=()=>{t("inputCount",String(r+1))},a=()=>{if(r<=2)return;t(`input${r}`,""),t("inputCount",String(r-1))};return qe("div",{className:"space-y-4",children:[qe("div",{className:"space-y-2",children:[Te(M,{htmlFor:"mode",children:"Mode"}),qe(ve,{disabled:o,onValueChange:l=>t("mode",l),value:n,children:[Te(he,{id:"mode",children:Te(xe,{placeholder:"Select mode"})}),qe(be,{children:[Te(Z,{value:"append",children:"Append"}),Te(Z,{value:"combineByPosition",children:"Combine by Position"}),Te(Z,{value:"combineByFields",children:"Combine by Fields"})]})]}),qe("p",{className:"text-muted-foreground text-xs",children:[n==="append"&&"Concatenate all lists into one.",n==="combineByPosition"&&"Merge items at the same index from all inputs.",n==="combineByFields"&&"Match and merge items based on a common field."]})]}),Array.from({length:r},(l,s)=>qe("div",{className:"space-y-2",children:[qe(M,{htmlFor:`input${s+1}`,children:["Input ",s+1]}),Te(Le,{disabled:o,id:`input${s+1}`,onChange:d=>t(`input${s+1}`,d),placeholder:"e.g., {{Node.rows}}",value:e?.[`input${s+1}`]||""}),s===0&&Te("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference outputs from previous nodes."})]},s)),qe("div",{className:"flex gap-2",children:[qe(E,{className:"flex-1",disabled:o,onClick:i,type:"button",variant:"outline",children:[Te(Ku,{className:"mr-2 size-4"}),"Add Input"]}),Te(E,{disabled:o||r<=2,onClick:a,type:"button",variant:"outline",children:Te(Uu,{className:"size-4"})})]}),n==="combineByPosition"&&qe("div",{className:"space-y-2",children:[Te(M,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),qe(ve,{disabled:o,onValueChange:l=>t("unmatchedHandling",l),value:e?.unmatchedHandling||"useNull",children:[Te(he,{id:"unmatchedHandling",children:Te(xe,{})}),qe(be,{children:[Te(Z,{value:"useNull",children:"Fill with null"}),Te(Z,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&qe(qu,{children:[qe("div",{className:"space-y-2",children:[Te(M,{htmlFor:"matchField",children:"Match Field"}),Te(Le,{disabled:o,id:"matchField",onChange:l=>t("matchField1",l),placeholder:"e.g., id",value:e?.matchField1||""}),Te("p",{className:"text-muted-foreground text-xs",children:"Field name to match items on across all inputs."})]}),qe("div",{className:"space-y-2",children:[Te(M,{htmlFor:"joinType",children:"Join Type"}),qe(ve,{disabled:o,onValueChange:l=>t("joinType",l),value:e?.joinType||"inner",children:[Te(he,{id:"joinType",children:Te(xe,{})}),qe(be,{children:[Te(Z,{value:"inner",children:"Inner Join"}),Te(Z,{value:"leftOuter",children:"Left Outer Join"}),Te(Z,{value:"rightOuter",children:"Right Outer Join"}),Te(Z,{value:"fullOuter",children:"Full Outer Join"})]})]}),Te("p",{className:"text-muted-foreground text-xs",children:"Inner keeps only matches. Left/Right keeps all items from that input. Full keeps everything."})]})]})]})}import{Loader2 as ju}from"lucide-react";import{useEffect as Ju,useState as Hi}from"react";import{jsx as $t,jsxs as _n}from"react/jsx-runtime";function Gi({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=Hi([]),[i,a]=Hi(!0);Ju(()=>{async function s(){try{let d=await fetch("/api/workflow-builder/workflows");if(d.ok){let c=await d.json();r((c.workflows||c||[]).map(u=>({id:u.id,name:u.name})))}}catch{}finally{a(!1)}}s()},[]);let l=e?.workflowId||"";return _n("div",{className:"space-y-4",children:[_n("div",{className:"space-y-2",children:[$t(M,{htmlFor:"workflowId",children:"Workflow"}),i?_n("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[$t(ju,{className:"size-4 animate-spin"}),"Loading workflows..."]}):_n(ve,{disabled:o||n.length===0,onValueChange:s=>t("workflowId",s),value:l||void 0,children:[$t(he,{className:"w-full",id:"workflowId",children:$t(xe,{placeholder:n.length===0?"No workflows found":"Select a workflow"})}),$t(be,{children:n.map(s=>$t(Z,{value:s.id,children:s.name},s.id))})]}),$t("p",{className:"text-muted-foreground text-xs",children:"The workflow to execute. It will run inline and wait for completion."})]}),_n("div",{className:"space-y-2",children:[$t(M,{htmlFor:"input",children:"Input (optional JSON)"}),$t(Le,{disabled:o,id:"input",onChange:s=>t("input",s),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),$t("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to the sub-workflow."})]})]})}import{ArrowDown as Yu,ArrowUp as Xu,Loader2 as Qu,Plus as Zu,Trash2 as em}from"lucide-react";import{useEffect as tm,useState as $i}from"react";import{jsx as Oe,jsxs as Ct}from"react/jsx-runtime";function _i({config:e,onUpdateConfig:t,disabled:o}){let[n,r]=$i([]),[i,a]=$i(!0);tm(()=>{async function m(){try{let b=await fetch("/api/workflow-builder/workflows");if(b.ok){let g=await b.json();r((g.workflows||g||[]).map(S=>({id:S.id,name:S.name})))}}catch{}finally{a(!1)}}m()},[]);let l=e?.workflowIds||"[]",s=[];try{let m=JSON.parse(l);Array.isArray(m)&&(s=m)}catch{s=l.split(",").map(m=>m.trim()).filter(Boolean)}let d=m=>{t("workflowIds",JSON.stringify(m))},c=m=>{m&&!s.includes(m)&&d([...s,m])},u=m=>{let b=[...s];b.splice(m,1),d(b)},f=m=>{if(m===0)return;let b=[...s];[b[m-1],b[m]]=[b[m],b[m-1]],d(b)},v=m=>{if(m===s.length-1)return;let b=[...s];[b[m],b[m+1]]=[b[m+1],b[m]],d(b)},C=m=>n.find(b=>b.id===m)?.name||m,h=n.filter(m=>!s.includes(m.id)),y=e?.continueOnFailure||"false";return Ct("div",{className:"space-y-4",children:[Ct("div",{className:"space-y-2",children:[Oe(M,{children:"Workflows (executed in order)"}),i?Ct("div",{className:"flex items-center gap-2 rounded-md border px-3 py-2 text-muted-foreground text-sm",children:[Oe(Qu,{className:"size-4 animate-spin"}),"Loading workflows..."]}):Ct("div",{className:"space-y-1",children:[s.map((m,b)=>Ct("div",{className:"flex items-center gap-1 rounded-md border bg-muted/30 px-2 py-1.5 text-sm",children:[Ct("span",{className:"w-5 shrink-0 text-center text-muted-foreground text-xs",children:[b+1,"."]}),Oe("span",{className:"min-w-0 flex-1 truncate",children:C(m)}),Oe(E,{className:"size-6",disabled:o||b===0,onClick:()=>f(b),size:"icon",variant:"ghost",children:Oe(Xu,{className:"size-3"})}),Oe(E,{className:"size-6",disabled:o||b===s.length-1,onClick:()=>v(b),size:"icon",variant:"ghost",children:Oe(Yu,{className:"size-3"})}),Oe(E,{className:"size-6 text-destructive hover:text-destructive",disabled:o,onClick:()=>u(b),size:"icon",variant:"ghost",children:Oe(em,{className:"size-3"})})]},`${m}-${b}`)),h.length>0&&Ct(ve,{disabled:o,onValueChange:c,value:"",children:[Oe(he,{className:N("w-full",s.length>0&&"border-dashed"),children:Ct("div",{className:"flex items-center gap-1.5 text-muted-foreground",children:[Oe(Zu,{className:"size-3.5"}),Oe("span",{children:"Add workflow..."})]})}),Oe(be,{children:h.map(m=>Oe(Z,{value:m.id,children:m.name},m.id))})]}),!i&&n.length===0&&Oe("p",{className:"text-muted-foreground text-xs",children:"No workflows found."})]})]}),Ct("div",{className:"space-y-2",children:[Oe(M,{htmlFor:"continueOnFailure",children:"On failure"}),Ct(ve,{disabled:o,onValueChange:m=>t("continueOnFailure",m),value:y,children:[Oe(he,{className:"w-full",id:"continueOnFailure",children:Oe(xe,{})}),Ct(be,{children:[Oe(Z,{value:"false",children:"Stop sequence"}),Oe(Z,{value:"true",children:"Continue with next workflow"})]})]})]}),Ct("div",{className:"space-y-2",children:[Oe(M,{htmlFor:"sequenceInput",children:"Input (optional JSON, passed to all workflows)"}),Oe(Le,{disabled:o,id:"sequenceInput",onChange:m=>t("input",m),placeholder:'{"key": "value"} or {{PreviousNode.field}}',value:e?.input||""}),Oe("p",{className:"text-muted-foreground text-xs",children:"Optional JSON passed as trigger input to every workflow in the sequence."})]})]})}import{Minus as om,Plus as nm}from"lucide-react";import{jsx as He,jsxs as vt}from"react/jsx-runtime";function Ui({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules",r=Number(e?.routeCount)||4,i=()=>{t("routeCount",String(r+1))},a=()=>{if(r<=1)return;let l=r-1;t(`routeName${l}`,""),t(`routeCondition${l}`,""),t(`routeCaseValue${l}`,""),t("routeCount",String(r-1))};return vt("div",{className:"space-y-4",children:[vt("div",{className:"space-y-2",children:[He(M,{htmlFor:"mode",children:"Mode"}),vt(ve,{disabled:o,onValueChange:l=>t("mode",l),value:n,children:[He(he,{id:"mode",children:He(xe,{placeholder:"Select mode"})}),vt(be,{children:[He(Z,{value:"rules",children:"Rules"}),He(Z,{value:"expression",children:"Expression"})]})]}),vt("p",{className:"text-muted-foreground text-xs",children:[n==="rules"&&"Each route has a condition. The first route whose condition is true wins.",n==="expression"&&"Compare a value against each route's case value. First match wins."]})]}),n==="expression"&&vt("div",{className:"space-y-2",children:[He(M,{htmlFor:"switchValue",children:"Value to Switch On"}),He(Le,{disabled:o,id:"switchValue",onChange:l=>t("switchValue",l),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),He("p",{className:"text-muted-foreground text-xs",children:"The value to compare against each route's case value. Use @ to reference previous node outputs."})]}),Array.from({length:r},(l,s)=>vt("div",{className:"space-y-3 rounded-md border p-3",children:[vt("p",{className:"font-medium text-sm",children:["Route ",s+1]}),vt("div",{className:"space-y-2",children:[He(M,{htmlFor:`routeName${s}`,children:"Name (optional)"}),He(ae,{disabled:o,id:`routeName${s}`,onChange:d=>t(`routeName${s}`,d.target.value),placeholder:`Route ${s+1}`,value:e?.[`routeName${s}`]||""})]}),n==="rules"&&vt("div",{className:"space-y-2",children:[He(M,{htmlFor:`routeCondition${s}`,children:"Condition"}),He(Le,{disabled:o,id:`routeCondition${s}`,onChange:d=>t(`routeCondition${s}`,d),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${s}`]||""})]}),n==="expression"&&vt("div",{className:"space-y-2",children:[He(M,{htmlFor:`routeCaseValue${s}`,children:"Case Value"}),He(Le,{disabled:o,id:`routeCaseValue${s}`,onChange:d=>t(`routeCaseValue${s}`,d),placeholder:`e.g., ${s===0?"200":s===1?"404":"500"}`,value:e?.[`routeCaseValue${s}`]||""})]})]},s)),vt("div",{className:"flex gap-2",children:[vt(E,{className:"flex-1",disabled:o,onClick:i,type:"button",variant:"outline",children:[He(nm,{className:"mr-2 size-4"}),"Add Route"]}),He(E,{disabled:o||r<=1,onClick:a,type:"button",variant:"outline",children:He(om,{className:"size-4"})})]}),He("p",{className:"text-muted-foreground text-xs",children:'Routes are evaluated in order. The first matching route wins. If no route matches, the result falls back to "Default".'})]})}import{atom as zr}from"jotai";var Br=zr(null),Ki=zr([]),qi=zr(!1),Yw=zr(!1);import{useAtomValue as Qi,useSetAtom as $a}from"jotai";import{Search as dm}from"lucide-react";import{useCallback as cm,useMemo as um,useState as gn}from"react";import{toast as Eo}from"sonner";import{atom as Un,useSetAtom as rm}from"jotai";import*as Ji from"react";var ji=null;var Po=Un(null),Vr=Un([]),Hr=Un(!1),Yi=Un(!1),jt=Un(null);function Xi(){let e=rm(jt);Ji.useEffect(()=>{ji&&e(ji)},[e])}import{Database as am,HelpCircle as sm}from"lucide-react";import{jsx as Kn}from"react/jsx-runtime";function im({className:e}){return Kn("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:Kn("path",{d:"m577.3 0 577.4 1000H0z"})})}var lm={database:am,vercel:im};function Wt({integration:e,className:t="h-3 w-3"}){let o=lm[e];if(o)return Kn(o,{className:N("text-foreground",t)});let n=Rt(e);if(n?.icon){let r=n.icon;return Kn(r,{className:N("text-foreground",t)})}return Kn(sm,{className:N("text-foreground",t)})}import{jsx as Ge,jsxs as ht}from"react/jsx-runtime";var mm=["database"],pm={database:"Database"},fm={database:"Connect to PostgreSQL databases"},gm=()=>[...ei(),...mm],_a=e=>to()[e]||pm[e]||e,ym=e=>Zs()[e]||fm[e]||"";function el({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=oe(),[r,i]=gn(""),a=Gt(),l=Qi(jt),s=Qi(Po),d=$a(Po),c=$a(Vr),u=$a(Hr),f=gm(),v=um(()=>{if(!r.trim())return f;let y=r.toLowerCase();return f.filter(m=>_a(m).toLowerCase().includes(y))},[f,r]),C=cm(()=>{l&&o(l.ConsentOverlay,{onConsent:y=>{t?.(y),n()}})},[l,o,n,t]),h=y=>{let m=l?.integrationType===y;if(m&&s?.enabled&&s?.isVercelUser){C();return}if(m&&s===null){l.api.getStatus().then(g=>{d(g),g?.enabled&&g?.isVercelUser?(u(!0),l.api.getTeams().then(S=>{c(S.teams)}).finally(()=>{u(!1),C()})):o(uo,{type:y,onSuccess:t})});return}o(uo,{type:y,onSuccess:t})};return ht(Re,{overlayId:e,title:"Add Connection",children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),ht("div",{className:"space-y-3",children:[ht("div",{className:"relative",children:[Ge(dm,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ge(ae,{autoFocus:!a,className:"pl-9",onChange:y=>i(y.target.value),placeholder:"Search services...",value:r})]}),Ge("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:v.length===0?Ge("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):v.map(y=>{let m=ym(y);return ht("button",{className:"flex w-full items-center gap-3 rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted/50",onClick:()=>h(y),type:"button",children:[Ge(Wt,{className:"size-5 shrink-0",integration:y==="ai-gateway"?"vercel":y}),ht("span",{className:"min-w-0 flex-1 truncate",children:[Ge("span",{className:"font-medium",children:_a(y)}),m&&ht("span",{className:"text-muted-foreground text-xs",children:[" ","- ",m]})]})]},y)})})]})]})}function Zi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:i,value:a,onChange:l}){return ht("div",{className:"space-y-2",children:[Ge(M,{htmlFor:e,children:t}),Ge(ae,{className:"flex-1",id:e,onChange:s=>l(o,s.target.value),placeholder:n,type:"password",value:a}),(r||i)&&ht("p",{className:"text-muted-foreground text-xs",children:[r,i&&Ge("a",{className:"underline hover:text-foreground",href:i.url,rel:"noopener noreferrer",target:"_blank",children:i.text})]})]})}function uo({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=oe(),[i,a]=gn(!1),[l,s]=gn(!1),[d,c]=gn(null),[u,f]=gn(""),[v,C]=gn({}),h=(I,x)=>{C(p=>({...p,[I]:x}))},y=async()=>{try{a(!0);let I=await j.integration.create({name:u.trim(),type:t,config:v});Eo.success("Connection created"),o?.(I.id),r()}catch(I){console.error("Failed to save integration:",I),Eo.error("Failed to save connection")}finally{a(!1)}},m=async()=>{if(!Object.values(v).some(x=>x&&x.length>0)){Eo.error("Please enter credentials");return}try{a(!0),c(null);let x=await j.integration.testCredentials({type:t,config:v});if(x.status==="error"){n(Pe,{title:"Connection Test Failed",message:`The test failed: ${x.message}
|
|
3
3
|
|
|
4
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1);return}await y()}catch(
|
|
4
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1);return}await y()}catch(x){let p=x instanceof Error?x.message:"Failed to test connection";n(Pe,{title:"Connection Test Failed",message:`${p}
|
|
5
5
|
|
|
6
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1)}},
|
|
6
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1)}},b=async()=>{if(!Object.values(v).some(x=>x&&x.length>0)){Eo.error("Please enter credentials first");return}try{s(!0),c(null);let x=await j.integration.testCredentials({type:t,config:v});c(x),x.status==="success"?Eo.success(x.message||"Connection successful"):Eo.error(x.message||"Connection failed")}catch(x){let p=x instanceof Error?x.message:"Connection test failed";c({status:"error",message:p}),Eo.error(p)}finally{s(!1)}},S=Rt(t)?.formFields,D=()=>t==="database"?Ge(Zi,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:h,placeholder:"postgresql://user:password@host:port/database",value:v.url||""}):S?S.map(I=>I.type==="password"?Ge(Zi,{configKey:I.configKey,fieldId:I.id,helpLink:I.helpLink,helpText:I.helpText,label:I.label,onChange:h,placeholder:I.placeholder,value:v[I.configKey]||""},I.id):ht("div",{className:"space-y-2",children:[Ge(M,{htmlFor:I.id,children:I.label}),Ge(ae,{id:I.id,onChange:x=>h(I.configKey,x.target.value),placeholder:I.placeholder,type:I.type,value:v[I.configKey]||""}),(I.helpText||I.helpLink)&&ht("p",{className:"text-muted-foreground text-xs",children:[I.helpText,I.helpLink&&Ge("a",{className:"underline hover:text-foreground",href:I.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:I.helpLink.text})]})]},I.id)):null;return ht(Re,{actions:[{label:"Test",variant:"outline",onClick:b,loading:l,disabled:i},{label:"Create",onClick:m,loading:i}],overlayId:e,title:`Add ${_a(t)}`,children:[Ge("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Enter your credentials"}),ht("div",{className:"space-y-4",children:[D(),ht("div",{className:"space-y-2",children:[Ge(M,{htmlFor:"name",children:"Label (Optional)"}),Ge(ae,{id:"name",onChange:I=>f(I.target.value),placeholder:"e.g. Production, Personal, Work",value:u})]})]})]})}import{useAtomValue as tl,useSetAtom as vm}from"jotai";import{Loader2 as hm,Sparkles as bm,X as wm}from"lucide-react";import{useCallback as Gr,useEffect as xm,useState as Ua}from"react";import{jsx as je,jsxs as mo}from"react/jsx-runtime";function ol({overlayId:e,onConsent:t,onManualEntry:o,onDecline:n}){let{pop:r}=oe(),i=vm(Br),[a,l]=Ua(!1),[s,d]=Ua(null),[c,u]=Ua(""),f=tl(Ki),v=tl(qi);xm(()=>{f.length>0&&!c&&u(f[0].id)},[f,c]);let C=Gr(g=>{l(!1),t?.(g),r()},[t,r]),h=Gr(async()=>{if(!c){d("Please select a team");return}let S=f.find(D=>D.id===c)?.name||"AI Gateway";l(!0),d(null);try{let D=await j.aiGateway.consent(c,S);if(!D.success)throw new Error(D.error||"Failed to set up AI Gateway");let I=D.managedIntegrationId||"";i(x=>x?{...x,hasManagedKey:D.hasManagedKey,managedIntegrationId:I}:null),C(I)}catch(D){d(D instanceof Error?D.message:"An error occurred"),l(!1)}},[c,f,i,C]),y=Gr(()=>{n?.(),r()},[n,r]),m=Gr(()=>{o?.()},[o]),b=[...o?[{label:"Enter manually",variant:"ghost",onClick:m,disabled:a}]:[],{label:"Cancel",variant:"outline",onClick:y,disabled:a},{label:a?"Setting up...":"Agree & Connect",variant:"default",onClick:h,disabled:a||v&&f.length===0||!c,loading:a}];return je(Re,{actions:b,description:"Connect your Vercel account to use your own AI Gateway balance",overlayId:e,title:"Use Your AI Gateway Credits",children:mo("div",{className:"space-y-4",children:[mo("div",{className:"flex items-start gap-3",children:[je("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/10",children:je(bm,{className:"size-5 text-primary"})}),je("p",{className:"pt-2 text-muted-foreground text-sm",children:"This will create an API key on your Vercel account that uses your AI Gateway credits for AI operations in workflows."})]}),mo("div",{className:"space-y-2",children:[je(M,{htmlFor:"team-select",children:"Vercel Team"}),v&&f.length===0?mo("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3 text-muted-foreground text-sm",children:[je(hm,{className:"size-4 animate-spin"}),"Loading teams..."]}):mo(ve,{disabled:a,onValueChange:u,value:c,children:[je(he,{id:"team-select",children:je(xe,{placeholder:"Select a team"})}),je(be,{children:f.map((g,S)=>mo("div",{children:[je(Z,{value:g.id,children:mo("div",{className:"flex items-center gap-2",children:[g.avatar?je("img",{alt:"",className:"size-4 rounded-full bg-white",src:g.avatar}):je("div",{className:"size-4 rounded-full bg-white"}),je("span",{children:g.name}),g.isPersonal&&je("span",{className:"text-muted-foreground text-xs",children:"(Personal)"})]})}),g.isPersonal&&S<f.length-1&&je(Lr,{})]},g.id))})]})]}),s&&mo("div",{className:"flex items-start gap-3 rounded-md border border-red-500/30 bg-red-500/10 p-3",children:[je(wm,{className:"mt-0.5 size-4 shrink-0 text-red-500"}),je("p",{className:"text-red-700 text-sm dark:text-red-400",children:s})]})]})})}import{useAtom as Ur,useAtomValue as al,useSetAtom as sl}from"jotai";import{AlertTriangle as Pm,Check as ja,Circle as il,Pencil as Ja,Plus as Em,Settings as Dm}from"lucide-react";import{useCallback as qn,useEffect as yn,useMemo as Rm,useRef as Om,useState as ll}from"react";import{useAtomValue as km}from"jotai";import{Check as Cm,Pencil as Tm,X as Sm}from"lucide-react";import{useState as po}from"react";import{toast as Do}from"sonner";import*as $r from"@radix-ui/react-checkbox";import{CheckIcon as Nm}from"lucide-react";import{jsx as Ka}from"react/jsx-runtime";function nl({className:e,...t}){return Ka($r.Root,{"data-slot":"checkbox",className:N("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:Ka($r.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:Ka(Nm,{className:"size-3.5"})})})}import{jsx as Fe,jsxs as ut}from"react/jsx-runtime";var Am={database:"Database"},Im=e=>to()[e]||Am[e]||e;function rl({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:i,value:a,onChange:l}){let[s,d]=po(!1),c=Gt(),u=a.length>0;return s||u?ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:e,children:t}),ut("div",{className:"flex items-center gap-2",children:[Fe(ae,{autoFocus:s&&!c,className:"flex-1",id:e,onChange:f=>l(o,f.target.value),placeholder:n,type:"password",value:a}),(s||u)&&Fe(E,{onClick:()=>{l(o,""),d(!1)},size:"icon",type:"button",variant:"ghost",children:Fe(Sm,{className:"size-4"})})]}),(r||i)&&ut("p",{className:"text-muted-foreground text-xs",children:[r,i&&Fe("a",{className:"underline hover:text-foreground",href:i.url,rel:"noopener noreferrer",target:"_blank",children:i.text})]})]}):ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:e,children:t}),ut("div",{className:"flex items-center gap-2",children:[ut("div",{className:"flex h-9 flex-1 items-center gap-2 rounded-md border bg-muted/30 px-3",children:[Fe(Cm,{className:"size-4 text-green-600"}),Fe("span",{className:"text-muted-foreground text-sm",children:"Configured"})]}),ut(E,{onClick:()=>d(!0),type:"button",variant:"outline",children:[Fe(Tm,{className:"mr-1.5 size-3"}),"Change"]})]})]})}function _r({overlayId:e,integration:t,onSuccess:o,onDelete:n}){let{push:r,closeAll:i}=oe(),[a,l]=po(!1),[s,d]=po(!1),[c,u]=po(null),[f,v]=po(t.name),[C,h]=po({}),y=(p,w)=>{h(G=>({...G,[p]:w}))},m=async()=>{try{l(!0);let p=Object.values(C).some(w=>w&&w.length>0);await j.integration.update(t.id,{name:f.trim(),...p?{config:C}:{}}),Do.success("Connection updated"),o?.(),i()}catch(p){console.error("Failed to update integration:",p),Do.error("Failed to update connection")}finally{l(!1)}},b=async()=>{if(!Object.values(C).some(w=>w&&w.length>0)){await m();return}try{l(!0),u(null);let w=await j.integration.testCredentials({type:t.type,config:C});if(w.status==="error"){r(Pe,{title:"Connection Test Failed",message:`The test failed: ${w.message}
|
|
7
7
|
|
|
8
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await
|
|
8
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await m()}}),l(!1);return}await m()}catch(w){let G=w instanceof Error?w.message:"Failed to test connection";r(Pe,{title:"Connection Test Failed",message:`${G}
|
|
9
9
|
|
|
10
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await p()}}),d(!1)}},g=async()=>{let m=Object.values(k).some(S=>S&&S.length>0);try{l(!0),u(null);let S;m?S=await q.integration.testCredentials({type:t.type,config:k}):S=await q.integration.testConnection(t.id),u(S),S.status==="success"?Po.success(S.message||"Connection successful"):Po.error(S.message||"Connection failed")}catch(S){let X=S instanceof Error?S.message:"Connection test failed";u({status:"error",message:X}),Po.error(X)}finally{l(!1)}},C=()=>{r(_a,{integration:t,onSuccess:()=>{n?.(),s()}})},A=Dt(t.type)?.formFields,w=()=>t.type==="database"?We(tl,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:y,placeholder:"postgresql://user:password@host:port/database",value:k.url||""}):A?A.map(m=>m.type==="password"?We(tl,{configKey:m.configKey,fieldId:m.id,helpLink:m.helpLink,helpText:m.helpText,label:m.label,onChange:y,placeholder:m.placeholder,value:k[m.configKey]||""},m.id):ut("div",{className:"space-y-2",children:[We(M,{htmlFor:m.id,children:m.label}),We(se,{id:m.id,onChange:S=>y(m.configKey,S.target.value),placeholder:m.placeholder,type:m.type,value:k[m.configKey]||""}),(m.helpText||m.helpLink)&&ut("p",{className:"text-muted-foreground text-xs",children:[m.helpText,m.helpLink&&We("a",{className:"underline hover:text-foreground",href:m.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:m.helpLink.text})]})]},m.id)):null;return ut(Oe,{actions:[{label:"Delete",variant:"ghost",onClick:C,disabled:a||i},{label:"Test",variant:"outline",onClick:g,loading:i,disabled:a},{label:"Update",onClick:v,loading:a}],overlayId:e,title:`Edit ${Cm(t.type)}`,children:[We("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),ut("div",{className:"space-y-4",children:[w(),ut("div",{className:"space-y-2",children:[We(M,{htmlFor:"name",children:"Label (Optional)"}),We(se,{id:"name",onChange:m=>h(m.target.value),placeholder:"e.g. Production, Personal, Work",value:f})]})]})]})}function _a({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=re(),r=bm(Kt),[s,a]=mo(!1),[d,i]=mo(!0);return ut(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:"Delete",variant:"destructive",onClick:async()=>{try{a(!0),t.isManaged&&d&&r?await r.api.revokeConsent():await q.integration.delete(t.id),Po.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Po.error("Failed to delete connection"),a(!1)}},loading:s}],overlayId:e,title:"Delete Connection",children:[We("p",{className:"text-muted-foreground text-sm",children:"Are you sure you want to delete this connection? Workflows using it will fail until a new one is configured."}),t.isManaged&&ut("div",{className:"mt-4 flex items-center gap-2",children:[We(el,{checked:d,id:"revoke-key",onCheckedChange:c=>i(c)}),We(M,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as qa,jsx as Se,jsxs as Ht}from"react/jsx-runtime";function sl({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:s}){let{push:a}=re(),[d,i]=Gr(ft),l=ol(Rt),c=nl(Rt),u=Pm(l),[f,h]=al(!1),k=ol(Kt),[b,y]=Gr(Ao),[p,v]=al(!1),[g,C]=Gr(Mr),[I,A]=Gr(zi),w=nl(Fr),m=Im(()=>d.filter(N=>N.type===e),[d,e]),S=d.length>0,X=Hn(async()=>{try{let N=await q.integration.getAll();i(N),h(!0)}catch(N){console.error("Failed to load integrations:",N)}},[i]);pn(()=>{k?.integrationType===e&&!p&&k.api.getStatus().then(N=>{y(N),v(!0)}).catch(()=>{v(!0)})},[e,p,k,y]),pn(()=>{k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&!I&&(w(!0),k.api.getTeams().then(N=>{C(N.teams),N.teams.length>0&&A(!0)}).catch(()=>{}).finally(()=>{w(!1)}))},[e,k,b,I,C,A,w]),pn(()=>{k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&k.api.getTeams().then(N=>{N.teams.length>0&&(C(N.teams),A(!0))}).catch(()=>{})},[e,k,b?.enabled,b?.isVercelUser]),pn(()=>{X()},[X,e]),pn(()=>{l!==u.current&&(u.current=l,X())},[l,X]),pn(()=>{if(m.length>0&&!r&&!(t&&m.some(R=>R.id===t))){let R=m.find(G=>G.isManaged);o(R?.id||m[0].id)}},[m,t,r,o]);let le=async N=>{await X(),o(N),c(R=>R+1)},L=async()=>{if(await X(),c(N=>N+1),k?.integrationType===e){let N=await k.api.getStatus();y(N)}},W=Hn(()=>{a(co,{type:e,onSuccess:le})},[e,a,le]),$=Hn(N=>{a(Vr,{integration:N,onSuccess:L,onDelete:L})},[a,L]),P=k?.integrationType===e&&b?.enabled&&b?.isVercelUser&&!b?.hasManagedKey,V=Hn(async N=>{if(await X(),o(N),c(R=>R+1),k){let R=await k.api.getStatus();y(R)}},[X,o,c,k,y]),J=Hn(()=>{s?s():P&&k?a(k.ConsentOverlay,{onConsent:V,onManualEntry:W}):W()},[s,P,k,a,V,W]);if(!S&&!f)return Se("div",{className:"flex flex-col gap-1",children:Ht("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5",children:[Se("div",{className:"size-4 shrink-0 animate-pulse rounded-full bg-muted"}),Se("div",{className:"h-4 flex-1 animate-pulse rounded bg-muted"}),Se("div",{className:"size-6 shrink-0 animate-pulse rounded bg-muted"})]})});let K=Dt(e)?.label||e,T=m.filter(N=>N.isManaged),z=m.filter(N=>!N.isManaged);if(m.length===0)return Se(qa,{children:Ht(D,{className:"w-full justify-start gap-2 border-orange-500/50 bg-orange-500/10 text-orange-600 hover:bg-orange-500/20 dark:text-orange-400",disabled:r,onClick:J,variant:"outline",children:[Se(Tm,{className:"size-4"}),Ht("span",{className:"flex-1 text-left",children:["Add ",K," connection"]}),Se(Am,{className:"size-4"})]})});if(m.length===1){let N=m[0],R=N.name||`${K} API Key`;return Se(qa,{children:Ht("div",{className:x("flex h-9 w-full items-center gap-2 rounded-md border px-3 text-sm",r&&"cursor-not-allowed opacity-50"),children:[Se(Ua,{className:"size-4 shrink-0 text-green-600"}),Se("span",{className:"flex-1 truncate",children:R}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:()=>$(N),size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]})})}return Se(qa,{children:Ht("div",{className:"flex flex-col gap-1",children:[T.map(N=>{let R=t===N.id,G=N.name||`${K} API Key`;return Ht("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Ht("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(N.id),type:"button",children:[R?Se(Ua,{className:"size-4 shrink-0"}):Se(rl,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:oe=>{oe.stopPropagation(),$(N)},size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]},N.id)}),z.map(N=>{let R=t===N.id,G=N.name||`${K} API Key`;return Ht("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Ht("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(N.id),type:"button",children:[R?Se(Ua,{className:"size-4 shrink-0"}):Se(rl,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(D,{className:"size-6 shrink-0",disabled:r,onClick:oe=>{oe.stopPropagation(),$(N)},size:"icon",variant:"ghost",children:Se(Ka,{className:"size-3"})})]},N.id)}),n&&Ht("button",{className:"flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted/50 hover:text-foreground",disabled:r,onClick:n,type:"button",children:[Se(Sm,{className:"size-4 shrink-0"}),Se("span",{children:"Manage all connections"})]})]})})}import*as Ct from"@radix-ui/react-tooltip";import{jsx as fn,jsxs as Em}from"react/jsx-runtime";function gn({delayDuration:e=0,...t}){return fn(Ct.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function $n({...e}){return fn(gn,{children:fn(Ct.Root,{"data-slot":"tooltip",...e})})}function _n({...e}){return fn(Ct.Trigger,{"data-slot":"tooltip-trigger",...e})}function Un({className:e,sideOffset:t=0,children:o,...n}){return fn(Ct.Portal,{children:Em(Ct.Content,{"data-slot":"tooltip-content",sideOffset:t,className:x("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[o,fn(Ct.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as Mm}from"lucide-react";import{useState as Fm}from"react";import{useAtom as il}from"jotai";import{useEffect as ja,useRef as Ja,useState as yn}from"react";import{Fragment as Om,jsx as Ya,jsxs as Lm}from"react/jsx-runtime";function Dm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Rm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(l=>l.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let l=s.data.config?.actionType;l&&(a=fe(l)?.label)}let d=r.indexOf(".");if(d===-1)return a??r;let i=r.substring(d+1);return a?`${a}.${i}`:r}function ll({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s,rows:a=3}){let[d,i]=yn(!1),l=Ja(null),[c,u]=yn(e),f=Ja(!0),[h]=il(ke),[k]=il(ne),[b,y]=yn(!1),[p,v]=yn({top:0,left:0}),[g,C]=yn(""),[I,A]=yn(null),w=Ja(null);ja(()=>{e!==c&&!d&&(u(e),f.current=!0)},[e,d,c]),ja(()=>{!d&&c&&(f.current=!0)},[k,d,c]);let m=()=>{if(!l.current)return null;let T=window.getSelection();if(!T||T.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let z=T.getRangeAt(0),N=z.cloneRange();N.selectNodeContents(l.current),N.setEnd(z.endContainer,z.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",z.endContainer,"endOffset",z.endOffset);let R=0,G=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),oe,de=!1;for(;(oe=G.nextNode())&&!de;)if(oe.nodeType===Node.TEXT_NODE)if(oe===z.endContainer)R+=z.endOffset,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",R);else{let B=(oe.textContent||"").length;R+=B,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",B)}else if(oe.nodeType===Node.ELEMENT_NODE){let B=oe,Ae=B.getAttribute("data-template");Ae?B.contains(z.endContainer)||B===z.endContainer?(R+=Ae.length,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",R)):(R+=Ae.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",Ae.length)):B.tagName==="BR"&&(B===z.endContainer||B.contains(z.endContainer)?de=!0:(R+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",R),{offset:R}},S=T=>{if(!l.current||!T)return;let z=0,N=document.createTreeWalker(l.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),R,G=null,oe=0;for(;R=N.nextNode();)if(R.nodeType===Node.TEXT_NODE){let de=(R.textContent||"").length;if(z+de>=T.offset){G=R,oe=T.offset-z;break}z+=de}else if(R.nodeType===Node.ELEMENT_NODE){let de=R,B=de.getAttribute("data-template");if(B){if(z+B.length>=T.offset){G=de.nextSibling,oe=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}z+=B.length}else if(de.tagName==="BR"){if(z+1>=T.offset){G=de.nextSibling,oe=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}z+=1}}if(G){let de=document.createRange(),B=window.getSelection();try{de.setStart(G,Math.min(oe,G.textContent?.length||0)),de.collapse(!0),B?.removeAllRanges(),B?.addRange(de),l.current.focus()}catch{l.current.focus()}}},X=()=>{if(!l.current||!f.current)return;let T=l.current,z=c||"",N=d?m():null;if(w.current!==null&&(N={offset:w.current},w.current=null),T.innerHTML="",!z&&!d){T.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let R=/\{\{@([^:]+):([^}]+)\}\}/g,G=0,oe;for(;(oe=R.exec(z))!==null;){let[de,,B]=oe,Ae=oe.index;if(Ae>G){let $e=z.slice(G,Ae);le(T,$e)}let Je=document.createElement("span"),Ye=Dm(de,k);Je.className=Ye?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",Je.contentEditable="false",Je.setAttribute("data-template",de),Je.textContent=Rm(de,k),T.appendChild(Je),G=R.lastIndex}if(G<z.length){let de=z.slice(G);le(T,de)}T.innerHTML===""&&d&&(T.innerHTML="<br>"),f.current=!1,N&&requestAnimationFrame(()=>S(N))},le=(T,z)=>{let N=z.split(`
|
|
11
|
-
`);
|
|
12
|
-
`,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",
|
|
13
|
-
`)){if(
|
|
14
|
-
`)){if(
|
|
10
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await m()}}),l(!1)}},g=async()=>{let p=Object.values(C).some(w=>w&&w.length>0);try{d(!0),u(null);let w;p?w=await j.integration.testCredentials({type:t.type,config:C}):w=await j.integration.testConnection(t.id),u(w),w.status==="success"?Do.success(w.message||"Connection successful"):Do.error(w.message||"Connection failed")}catch(w){let G=w instanceof Error?w.message:"Connection test failed";u({status:"error",message:G}),Do.error(G)}finally{d(!1)}},S=()=>{r(qa,{integration:t,onSuccess:()=>{n?.(),i()}})},I=Rt(t.type)?.formFields,x=()=>t.type==="database"?Fe(rl,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:y,placeholder:"postgresql://user:password@host:port/database",value:C.url||""}):I?I.map(p=>p.type==="password"?Fe(rl,{configKey:p.configKey,fieldId:p.id,helpLink:p.helpLink,helpText:p.helpText,label:p.label,onChange:y,placeholder:p.placeholder,value:C[p.configKey]||""},p.id):ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:p.id,children:p.label}),Fe(ae,{id:p.id,onChange:w=>y(p.configKey,w.target.value),placeholder:p.placeholder,type:p.type,value:C[p.configKey]||""}),(p.helpText||p.helpLink)&&ut("p",{className:"text-muted-foreground text-xs",children:[p.helpText,p.helpLink&&Fe("a",{className:"underline hover:text-foreground",href:p.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:p.helpLink.text})]})]},p.id)):null;return ut(Re,{actions:[{label:"Delete",variant:"ghost",onClick:S,disabled:a||s},{label:"Test",variant:"outline",onClick:g,loading:s,disabled:a},{label:"Update",onClick:b,loading:a}],overlayId:e,title:`Edit ${Im(t.type)}`,children:[Fe("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),ut("div",{className:"space-y-4",children:[x(),ut("div",{className:"space-y-2",children:[Fe(M,{htmlFor:"name",children:"Label (Optional)"}),Fe(ae,{id:"name",onChange:p=>v(p.target.value),placeholder:"e.g. Production, Personal, Work",value:f})]})]})]})}function qa({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=oe(),r=km(jt),[i,a]=po(!1),[l,s]=po(!0);return ut(Re,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:"Delete",variant:"destructive",onClick:async()=>{try{a(!0),t.isManaged&&l&&r?await r.api.revokeConsent():await j.integration.delete(t.id),Do.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Do.error("Failed to delete connection"),a(!1)}},loading:i}],overlayId:e,title:"Delete Connection",children:[Fe("p",{className:"text-muted-foreground text-sm",children:"Are you sure you want to delete this connection? Workflows using it will fail until a new one is configured."}),t.isManaged&&ut("div",{className:"mt-4 flex items-center gap-2",children:[Fe(nl,{checked:l,id:"revoke-key",onCheckedChange:c=>s(c)}),Fe(M,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as Ya,jsx as Ie,jsxs as _t}from"react/jsx-runtime";function dl({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:i}){let{push:a}=oe(),[l,s]=Ur(ft),d=al(Ot),c=sl(Ot),u=Om(d),[f,v]=ll(!1),C=al(jt),[h,y]=Ur(Po),[m,b]=ll(!1),[g,S]=Ur(Vr),[D,I]=Ur(Yi),x=sl(Hr),p=Rm(()=>l.filter(k=>k.type===e),[l,e]),w=l.length>0,G=qn(async()=>{try{let k=await j.integration.getAll();s(k),v(!0)}catch(k){console.error("Failed to load integrations:",k)}},[s]);yn(()=>{C?.integrationType===e&&!m&&C.api.getStatus().then(k=>{y(k),b(!0)}).catch(()=>{b(!0)})},[e,m,C,y]),yn(()=>{C?.integrationType===e&&h?.enabled&&h?.isVercelUser&&!D&&(x(!0),C.api.getTeams().then(k=>{S(k.teams),k.teams.length>0&&I(!0)}).catch(()=>{}).finally(()=>{x(!1)}))},[e,C,h,D,S,I,x]),yn(()=>{C?.integrationType===e&&h?.enabled&&h?.isVercelUser&&C.api.getTeams().then(k=>{k.teams.length>0&&(S(k.teams),I(!0))}).catch(()=>{})},[e,C,h?.enabled,h?.isVercelUser]),yn(()=>{G()},[G,e]),yn(()=>{d!==u.current&&(u.current=d,G())},[d,G]),yn(()=>{if(p.length>0&&!r&&!(t&&p.some(R=>R.id===t))){let R=p.find(_=>_.isManaged);o(R?.id||p[0].id)}},[p,t,r,o]);let te=async k=>{await G(),o(k),c(R=>R+1)},O=async()=>{if(await G(),c(k=>k+1),C?.integrationType===e){let k=await C.api.getStatus();y(k)}},W=qn(()=>{a(uo,{type:e,onSuccess:te})},[e,a,te]),$=qn(k=>{a(_r,{integration:k,onSuccess:O,onDelete:O})},[a,O]),T=C?.integrationType===e&&h?.enabled&&h?.isVercelUser&&!h?.hasManagedKey,H=qn(async k=>{if(await G(),o(k),c(R=>R+1),C){let R=await C.api.getStatus();y(R)}},[G,o,c,C,y]),X=qn(()=>{i?i():T&&C?a(C.ConsentOverlay,{onConsent:H,onManualEntry:W}):W()},[i,T,C,a,H,W]);if(!w&&!f)return Ie("div",{className:"flex flex-col gap-1",children:_t("div",{className:"flex items-center gap-2 rounded-md px-2 py-1.5",children:[Ie("div",{className:"size-4 shrink-0 animate-pulse rounded-full bg-muted"}),Ie("div",{className:"h-4 flex-1 animate-pulse rounded bg-muted"}),Ie("div",{className:"size-6 shrink-0 animate-pulse rounded bg-muted"})]})});let q=Rt(e)?.label||e,A=p.filter(k=>k.isManaged),B=p.filter(k=>!k.isManaged);if(p.length===0)return Ie(Ya,{children:_t(E,{className:"w-full justify-start gap-2 border-orange-500/50 bg-orange-500/10 text-orange-600 hover:bg-orange-500/20 dark:text-orange-400",disabled:r,onClick:X,variant:"outline",children:[Ie(Pm,{className:"size-4"}),_t("span",{className:"flex-1 text-left",children:["Add ",q," connection"]}),Ie(Em,{className:"size-4"})]})});if(p.length===1){let k=p[0],R=k.name||`${q} API Key`;return Ie(Ya,{children:_t("div",{className:N("flex h-9 w-full items-center gap-2 rounded-md border px-3 text-sm",r&&"cursor-not-allowed opacity-50"),children:[Ie(ja,{className:"size-4 shrink-0 text-green-600"}),Ie("span",{className:"flex-1 truncate",children:R}),Ie(E,{className:"size-6 shrink-0",disabled:r,onClick:()=>$(k),size:"icon",variant:"ghost",children:Ie(Ja,{className:"size-3"})})]})})}return Ie(Ya,{children:_t("div",{className:"flex flex-col gap-1",children:[A.map(k=>{let R=t===k.id,_=k.name||`${q} API Key`;return _t("div",{className:N("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[_t("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(k.id),type:"button",children:[R?Ie(ja,{className:"size-4 shrink-0"}):Ie(il,{className:"size-4 shrink-0 text-muted-foreground"}),Ie("span",{className:"truncate",children:_})]}),Ie(E,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(k)},size:"icon",variant:"ghost",children:Ie(Ja,{className:"size-3"})})]},k.id)}),B.map(k=>{let R=t===k.id,_=k.name||`${q} API Key`;return _t("div",{className:N("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",R?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[_t("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(k.id),type:"button",children:[R?Ie(ja,{className:"size-4 shrink-0"}):Ie(il,{className:"size-4 shrink-0 text-muted-foreground"}),Ie("span",{className:"truncate",children:_})]}),Ie(E,{className:"size-6 shrink-0",disabled:r,onClick:ne=>{ne.stopPropagation(),$(k)},size:"icon",variant:"ghost",children:Ie(Ja,{className:"size-3"})})]},k.id)}),n&&_t("button",{className:"flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-muted-foreground text-sm transition-colors hover:bg-muted/50 hover:text-foreground",disabled:r,onClick:n,type:"button",children:[Ie(Dm,{className:"size-4 shrink-0"}),Ie("span",{children:"Manage all connections"})]})]})})}import*as Tt from"@radix-ui/react-tooltip";import{jsx as vn,jsxs as Lm}from"react/jsx-runtime";function hn({delayDuration:e=0,...t}){return vn(Tt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function jn({...e}){return vn(hn,{children:vn(Tt.Root,{"data-slot":"tooltip",...e})})}function Jn({...e}){return vn(Tt.Trigger,{"data-slot":"tooltip-trigger",...e})}function Yn({className:e,sideOffset:t=0,children:o,...n}){return vn(Tt.Portal,{children:Lm(Tt.Content,{"data-slot":"tooltip-content",sideOffset:t,className:N("bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",e),...n,children:[o,vn(Tt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as Bm}from"lucide-react";import{useState as Vm}from"react";import{useAtom as cl}from"jotai";import{useEffect as Xa,useRef as Qa,useState as bn}from"react";import{Fragment as Fm,jsx as Za,jsxs as zm}from"react/jsx-runtime";function Mm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function Wm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],i=t.find(d=>d.id===n);if(!i)return r;let a=i.data.label;if(!a&&i.data.type==="action"){let d=i.data.config?.actionType;d&&(a=ge(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let s=r.substring(l+1);return a?`${a}.${s}`:r}function ul({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:i,rows:a=3}){let[l,s]=bn(!1),d=Qa(null),[c,u]=bn(e),f=Qa(!0),[v]=cl(Ce),[C]=cl(re),[h,y]=bn(!1),[m,b]=bn({top:0,left:0}),[g,S]=bn(""),[D,I]=bn(null),x=Qa(null);Xa(()=>{e!==c&&!l&&(u(e),f.current=!0)},[e,l,c]),Xa(()=>{!l&&c&&(f.current=!0)},[C,l,c]);let p=()=>{if(!d.current)return null;let A=window.getSelection();if(!A||A.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let B=A.getRangeAt(0),k=B.cloneRange();k.selectNodeContents(d.current),k.setEnd(B.endContainer,B.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",B.endContainer,"endOffset",B.endOffset);let R=0,_=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),ne,le=!1;for(;(ne=_.nextNode())&&!le;)if(ne.nodeType===Node.TEXT_NODE)if(ne===B.endContainer)R+=B.endOffset,le=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",R);else{let V=(ne.textContent||"").length;R+=V,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",V)}else if(ne.nodeType===Node.ELEMENT_NODE){let V=ne,Ae=V.getAttribute("data-template");Ae?V.contains(B.endContainer)||V===B.endContainer?(R+=Ae.length,le=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",R)):(R+=Ae.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",Ae.length)):V.tagName==="BR"&&(V===B.endContainer||V.contains(B.endContainer)?le=!0:(R+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",R),{offset:R}},w=A=>{if(!d.current||!A)return;let B=0,k=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),R,_=null,ne=0;for(;R=k.nextNode();)if(R.nodeType===Node.TEXT_NODE){let le=(R.textContent||"").length;if(B+le>=A.offset){_=R,ne=A.offset-B;break}B+=le}else if(R.nodeType===Node.ELEMENT_NODE){let le=R,V=le.getAttribute("data-template");if(V){if(B+V.length>=A.offset){_=le.nextSibling,ne=0,!_&&le.parentNode&&(_=document.createTextNode(""),le.parentNode.appendChild(_));break}B+=V.length}else if(le.tagName==="BR"){if(B+1>=A.offset){_=le.nextSibling,ne=0,!_&&le.parentNode&&(_=document.createTextNode(""),le.parentNode.appendChild(_));break}B+=1}}if(_){let le=document.createRange(),V=window.getSelection();try{le.setStart(_,Math.min(ne,_.textContent?.length||0)),le.collapse(!0),V?.removeAllRanges(),V?.addRange(le),d.current.focus()}catch{d.current.focus()}}},G=()=>{if(!d.current||!f.current)return;let A=d.current,B=c||"",k=l?p():null;if(x.current!==null&&(k={offset:x.current},x.current=null),A.innerHTML="",!B&&!l){A.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let R=/\{\{@([^:]+):([^}]+)\}\}/g,_=0,ne;for(;(ne=R.exec(B))!==null;){let[le,,V]=ne,Ae=ne.index;if(Ae>_){let ot=B.slice(_,Ae);te(A,ot)}let tt=document.createElement("span"),Ye=Mm(le,C);tt.className=Ye?"inline-flex items-center gap-1 rounded bg-blue-500/10 px-1.5 py-0.5 text-blue-600 dark:text-blue-400 font-mono text-xs border border-blue-500/20 mx-0.5":"inline-flex items-center gap-1 rounded bg-red-500/10 px-1.5 py-0.5 text-red-600 dark:text-red-400 font-mono text-xs border border-red-500/20 mx-0.5",tt.contentEditable="false",tt.setAttribute("data-template",le),tt.textContent=Wm(le,C),A.appendChild(tt),_=R.lastIndex}if(_<B.length){let le=B.slice(_);te(A,le)}A.innerHTML===""&&l&&(A.innerHTML="<br>"),f.current=!1,k&&requestAnimationFrame(()=>w(k))},te=(A,B)=>{let k=B.split(`
|
|
11
|
+
`);k.forEach((R,_)=>{R&&A.appendChild(document.createTextNode(R)),_<k.length-1&&A.appendChild(document.createElement("br"))})},O=()=>{if(!d.current)return"";let A="",B=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),k;for(;k=B.nextNode();)if(k.nodeType===Node.TEXT_NODE){let R=k.parentElement,_=!1;for(;R&&R!==d.current;){if(R.getAttribute("data-template")){_=!0;break}R=R.parentElement}_?console.log("[Textarea] extractValue: Skipping text inside badge:",k.textContent):(A+=k.textContent,console.log("[Textarea] extractValue: Adding text node:",k.textContent))}else if(k.nodeType===Node.ELEMENT_NODE){let R=k,_=R.getAttribute("data-template");_?(A+=_,console.log("[Textarea] extractValue: Adding template:",_)):R.tagName==="BR"&&(A+=`
|
|
12
|
+
`,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",A),A},W=()=>{let A=O();if(console.log("[Textarea] handleInput: newValue:",A),console.log("[Textarea] handleInput: internalValue:",c),console.log("[Textarea] handleInput: DOM innerHTML:",d.current?.innerHTML),A===c){console.log("[Textarea] handleInput: No change detected, ignoring");return}let B=(c.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,k=(A.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(console.log("[Textarea] handleInput: oldTemplates:",B,"newTemplates:",k),k>B){console.log("[Textarea] handleInput: New template added, rendering badge"),u(A),t?.(A),f.current=!0,y(!1),requestAnimationFrame(()=>G());return}if(k===B&&k>0){console.log("[Textarea] handleInput: Typing around existing badges, NOT updating display"),u(A),t?.(A);let _=A.lastIndexOf("@");if(_!==-1){let ne=A.slice(_+1);if(!ne.includes(" ")&&!ne.includes(`
|
|
13
|
+
`)){if(S(ne),I(_),d.current){let le=d.current.getBoundingClientRect(),V={top:le.bottom+window.scrollY+4,left:le.left+window.scrollX};b(V)}y(!0)}else y(!1)}else y(!1);return}if(k<B){console.log("[Textarea] handleInput: Template removed, updating display"),u(A),t?.(A),f.current=!0,requestAnimationFrame(()=>G());return}console.log("[Textarea] handleInput: Normal typing, no badges"),u(A),t?.(A);let R=A.lastIndexOf("@");if(R!==-1){let _=A.slice(R+1);if(!_.includes(" ")&&!_.includes(`
|
|
14
|
+
`)){if(S(_),I(R),d.current){let ne=d.current.getBoundingClientRect(),le={top:ne.bottom+window.scrollY+4,left:ne.left+window.scrollX};b(le)}y(!0)}else y(!1)}else y(!1)},$=A=>{if(!d.current||D===null)return;let B=O(),k=B.slice(0,D),R=B.slice(D+1+g.length),_=k+A+R,ne=k.length+A.length;console.log("[Textarea] Autocomplete select:",{currentText:B,atSignPosition:D,filter:g,template:A,beforeAt:k,afterFilter:R,newText:_,targetCursorPosition:ne}),u(_),t?.(_),f.current=!0,y(!1),I(null),x.current=ne,d.current.focus()},T=()=>{s(!0),f.current=!0},H=()=>{setTimeout(()=>{document.activeElement!==d.current&&(s(!1),f.current=!0,y(!1))},200)},X=A=>{A.preventDefault();let B=A.clipboardData.getData("text/plain");document.execCommand("insertText",!1,B)},z=A=>{A.key==="Enter"&&(A.preventDefault(),document.execCommand("insertLineBreak"))};Xa(()=>{f.current&&G()},[c,l]);let q=`${a*1.5}rem`;return zm(Fm,{children:[Za("div",{className:N("flex w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm transition-colors focus-within:outline-none focus-within:ring-1 focus-within:ring-ring",n&&"cursor-not-allowed opacity-50",r),style:{minHeight:q},children:Za("div",{className:"w-full outline-none whitespace-pre-wrap break-words",contentEditable:!n,id:i,onBlur:H,onFocus:T,onInput:W,onKeyDown:z,onPaste:X,ref:d,role:"textbox",suppressContentEditableWarning:!0})}),Za(Fr,{currentNodeId:v||void 0,filter:g,isOpen:h,onClose:()=>y(!1),onSelect:$,position:m})]})}import{Fragment as Jm,jsx as Xe,jsxs as Xn}from"react/jsx-runtime";function Hm({field:e,value:t,onChange:o,disabled:n}){return Xe(Le,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,value:t})}function Gm({field:e,value:t,onChange:o,disabled:n}){return Xe(ul,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,rows:e.rows||4,value:t})}function $m({field:e,value:t,onChange:o,disabled:n}){return Xe(ae,{disabled:n,id:e.key,onChange:r=>o(r.target.value),placeholder:e.placeholder,value:t})}function _m({field:e,value:t,onChange:o,disabled:n}){return Xe(ae,{disabled:n,id:e.key,min:e.min,onChange:r=>o(r.target.value),placeholder:e.placeholder,type:"number",value:t})}function Um({field:e,value:t,onChange:o,disabled:n}){return e.options?Xn(ve,{disabled:n,onValueChange:o,value:t,children:[Xe(he,{className:"w-full",id:e.key,children:Xe(xe,{placeholder:e.placeholder})}),Xe(be,{children:e.options.map(r=>Xe(Z,{value:r.value,children:r.label},r.value))})]}):null}function Km(e){return Xe(co,{disabled:e.disabled,onChange:t=>e.onChange(JSON.stringify(t)),schema:e.value?JSON.parse(e.value):[]})}var qm={"template-input":Hm,"template-textarea":Gm,text:$m,number:_m,select:Um,"schema-builder":Km};function ml(e,t,o,n){if(e.showWhen&&t[e.showWhen.field]!==e.showWhen.equals)return null;let r=t[e.key]||e.defaultValue||"",i=qm[e.type];return Xn("div",{className:"space-y-2",children:[Xn(M,{className:"ml-1",htmlFor:e.key,children:[e.label,e.required&&Xe("span",{className:"text-red-500",children:"*"})]}),Xe(i,{disabled:n,field:e,onChange:a=>o(e.key,a),value:r})]},e.key)}function jm({label:e,fields:t,config:o,onUpdateConfig:n,disabled:r,defaultExpanded:i=!1}){let[a,l]=Vm(i);return Xn("div",{className:"space-y-2",children:[Xn("button",{className:"ml-1 flex items-center gap-1 text-left",onClick:()=>l(!a),type:"button",children:[Xe("span",{className:"font-medium text-sm",children:e}),Xe(Bm,{className:`h-3.5 w-3.5 text-muted-foreground transition-transform duration-200 ${a?"":"-rotate-90"}`})]}),a&&Xe("div",{className:"ml-1 space-y-4 border-primary/50 border-l-2 py-2 pl-3",children:t.map(s=>ml(s,o,n,r))})]})}function pl({fields:e,config:t,onUpdateConfig:o,disabled:n}){return Xe(Jm,{children:e.map(r=>ti(r)?Xe(jm,{config:t,defaultExpanded:r.defaultExpanded,disabled:n,fields:r.fields,label:r.label,onUpdateConfig:o},`group-${r.label}`):ml(r,t,o,n))})}import{Fragment as ap,jsx as fe,jsxs as bt}from"react/jsx-runtime";function op({actionType:e,config:t,onUpdateConfig:o,onUpdateMultipleConfig:n,disabled:r}){switch(e){case"HTTP Request":return fe(zi,{config:t,disabled:r,onUpdateConfig:o});case"Database Query":return fe(Fi,{config:t,disabled:r,onUpdateConfig:o});case"Condition":return fe(Li,{config:t,disabled:r,onUpdateConfig:o,onUpdateMultipleConfig:n});case"Loop":return fe(Bi,{config:t,disabled:r,onUpdateConfig:o});case"Merge":return fe(Vi,{config:t,disabled:r,onUpdateConfig:o});case"Switch":return fe(Ui,{config:t,disabled:r,onUpdateConfig:o});case"Run Workflow":return fe(Gi,{config:t,disabled:r,onUpdateConfig:o});case"Run Workflows in Sequence":return fe(_i,{config:t,disabled:r,onUpdateConfig:o});default:return null}}var vl=[{id:"HTTP Request",label:"HTTP Request"},{id:"Database Query",label:"Database Query"},{id:"Condition",label:"Condition"},{id:"Loop",label:"Loop"},{id:"Merge",label:"Merge"},{id:"Switch",label:"Switch"},{id:"Run Workflow",label:"Run Workflow"},{id:"Run Workflows in Sequence",label:"Run Workflows in Sequence"}],es=vl.map(e=>e.id),gl={"Database Query":"database"};function np(){return Kr(()=>{let e=Qs(),t={System:vl};for(let[o,n]of Object.entries(e))t[o]=n.map(r=>({id:r.id,label:r.label}));return t},[])}function yl(e){if(es.includes(e))return"System";let t=ge(e);return t?.category?t.category:null}function rp(e){if(es.includes(e))return e;let t=ge(e);return t?t.id:e}function qr({config:e,onUpdateConfig:t,onUpdateMultipleConfig:o,disabled:n,isOwner:r=!0}){let i=e?.actionType||"",a=np(),l=Kr(()=>Ys(),[]),s=i?yl(i):null,[d,c]=tp(s||""),u=Ym(Ot),f=fl(ft),{push:v}=oe(),C=fl(Br);ep(()=>{let w=i?yl(i):null;c(w||"")},[i]);let h=w=>{c(w);let G=a[w]?.[0];G&&t("actionType",G.id)},y=w=>{t("actionType",w)},m=(w,G)=>{t(w,String(G))},b=i?ge(i):null,g=Kr(()=>{if(!i)return;if(gl[i])return gl[i];let G=ge(i)?.integration;if(!(G&&!Ko(G)))return G},[i]),S=g==="ai-gateway"&&C?.enabled&&C?.isVercelUser,D=Kr(()=>g?f.some(w=>w.type===g):!1,[g,f]),I=w=>{t("integrationId",w),u(G=>G+1)},x=()=>{g&&v(uo,{type:g,onSuccess:w=>{u(G=>G+1),t("integrationId",w)}})},p=()=>{S?v(ol,{onConsent:I,onManualEntry:x}):x()};return bt(ap,{children:[bt("div",{className:"grid grid-cols-2 gap-2",children:[bt("div",{className:"space-y-2",children:[fe(M,{className:"ml-1",htmlFor:"actionCategory",children:"Service"}),bt(ve,{disabled:n,onValueChange:h,value:d||void 0,children:[fe(he,{className:"w-full",id:"actionCategory",children:fe(xe,{placeholder:"Select category"})}),bt(be,{children:[fe(Z,{value:"System",children:bt("div",{className:"flex items-center gap-2",children:[fe(Zm,{className:"size-4"}),fe("span",{children:"System"})]})}),fe(Lr,{}),l.map(w=>fe(Z,{value:w.label,children:bt("div",{className:"flex items-center gap-2",children:[fe(Wt,{className:"size-4",integration:w.type}),fe("span",{children:w.label})]})},w.type))]})]})]}),bt("div",{className:"space-y-2",children:[fe(M,{className:"ml-1",htmlFor:"actionType",children:"Action"}),bt(ve,{disabled:n||!d,onValueChange:y,value:rp(i)||void 0,children:[fe(he,{className:"w-full",id:"actionType",children:fe(xe,{placeholder:"Select action"})}),fe(be,{children:d&&a[d]?.map(w=>fe(Z,{value:w.id,children:w.label},w.id))})]})]})]}),g&&r&&bt("div",{className:"space-y-2",children:[bt("div",{className:"ml-1 flex items-center justify-between",children:[bt("div",{className:"flex items-center gap-1",children:[fe(M,{children:"Connection"}),fe(hn,{children:bt(jn,{children:[fe(Jn,{asChild:!0,children:fe(Xm,{className:"size-3.5 text-muted-foreground"})}),fe(Yn,{children:fe("p",{children:"API key or OAuth credentials for this service"})})]})})]}),D&&fe(E,{className:"size-6",disabled:n,onClick:p,size:"icon",variant:"ghost",children:fe(Qm,{className:"size-4"})})]}),fe(dl,{disabled:n,integrationType:g,onChange:w=>t("integrationId",w),value:e?.integrationId||""})]}),fe(op,{actionType:e?.actionType||"",config:e,disabled:n,onUpdateConfig:t,onUpdateMultipleConfig:o}),b&&!es.includes(i)&&fe(pl,{config:e,disabled:n,fields:b.configFields,onUpdateConfig:m})]})}import{ChevronRight as wp,Eye as Tl,EyeOff as Sl,Grid3X3 as xp,List as Np,MoreHorizontal as kp,Search as Cp,Settings as Il,Zap as Pl}from"lucide-react";import{useEffect as Tp,useMemo as ts,useRef as Sp,useState as Zn}from"react";import{Repeat as sp}from"lucide-react";import{jsx as ip}from"react/jsx-runtime";var jr={id:"Loop",label:"Loop",description:"Loop through a list of items",category:"System",icon:ip(sp,{className:"size-12 text-cyan-300",strokeWidth:1.5}),codeGenerator:`export async function loopStep(input: {
|
|
15
15
|
items: unknown[];
|
|
16
16
|
batchSize?: number;
|
|
17
17
|
currentBatchIndex?: number;
|
|
@@ -39,89 +39,88 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
39
39
|
items,
|
|
40
40
|
batchSize,
|
|
41
41
|
};
|
|
42
|
-
}`};import{Merge as
|
|
43
|
-
|
|
44
|
-
|
|
42
|
+
}`};import{Merge as lp}from"lucide-react";import{jsx as dp}from"react/jsx-runtime";var wn={id:"Merge",label:"Merge",description:"Combine data from multiple inputs",category:"System",icon:dp(lp,{className:"size-12 text-orange-300",strokeWidth:1.5}),codeGenerator:`export async function mergeStep(input: {
|
|
43
|
+
inputCount?: number;
|
|
44
|
+
[key: string]: unknown;
|
|
45
45
|
mode: "append" | "combineByPosition" | "combineByFields";
|
|
46
46
|
matchField1?: string;
|
|
47
|
-
matchField2?: string;
|
|
48
47
|
joinType?: "inner" | "leftOuter" | "rightOuter" | "fullOuter";
|
|
49
48
|
unmatchedHandling?: "discard" | "useNull";
|
|
50
49
|
}) {
|
|
51
50
|
"use step";
|
|
52
51
|
|
|
53
|
-
const
|
|
54
|
-
const
|
|
52
|
+
const count = Number(input.inputCount) || 2;
|
|
53
|
+
const inputs: unknown[][] = [];
|
|
54
|
+
for (let i = 1; i <= count; i++) {
|
|
55
|
+
const val = (input as Record<string, unknown>)[\`input\${i}\`];
|
|
56
|
+
inputs.push(Array.isArray(val) ? val : []);
|
|
57
|
+
}
|
|
55
58
|
const mode = input.mode || "append";
|
|
56
59
|
|
|
57
60
|
if (mode === "append") {
|
|
58
|
-
const merged =
|
|
61
|
+
const merged = inputs.flat();
|
|
59
62
|
return { merged, totalItems: merged.length };
|
|
60
63
|
}
|
|
61
64
|
|
|
62
65
|
if (mode === "combineByPosition") {
|
|
63
|
-
const maxLength = Math.max(
|
|
66
|
+
const maxLength = Math.max(...inputs.map(arr => arr.length));
|
|
64
67
|
const useNull = input.unmatchedHandling !== "discard";
|
|
65
68
|
const merged = [];
|
|
66
69
|
for (let i = 0; i < maxLength; i++) {
|
|
67
|
-
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
70
|
+
if (!useNull && inputs.some(arr => arr[i] === undefined)) continue;
|
|
71
|
+
const combined: Record<string, unknown> = {};
|
|
72
|
+
for (let j = 0; j < inputs.length; j++) {
|
|
73
|
+
const item = inputs[j][i];
|
|
74
|
+
if (item && typeof item === "object") Object.assign(combined, item);
|
|
75
|
+
else combined[\`input\${j + 1}\`] = item ?? null;
|
|
76
|
+
}
|
|
77
|
+
merged.push(combined);
|
|
74
78
|
}
|
|
75
79
|
return { merged, totalItems: merged.length };
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
if (mode === "combineByFields") {
|
|
79
|
-
const
|
|
80
|
-
const field2 = input.matchField2 || "id";
|
|
83
|
+
const matchField = input.matchField1 || "id";
|
|
81
84
|
const joinType = input.joinType || "inner";
|
|
82
85
|
const getField = (item: unknown, field: string) =>
|
|
83
86
|
item && typeof item === "object" ? (item as Record<string, unknown>)[field] : undefined;
|
|
84
87
|
|
|
85
|
-
|
|
86
|
-
for (
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
...(typeof item1 === "object" ? item1 : {}),
|
|
103
|
-
|
|
104
|
-
|
|
88
|
+
let current = inputs[0];
|
|
89
|
+
for (let idx = 1; idx < inputs.length; idx++) {
|
|
90
|
+
const next = inputs[idx];
|
|
91
|
+
const map = new Map<unknown, unknown[]>();
|
|
92
|
+
for (const item of next) {
|
|
93
|
+
const key = getField(item, matchField);
|
|
94
|
+
if (!map.has(key)) map.set(key, []);
|
|
95
|
+
map.get(key)!.push(item);
|
|
96
|
+
}
|
|
97
|
+
const merged: unknown[] = [];
|
|
98
|
+
const matchedKeys = new Set<unknown>();
|
|
99
|
+
for (const item1 of current) {
|
|
100
|
+
const key = getField(item1, matchField);
|
|
101
|
+
const matches = map.get(key);
|
|
102
|
+
if (matches && matches.length > 0) {
|
|
103
|
+
matchedKeys.add(key);
|
|
104
|
+
for (const item2 of matches) {
|
|
105
|
+
merged.push({ ...(typeof item1 === "object" ? item1 : {}), ...(typeof item2 === "object" ? item2 : {}) });
|
|
106
|
+
}
|
|
107
|
+
} else if (joinType === "leftOuter" || joinType === "fullOuter") {
|
|
108
|
+
merged.push({ ...(typeof item1 === "object" ? item1 : {}) });
|
|
105
109
|
}
|
|
106
|
-
} else if (joinType === "leftOuter" || joinType === "fullOuter") {
|
|
107
|
-
merged.push({ ...(typeof item1 === "object" ? item1 : {}) });
|
|
108
110
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
const key = getField(item2, field2);
|
|
114
|
-
if (!matchedKeys2.has(key)) {
|
|
115
|
-
merged.push({ ...(typeof item2 === "object" ? item2 : {}) });
|
|
111
|
+
if (joinType === "rightOuter" || joinType === "fullOuter") {
|
|
112
|
+
for (const item2 of next) {
|
|
113
|
+
const key = getField(item2, matchField);
|
|
114
|
+
if (!matchedKeys.has(key)) merged.push({ ...(typeof item2 === "object" ? item2 : {}) });
|
|
116
115
|
}
|
|
117
116
|
}
|
|
117
|
+
current = merged;
|
|
118
118
|
}
|
|
119
|
-
|
|
120
|
-
return { merged, totalItems: merged.length };
|
|
119
|
+
return { merged: current, totalItems: current.length };
|
|
121
120
|
}
|
|
122
121
|
|
|
123
|
-
return { merged:
|
|
124
|
-
}`};import{WorkflowIcon as
|
|
122
|
+
return { merged: inputs.flat(), totalItems: inputs.flat().length };
|
|
123
|
+
}`};import{WorkflowIcon as cp}from"lucide-react";import{jsx as up}from"react/jsx-runtime";var Jr={id:"Run Workflow",label:"Run Workflow",description:"Execute another workflow and wait for it to complete",category:"System",icon:up(cp,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowStep(input: {
|
|
125
124
|
workflowId: string;
|
|
126
125
|
input?: string;
|
|
127
126
|
}) {
|
|
@@ -130,7 +129,7 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
130
129
|
// Note: Run Workflow is only available in the visual builder.
|
|
131
130
|
// It executes another workflow internally and returns its output.
|
|
132
131
|
throw new Error("Run Workflow is not supported in exported code. Use HTTP Request instead.");
|
|
133
|
-
}`};import{ListOrdered as
|
|
132
|
+
}`};import{ListOrdered as mp}from"lucide-react";import{jsx as pp}from"react/jsx-runtime";var Yr={id:"Run Workflows in Sequence",label:"Run Workflows in Sequence",description:"Execute multiple workflows one after another in order",category:"System",icon:pp(mp,{className:"size-12 text-emerald-300",strokeWidth:1.5}),codeGenerator:`export async function runWorkflowsInSequenceStep(input: {
|
|
134
133
|
workflowIds: string[];
|
|
135
134
|
continueOnFailure?: boolean;
|
|
136
135
|
input?: string;
|
|
@@ -140,27 +139,18 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
140
139
|
// Note: Run Workflows in Sequence is only available in the visual builder.
|
|
141
140
|
// It executes multiple workflows internally in order and returns their outputs.
|
|
142
141
|
throw new Error("Run Workflows in Sequence is not supported in exported code. Use HTTP Request instead.");
|
|
143
|
-
}`};import{ArrowLeftRight as
|
|
142
|
+
}`};import{ArrowLeftRight as fp}from"lucide-react";import{jsx as gp}from"react/jsx-runtime";var xn={id:"Switch",label:"Switch",description:"Route based on rules or values",category:"System",icon:gp(fp,{className:"size-12 text-violet-300",strokeWidth:1.5}),codeGenerator:`export async function switchStep(input: {
|
|
144
143
|
mode: "rules" | "expression";
|
|
145
144
|
switchValue?: string;
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
routeName2?: string;
|
|
149
|
-
routeName3?: string;
|
|
150
|
-
routeCondition0?: boolean;
|
|
151
|
-
routeCondition1?: boolean;
|
|
152
|
-
routeCondition2?: boolean;
|
|
153
|
-
routeCondition3?: boolean;
|
|
154
|
-
routeCaseValue0?: string;
|
|
155
|
-
routeCaseValue1?: string;
|
|
156
|
-
routeCaseValue2?: string;
|
|
157
|
-
routeCaseValue3?: string;
|
|
145
|
+
routeCount?: number;
|
|
146
|
+
[key: string]: unknown;
|
|
158
147
|
}) {
|
|
159
148
|
"use step";
|
|
160
149
|
|
|
161
150
|
const mode = input.mode || "rules";
|
|
151
|
+
const count = Number(input.routeCount) || 4;
|
|
162
152
|
const routes = [];
|
|
163
|
-
for (let i = 0; i <
|
|
153
|
+
for (let i = 0; i < count; i++) {
|
|
164
154
|
const name = (input as Record<string, unknown>)[\`routeName\${i}\`] as string | undefined;
|
|
165
155
|
const condition = (input as Record<string, unknown>)[\`routeCondition\${i}\`] as boolean | undefined;
|
|
166
156
|
const caseValue = (input as Record<string, unknown>)[\`routeCaseValue\${i}\`] as string | undefined;
|
|
@@ -183,16 +173,16 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
183
173
|
}
|
|
184
174
|
|
|
185
175
|
return { matchedRouteIndex: -1, matchedRouteName: "Default", isDefault: true };
|
|
186
|
-
}`};import{useEffect as mp,useState as pp}from"react";function gl(){let[e,t]=pp(void 0);return mp(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as bt}from"radix-ui";import{CheckIcon as bk,ChevronRightIcon as fp,CircleIcon as gp}from"lucide-react";import{jsx as mt,jsxs as xl}from"react/jsx-runtime";function Eo({...e}){return mt(bt.Root,{"data-slot":"dropdown-menu",...e})}function Do({...e}){return mt(bt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Ro({className:e,sideOffset:t=4,...o}){return mt(bt.Portal,{children:mt(bt.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...o})})}function wt({className:e,inset:t,variant:o="default",...n}){return mt(bt.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":o,className:x("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function yl({...e}){return mt(bt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Jr({className:e,children:t,...o}){return xl(bt.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:x("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[mt("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:mt(bt.ItemIndicator,{children:mt(gp,{className:"size-2 fill-current"})})}),t]})}function vl({className:e,inset:t,...o}){return mt(bt.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:x("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...o})}function qn({className:e,...t}){return mt(bt.Separator,{"data-slot":"dropdown-menu-separator",className:x("bg-border -mx-1 my-1 h-px",e),...t})}function hl({...e}){return mt(bt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function bl({className:e,inset:t,children:o,...n}){return xl(bt.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:x("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,mt(fp,{className:"ml-auto size-4"})]})}function wl({className:e,...t}){return mt(bt.SubContent,{"data-slot":"dropdown-menu-sub-content",className:x("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}import{Fragment as Cl,jsx as me,jsxs as it}from"react/jsx-runtime";var kp=[qo,Uo,Ko,_r,Ur,jr,Kr,qr];function Cp(){return Qa(()=>{let t=js().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...kp,...t]},[])}function Tp({group:e}){let t=e.actions[0];return t?.integration?me(Mt,{className:"size-4",integration:t.integration}):e.category==="System"?me(Tl,{className:"size-4"}):me(Al,{className:"size-4"})}function Ap({action:e,className:t}){return e.integration?me(Mt,{className:t,integration:e.integration}):e.category==="System"?me(Tl,{className:x(t,"text-muted-foreground")}):me(Al,{className:x(t,"text-muted-foreground")})}var Sl="workflow-action-grid-hidden-groups",Il="workflow-action-grid-view-mode";function Sp(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(Sl);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function Ip(){if(typeof window>"u")return"list";try{return localStorage.getItem(Il)==="grid"?"grid":"list"}catch{return"list"}}function Yr({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=jn(""),[s,a]=jn(new Set),[d,i]=jn(Sp),[l,c]=jn(!1),[u,f]=jn(Ip),h=Cp(),k=Np(null),b=gl(),y=()=>{let w=u==="list"?"grid":"list";f(w),localStorage.setItem(Il,w)},p=w=>{a(m=>{let S=new Set(m);return S.has(w)?S.delete(w):S.add(w),S})},v=w=>{i(m=>{let S=new Set(m);return S.has(w)?S.delete(w):S.add(w),localStorage.setItem(Sl,JSON.stringify([...S])),S})};xp(()=>{o&&b===!1&&k.current&&k.current.focus()},[o,b]);let g=h.filter(w=>{let m=n.toLowerCase();return w.label.toLowerCase().includes(m)||w.description.toLowerCase().includes(m)||w.category.toLowerCase().includes(m)}),C=Qa(()=>{let w={};for(let S of g){let X=S.category;w[X]||(w[X]=[]),w[X].push(S)}return Object.keys(w).sort((S,X)=>S==="System"?-1:X==="System"?1:S.localeCompare(X)).map(S=>({category:S,actions:w[S]}))},[g]),I=Qa(()=>l?C:C.filter(w=>!d.has(w.category)),[C,d,l]),A=d.size;return it("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[it("div",{className:"flex shrink-0 gap-2",children:[it("div",{className:"relative flex-1",children:[me(wp,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),me(se,{className:"pl-9","data-testid":"action-search-input",disabled:t,id:"action-filter",onChange:w=>r(w.target.value),placeholder:"Search actions...",ref:k,value:n})]}),me(gn,{children:it($n,{children:[me(_n,{asChild:!0,children:me(D,{className:"shrink-0",onClick:y,size:"icon",variant:"ghost",children:u==="list"?me(vp,{className:"size-4"}):me(hp,{className:"size-4"})})}),me(Un,{children:u==="list"?"Grid view":"List view"})]})}),A>0&&me(gn,{children:it($n,{children:[me(_n,{asChild:!0,children:me(D,{className:x("shrink-0",l&&"bg-muted"),onClick:()=>c(!l),size:"icon",variant:"ghost",children:l?me(Nl,{className:"size-4"}):me(kl,{className:"size-4"})})}),me(Un,{children:l?"Hide hidden groups":`Show ${A} hidden group${A>1?"s":""}`})]})})]}),it("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[g.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),g.length>0&&I.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"All groups are hidden"}),u==="grid"&&I.length>0&&me("div",{className:"grid gap-2 p-1",style:{gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))"},children:g.filter(w=>l||!d.has(w.category)).map(w=>it("button",{className:x("flex aspect-square flex-col items-center justify-center gap-1.5 rounded-lg border border-transparent p-2 text-center transition-colors hover:border-border hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${w.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(w.id),type:"button",children:[me(Ap,{action:w,className:"size-6"}),me("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:w.label})]},w.id))}),u==="list"&&I.length>0&&I.map((w,m)=>{let S=s.has(w.category),X=d.has(w.category);return it("div",{children:[m>0&&me("div",{className:"my-2 h-px bg-border"}),it("div",{className:x("sticky top-0 z-10 mb-1 flex items-center gap-2 bg-background px-3 py-2 font-medium text-muted-foreground text-xs uppercase tracking-wider",X&&"opacity-50"),children:[it("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>p(w.category),type:"button",children:[me(yp,{className:x("size-3.5 transition-transform",!S&&"rotate-90")}),me(Tp,{group:w}),w.category]}),it(Eo,{children:[me(Do,{asChild:!0,children:me("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:me(bp,{className:"size-4"})})}),me(Ro,{align:"end",children:me(wt,{onClick:()=>v(w.category),children:X?it(Cl,{children:[me(Nl,{className:"mr-2 size-4"}),"Show group"]}):it(Cl,{children:[me(kl,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!S&&w.actions.map(le=>me("button",{className:x("flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${le.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(le.id),type:"button",children:it("span",{className:"min-w-0 flex-1 truncate",children:[me("span",{className:"font-medium",children:le.label}),le.description&&it("span",{className:"text-muted-foreground text-xs",children:[" ","- ",le.description]})]})},le.id))]},w.category)})]})]})}import{Clock as Ep,Copy as Dp,Play as Rp,Webhook as Op}from"lucide-react";import{toast as Lp}from"sonner";import{jsx as Jn,jsxs as Pl}from"react/jsx-runtime";var Pp=[{label:"North America",zones:[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Phoenix",label:"Arizona Time (MST)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HST)"},{value:"America/Toronto",label:"Toronto"},{value:"America/Vancouver",label:"Vancouver"}]},{label:"Europe",zones:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET/CEST)"},{value:"Europe/Berlin",label:"Berlin (CET/CEST)"},{value:"Europe/Rome",label:"Rome (CET/CEST)"},{value:"Europe/Madrid",label:"Madrid (CET/CEST)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET/CEST)"},{value:"Europe/Brussels",label:"Brussels (CET/CEST)"},{value:"Europe/Stockholm",label:"Stockholm (CET/CEST)"},{value:"Europe/Warsaw",label:"Warsaw (CET/CEST)"},{value:"Europe/Athens",label:"Athens (EET/EEST)"},{value:"Europe/Moscow",label:"Moscow (MSK)"}]},{label:"Asia",zones:[{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Asia/Kolkata",label:"India (IST)"},{value:"Asia/Shanghai",label:"China (CST)"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)"},{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Seoul",label:"Seoul (KST)"},{value:"Asia/Singapore",label:"Singapore (SGT)"},{value:"Asia/Bangkok",label:"Bangkok (ICT)"},{value:"Asia/Jakarta",label:"Jakarta (WIB)"}]},{label:"Australia & Pacific",zones:[{value:"Australia/Sydney",label:"Sydney (AEDT/AEST)"},{value:"Australia/Melbourne",label:"Melbourne (AEDT/AEST)"},{value:"Australia/Brisbane",label:"Brisbane (AEST)"},{value:"Australia/Perth",label:"Perth (AWST)"},{value:"Pacific/Auckland",label:"Auckland (NZDT/NZST)"}]},{label:"South America",zones:[{value:"America/Sao_Paulo",label:"S\xE3o Paulo (BRT)"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires (ART)"},{value:"America/Santiago",label:"Santiago (CLT)"},{value:"America/Bogota",label:"Bogot\xE1 (COT)"},{value:"America/Lima",label:"Lima (PET)"}]},{label:"Africa & Middle East",zones:[{value:"Africa/Cairo",label:"Cairo (EET)"},{value:"Africa/Johannesburg",label:"Johannesburg (SAST)"},{value:"Africa/Lagos",label:"Lagos (WAT)"},{value:"Africa/Nairobi",label:"Nairobi (EAT)"},{value:"Asia/Jerusalem",label:"Jerusalem (IST)"}]},{label:"Other",zones:[{value:"UTC",label:"UTC (Coordinated Universal Time)"}]}];function El({value:e,onValueChange:t,disabled:o,id:n}){return Pl(ve,{value:e,onValueChange:t,disabled:o,children:[Jn(he,{id:n,children:Jn(we,{placeholder:"Select timezone"})}),Jn(be,{children:Pp.map(r=>Pl(bi,{children:[Jn(wi,{children:r.label}),r.zones.map(s=>Jn(te,{value:s.value,children:s.label},s.value))]},r.label))})]})}import{Fragment as Za,jsx as Ie,jsxs as lt}from"react/jsx-runtime";function Xr({config:e,onUpdateConfig:t,disabled:o,workflowId:n}){let r=n?`${typeof window<"u"?window.location.origin:""}/api/workflows/${n}/webhook`:"",s=()=>{r&&(navigator.clipboard.writeText(r),Lp.success("Webhook URL copied to clipboard"))};return lt(Za,{children:[lt("div",{className:"space-y-2",children:[Ie(M,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),lt(ve,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[Ie(he,{className:"w-full",id:"triggerType",children:Ie(we,{placeholder:"Select trigger type"})}),lt(be,{children:[Ie(te,{value:"Manual",children:lt("div",{className:"flex items-center gap-2",children:[Ie(Rp,{className:"h-4 w-4"}),"Manual"]})}),Ie(te,{value:"Schedule",children:lt("div",{className:"flex items-center gap-2",children:[Ie(Ep,{className:"h-4 w-4"}),"Schedule"]})}),Ie(te,{value:"Webhook",children:lt("div",{className:"flex items-center gap-2",children:[Ie(Op,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&<(Za,{children:[lt("div",{className:"space-y-2",children:[Ie(M,{className:"ml-1",children:"Webhook URL"}),lt("div",{className:"flex gap-2",children:[Ie(se,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),Ie(D,{disabled:!r,onClick:s,size:"icon",variant:"outline",children:Ie(Dp,{className:"h-4 w-4"})})]})]}),lt("div",{className:"space-y-2",children:[Ie(M,{children:"Request Schema (Optional)"}),Ie(lo,{disabled:o,onChange:a=>t("webhookSchema",JSON.stringify(a)),schema:e?.webhookSchema?JSON.parse(e.webhookSchema):[]}),Ie("p",{className:"text-muted-foreground text-xs",children:"Define the expected structure of the incoming webhook payload."})]}),lt("div",{className:"space-y-2",children:[Ie(M,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),Ie("div",{className:"overflow-hidden rounded-md border",children:Ie(yt,{defaultLanguage:"json",height:"150px",onChange:a=>t("webhookMockRequest",a||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"on"},value:e?.webhookMockRequest||""})}),Ie("p",{className:"text-muted-foreground text-xs",children:"Enter a sample JSON payload to test the webhook trigger."})]})]}),e?.triggerType==="Schedule"&<(Za,{children:[lt("div",{className:"space-y-2",children:[Ie(M,{className:"ml-1",htmlFor:"scheduleCron",children:"Cron Expression"}),Ie(se,{disabled:o,id:"scheduleCron",onChange:a=>t("scheduleCron",a.target.value),placeholder:"0 9 * * * (every day at 9am)",value:e?.scheduleCron||""})]}),lt("div",{className:"space-y-2",children:[Ie(M,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),Ie(El,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var Dl={"Database Query":Ko.codeGenerator,"HTTP Request":qo.codeGenerator,Condition:Uo.codeGenerator},es=`async function actionStep(input: Record<string, unknown>) {
|
|
176
|
+
}`};import{useEffect as yp,useState as vp}from"react";function hl(){let[e,t]=vp(void 0);return yp(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as wt}from"radix-ui";import{CheckIcon as Sk,ChevronRightIcon as hp,CircleIcon as bp}from"lucide-react";import{jsx as mt,jsxs as Cl}from"react/jsx-runtime";function Ro({...e}){return mt(wt.Root,{"data-slot":"dropdown-menu",...e})}function Oo({...e}){return mt(wt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function Lo({className:e,sideOffset:t=4,...o}){return mt(wt.Portal,{children:mt(wt.Content,{"data-slot":"dropdown-menu-content",sideOffset:t,className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",e),...o})})}function xt({className:e,inset:t,variant:o="default",...n}){return mt(wt.Item,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":o,className:N("focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n})}function bl({...e}){return mt(wt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Xr({className:e,children:t,...o}){return Cl(wt.RadioItem,{"data-slot":"dropdown-menu-radio-item",className:N("focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...o,children:[mt("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:mt(wt.ItemIndicator,{children:mt(bp,{className:"size-2 fill-current"})})}),t]})}function wl({className:e,inset:t,...o}){return mt(wt.Label,{"data-slot":"dropdown-menu-label","data-inset":t,className:N("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...o})}function Qn({className:e,...t}){return mt(wt.Separator,{"data-slot":"dropdown-menu-separator",className:N("bg-border -mx-1 my-1 h-px",e),...t})}function xl({...e}){return mt(wt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function Nl({className:e,inset:t,children:o,...n}){return Cl(wt.SubTrigger,{"data-slot":"dropdown-menu-sub-trigger","data-inset":t,className:N("focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...n,children:[o,mt(hp,{className:"ml-auto size-4"})]})}function kl({className:e,...t}){return mt(wt.SubContent,{"data-slot":"dropdown-menu-sub-content",className:N("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",e),...t})}import{Fragment as Al,jsx as ue,jsxs as it}from"react/jsx-runtime";var Ap=[Jo,qo,jo,jr,wn,xn,Jr,Yr];function Ip(){return ts(()=>{let t=Xs().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...Ap,...t]},[])}function Pp({group:e}){let t=e.actions[0];return t?.integration?ue(Wt,{className:"size-4",integration:t.integration}):e.category==="System"?ue(Il,{className:"size-4"}):ue(Pl,{className:"size-4"})}function Ep({action:e,className:t}){return e.integration?ue(Wt,{className:t,integration:e.integration}):e.category==="System"?ue(Il,{className:N(t,"text-muted-foreground")}):ue(Pl,{className:N(t,"text-muted-foreground")})}var El="workflow-action-grid-hidden-groups",Dl="workflow-action-grid-view-mode";function Dp(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(El);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function Rp(){if(typeof window>"u")return"list";try{return localStorage.getItem(Dl)==="grid"?"grid":"list"}catch{return"list"}}function Qr({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=Zn(""),[i,a]=Zn(new Set),[l,s]=Zn(Dp),[d,c]=Zn(!1),[u,f]=Zn(Rp),v=Ip(),C=Sp(null),h=hl(),y=()=>{let x=u==="list"?"grid":"list";f(x),localStorage.setItem(Dl,x)},m=x=>{a(p=>{let w=new Set(p);return w.has(x)?w.delete(x):w.add(x),w})},b=x=>{s(p=>{let w=new Set(p);return w.has(x)?w.delete(x):w.add(x),localStorage.setItem(El,JSON.stringify([...w])),w})};Tp(()=>{o&&h===!1&&C.current&&C.current.focus()},[o,h]);let g=v.filter(x=>{let p=n.toLowerCase();return x.label.toLowerCase().includes(p)||x.description.toLowerCase().includes(p)||x.category.toLowerCase().includes(p)}),S=ts(()=>{let x={};for(let w of g){let G=w.category;x[G]||(x[G]=[]),x[G].push(w)}return Object.keys(x).sort((w,G)=>w==="System"?-1:G==="System"?1:w.localeCompare(G)).map(w=>({category:w,actions:x[w]}))},[g]),D=ts(()=>d?S:S.filter(x=>!l.has(x.category)),[S,l,d]),I=l.size;return it("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[it("div",{className:"flex shrink-0 gap-2",children:[it("div",{className:"relative flex-1",children:[ue(Cp,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),ue(ae,{className:"pl-9","data-testid":"action-search-input",disabled:t,id:"action-filter",onChange:x=>r(x.target.value),placeholder:"Search actions...",ref:C,value:n})]}),ue(hn,{children:it(jn,{children:[ue(Jn,{asChild:!0,children:ue(E,{className:"shrink-0",onClick:y,size:"icon",variant:"ghost",children:u==="list"?ue(xp,{className:"size-4"}):ue(Np,{className:"size-4"})})}),ue(Yn,{children:u==="list"?"Grid view":"List view"})]})}),I>0&&ue(hn,{children:it(jn,{children:[ue(Jn,{asChild:!0,children:ue(E,{className:N("shrink-0",d&&"bg-muted"),onClick:()=>c(!d),size:"icon",variant:"ghost",children:d?ue(Tl,{className:"size-4"}):ue(Sl,{className:"size-4"})})}),ue(Yn,{children:d?"Hide hidden groups":`Show ${I} hidden group${I>1?"s":""}`})]})})]}),it("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[g.length===0&&ue("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),g.length>0&&D.length===0&&ue("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"All groups are hidden"}),u==="grid"&&D.length>0&&ue("div",{className:"grid gap-2 p-1",style:{gridTemplateColumns:"repeat(auto-fill, minmax(72px, 1fr))"},children:g.filter(x=>d||!l.has(x.category)).map(x=>it("button",{className:N("flex aspect-square flex-col items-center justify-center gap-1.5 rounded-lg border border-transparent p-2 text-center transition-colors hover:border-border hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${x.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(x.id),type:"button",children:[ue(Ep,{action:x,className:"size-6"}),ue("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:x.label})]},x.id))}),u==="list"&&D.length>0&&D.map((x,p)=>{let w=i.has(x.category),G=l.has(x.category);return it("div",{children:[p>0&&ue("div",{className:"my-2 h-px bg-border"}),it("div",{className:N("sticky top-0 z-10 mb-1 flex items-center gap-2 bg-background px-3 py-2 font-medium text-muted-foreground text-xs uppercase tracking-wider",G&&"opacity-50"),children:[it("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>m(x.category),type:"button",children:[ue(wp,{className:N("size-3.5 transition-transform",!w&&"rotate-90")}),ue(Pp,{group:x}),x.category]}),it(Ro,{children:[ue(Oo,{asChild:!0,children:ue("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:ue(kp,{className:"size-4"})})}),ue(Lo,{align:"end",children:ue(xt,{onClick:()=>b(x.category),children:G?it(Al,{children:[ue(Tl,{className:"mr-2 size-4"}),"Show group"]}):it(Al,{children:[ue(Sl,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!w&&x.actions.map(te=>ue("button",{className:N("flex w-full items-center rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-muted",t&&"pointer-events-none opacity-50"),"data-testid":`action-option-${te.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(te.id),type:"button",children:it("span",{className:"min-w-0 flex-1 truncate",children:[ue("span",{className:"font-medium",children:te.label}),te.description&&it("span",{className:"text-muted-foreground text-xs",children:[" ","- ",te.description]})]})},te.id))]},x.category)})]})]})}import{Clock as Lp,Copy as Mp,Play as Wp,Webhook as Fp}from"lucide-react";import{toast as zp}from"sonner";import{jsx as er,jsxs as Rl}from"react/jsx-runtime";var Op=[{label:"North America",zones:[{value:"America/New_York",label:"Eastern Time (ET)"},{value:"America/Chicago",label:"Central Time (CT)"},{value:"America/Denver",label:"Mountain Time (MT)"},{value:"America/Phoenix",label:"Arizona Time (MST)"},{value:"America/Los_Angeles",label:"Pacific Time (PT)"},{value:"America/Anchorage",label:"Alaska Time (AKT)"},{value:"Pacific/Honolulu",label:"Hawaii Time (HST)"},{value:"America/Toronto",label:"Toronto"},{value:"America/Vancouver",label:"Vancouver"}]},{label:"Europe",zones:[{value:"Europe/London",label:"London (GMT/BST)"},{value:"Europe/Paris",label:"Paris (CET/CEST)"},{value:"Europe/Berlin",label:"Berlin (CET/CEST)"},{value:"Europe/Rome",label:"Rome (CET/CEST)"},{value:"Europe/Madrid",label:"Madrid (CET/CEST)"},{value:"Europe/Amsterdam",label:"Amsterdam (CET/CEST)"},{value:"Europe/Brussels",label:"Brussels (CET/CEST)"},{value:"Europe/Stockholm",label:"Stockholm (CET/CEST)"},{value:"Europe/Warsaw",label:"Warsaw (CET/CEST)"},{value:"Europe/Athens",label:"Athens (EET/EEST)"},{value:"Europe/Moscow",label:"Moscow (MSK)"}]},{label:"Asia",zones:[{value:"Asia/Dubai",label:"Dubai (GST)"},{value:"Asia/Kolkata",label:"India (IST)"},{value:"Asia/Shanghai",label:"China (CST)"},{value:"Asia/Hong_Kong",label:"Hong Kong (HKT)"},{value:"Asia/Tokyo",label:"Tokyo (JST)"},{value:"Asia/Seoul",label:"Seoul (KST)"},{value:"Asia/Singapore",label:"Singapore (SGT)"},{value:"Asia/Bangkok",label:"Bangkok (ICT)"},{value:"Asia/Jakarta",label:"Jakarta (WIB)"}]},{label:"Australia & Pacific",zones:[{value:"Australia/Sydney",label:"Sydney (AEDT/AEST)"},{value:"Australia/Melbourne",label:"Melbourne (AEDT/AEST)"},{value:"Australia/Brisbane",label:"Brisbane (AEST)"},{value:"Australia/Perth",label:"Perth (AWST)"},{value:"Pacific/Auckland",label:"Auckland (NZDT/NZST)"}]},{label:"South America",zones:[{value:"America/Sao_Paulo",label:"S\xE3o Paulo (BRT)"},{value:"America/Argentina/Buenos_Aires",label:"Buenos Aires (ART)"},{value:"America/Santiago",label:"Santiago (CLT)"},{value:"America/Bogota",label:"Bogot\xE1 (COT)"},{value:"America/Lima",label:"Lima (PET)"}]},{label:"Africa & Middle East",zones:[{value:"Africa/Cairo",label:"Cairo (EET)"},{value:"Africa/Johannesburg",label:"Johannesburg (SAST)"},{value:"Africa/Lagos",label:"Lagos (WAT)"},{value:"Africa/Nairobi",label:"Nairobi (EAT)"},{value:"Asia/Jerusalem",label:"Jerusalem (IST)"}]},{label:"Other",zones:[{value:"UTC",label:"UTC (Coordinated Universal Time)"}]}];function Ol({value:e,onValueChange:t,disabled:o,id:n}){return Rl(ve,{value:e,onValueChange:t,disabled:o,children:[er(he,{id:n,children:er(xe,{placeholder:"Select timezone"})}),er(be,{children:Op.map(r=>Rl(Pi,{children:[er(Ei,{children:r.label}),r.zones.map(i=>er(Z,{value:i.value,children:i.label},i.value))]},r.label))})]})}import{Fragment as os,jsx as Ee,jsxs as lt}from"react/jsx-runtime";function Zr({config:e,onUpdateConfig:t,disabled:o,workflowId:n}){let r=n?`${typeof window<"u"?window.location.origin:""}/api/workflows/${n}/webhook`:"",i=()=>{r&&(navigator.clipboard.writeText(r),zp.success("Webhook URL copied to clipboard"))};return lt(os,{children:[lt("div",{className:"space-y-2",children:[Ee(M,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),lt(ve,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[Ee(he,{className:"w-full",id:"triggerType",children:Ee(xe,{placeholder:"Select trigger type"})}),lt(be,{children:[Ee(Z,{value:"Manual",children:lt("div",{className:"flex items-center gap-2",children:[Ee(Wp,{className:"h-4 w-4"}),"Manual"]})}),Ee(Z,{value:"Schedule",children:lt("div",{className:"flex items-center gap-2",children:[Ee(Lp,{className:"h-4 w-4"}),"Schedule"]})}),Ee(Z,{value:"Webhook",children:lt("div",{className:"flex items-center gap-2",children:[Ee(Fp,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&<(os,{children:[lt("div",{className:"space-y-2",children:[Ee(M,{className:"ml-1",children:"Webhook URL"}),lt("div",{className:"flex gap-2",children:[Ee(ae,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),Ee(E,{disabled:!r,onClick:i,size:"icon",variant:"outline",children:Ee(Mp,{className:"h-4 w-4"})})]})]}),lt("div",{className:"space-y-2",children:[Ee(M,{children:"Request Schema (Optional)"}),Ee(co,{disabled:o,onChange:a=>t("webhookSchema",JSON.stringify(a)),schema:e?.webhookSchema?JSON.parse(e.webhookSchema):[]}),Ee("p",{className:"text-muted-foreground text-xs",children:"Define the expected structure of the incoming webhook payload."})]}),lt("div",{className:"space-y-2",children:[Ee(M,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),Ee("div",{className:"overflow-hidden rounded-md border",children:Ee(yt,{defaultLanguage:"json",height:"150px",onChange:a=>t("webhookMockRequest",a||""),options:{minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,readOnly:o,wordWrap:"on"},value:e?.webhookMockRequest||""})}),Ee("p",{className:"text-muted-foreground text-xs",children:"Enter a sample JSON payload to test the webhook trigger."})]})]}),e?.triggerType==="Schedule"&<(os,{children:[lt("div",{className:"space-y-2",children:[Ee(M,{className:"ml-1",htmlFor:"scheduleCron",children:"Cron Expression"}),Ee(ae,{disabled:o,id:"scheduleCron",onChange:a=>t("scheduleCron",a.target.value),placeholder:"0 9 * * * (every day at 9am)",value:e?.scheduleCron||""})]}),lt("div",{className:"space-y-2",children:[Ee(M,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),Ee(Ol,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var Ll={"Database Query":jo.codeGenerator,"HTTP Request":Jo.codeGenerator,Condition:qo.codeGenerator,Switch:xn.codeGenerator,Merge:wn.codeGenerator},ns=`async function actionStep(input: Record<string, unknown>) {
|
|
187
177
|
"use step";
|
|
188
178
|
|
|
189
179
|
console.log('Executing action');
|
|
190
180
|
return { success: true };
|
|
191
|
-
}`,
|
|
181
|
+
}`,Bp=`async function unknownStep(input: Record<string, unknown>) {
|
|
192
182
|
"use step";
|
|
193
183
|
|
|
194
184
|
return input;
|
|
195
|
-
}`;function
|
|
185
|
+
}`;function Vp(e,t){let o=e?.triggerType||"Manual";if(o==="Schedule"){let n=e?.scheduleCron||"0 9 * * *";return`{
|
|
196
186
|
"crons": [
|
|
197
187
|
{
|
|
198
188
|
"path": "${t?`/api/workflow-builder/workflow/${t}/cron`:"/api/workflow-builder/workflow/<workflowId>/cron"}",
|
|
@@ -208,7 +198,7 @@ export async function POST(request: NextRequest) {
|
|
|
208
198
|
await executeWorkflow(body);
|
|
209
199
|
|
|
210
200
|
return Response.json({ success: true });
|
|
211
|
-
}`:""}function Wp(e){if(!e)return es;if(Dl[e])return Dl[e];let t=fe(e);return t&&t.codegenTemplate||es}var vn=(e,t)=>e.data.type==="trigger"?Fp(e.data.config,t):e.data.type==="action"?Wp(e.data.config?.actionType):Mp;import{useAtom as ts}from"jotai";import{Check as Ml,ChevronDown as ns,ChevronRight as rs,Clock as Vp,Copy as Gp,ExternalLink as Hp,Loader2 as $p,Play as _p,Square as Ol,X as Up}from"lucide-react";import Ll from"next/image";import{useCallback as Yn,useEffect as Qr,useRef as Kp,useState as Oo}from"react";function hn(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function Rl(e){let t=new Date,o=new Date(e),n=Math.floor((t.getTime()-o.getTime())/1e3);if(n<60)return"just now";let r=Math.floor(n/60);if(r<60)return hn(r,"min");let s=Math.floor(r/60);if(s<24)return hn(s,"hour");let a=Math.floor(s/24);if(a<7)return hn(a,"day");let d=Math.floor(a/7);if(d<4)return hn(d,"week");let i=Math.floor(a/30);if(i<12)return hn(i,"month");let l=Math.floor(a/365);return hn(l,"year")}import{Loader2Icon as zp}from"lucide-react";import{jsx as Bp}from"react/jsx-runtime";function Tt({className:e,...t}){let{ref:o,...n}=t;return Bp(zp,{role:"status","aria-label":"Loading",className:x("size-4 animate-spin",e),...n})}import{Fragment as ea,jsx as H,jsxs as ze}from"react/jsx-runtime";function qp(e){return Ks(e)}function jp(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function Jp(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function os(e){let t={};for(let o of e)t[o.nodeId]={nodeId:o.nodeId,nodeName:o.nodeName,nodeType:o.nodeType,status:o.status,output:o.output};return t}function Yp(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Fl({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return H(ea,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(Yp(r))return H("a",{className:"text-blue-500 underline hover:text-blue-400",href:r,rel:"noopener noreferrer",target:"_blank",children:n},r)}return n})})}function Xp({data:e,isError:t=!1}){let[o,n]=Oo(!1);return H(D,{className:"h-7 px-2",onClick:async s=>{s.stopPropagation();try{let a=t?String(e):JSON.stringify(e,null,2);await navigator.clipboard.writeText(a),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}},size:"sm",type:"button",variant:"ghost",children:o?H(Ml,{className:"h-3 w-3 text-green-600"}):H(Gp,{className:"h-3 w-3"})})}function Zr({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:s}){let[a,d]=Oo(o);return ze("div",{children:[ze("div",{className:"mb-2 flex w-full items-center justify-between",children:[ze("button",{className:"flex items-center gap-1.5",onClick:()=>d(!a),type:"button",children:[a?H(ns,{className:"h-3 w-3 text-muted-foreground"}):H(rs,{className:"h-3 w-3 text-muted-foreground"}),H("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),ze("div",{className:"flex items-center gap-1",children:[s&&H(D,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:H("a",{href:s,rel:"noopener noreferrer",target:"_blank",children:H(Hp,{className:"h-3 w-3"})})}),n!==void 0&&H(Xp,{data:n,isError:r})]})]}),a&&t]})}function Qp({output:e,input:t,actionType:o}){let r=(o?fe(o):void 0)?.outputConfig,s=o?qp(o):void 0,a=r?.type!=="component"?r:s,d=a?jp(e,a):void 0,i=!(r||s)&&Jp(e),c=(()=>{if(r?.type==="component"){let h=r.component;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(h,{input:t,output:e})})}if(a&&d)switch(a.type){case"image":{let h=a.field==="base64"&&!d.startsWith("data:")?`data:image/png;base64,${d}`:d;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(Ll,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:h,unoptimized:!0,width:384})})}case"video":return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H("video",{className:"max-h-96 w-auto rounded",controls:!0,src:d,children:H("track",{kind:"captions"})})});case"url":return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50",children:H("iframe",{className:"h-96 w-full rounded",sandbox:"allow-scripts allow-same-origin",src:d,title:"Output preview"})});default:return null}return i?H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(Ll,{alt:"AI generated output",className:"max-h-96 w-auto rounded",height:384,src:`data:image/png;base64,${e.base64}`,unoptimized:!0,width:384})}):null})(),u=c!==null,f=a?.type==="url"&&d?d:void 0;return ze(ea,{children:[H(Zr,{copyData:e,title:"Output",children:H("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:H(Fl,{data:e})})}),u&&H(Zr,{defaultExpanded:!0,externalLink:f,title:"Result",children:c})]})}function Zp({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:s,isLast:a}){return ze("div",{className:"relative flex gap-3",children:[ze("div",{className:"relative -ml-px flex flex-col items-center pt-2",children:[!s&&H("div",{className:"absolute bottom-full h-2 w-px bg-border"}),H("div",{className:x("z-10 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-0",r(e.status)),children:n(e.status)}),!a&&H("div",{className:"absolute top-[calc(0.5rem+1.25rem)] bottom-0 w-px bg-border"})]}),ze("div",{className:"min-w-0 flex-1",children:[H("button",{className:"group w-full rounded-lg py-2 text-left transition-colors hover:bg-muted/50",onClick:o,type:"button",children:ze("div",{className:"flex items-center gap-3",children:[H("div",{className:"min-w-0 flex-1",children:ze("div",{className:"flex items-center gap-2",children:[t?H(ns,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):H(rs,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),H("span",{className:"truncate font-medium text-sm transition-colors group-hover:text-foreground",children:e.nodeName||e.nodeType})]})}),e.duration&&H("span",{className:"shrink-0 font-mono text-muted-foreground text-xs tabular-nums",children:Number.parseInt(e.duration,10)<1e3?`${e.duration}ms`:`${(Number.parseInt(e.duration,10)/1e3).toFixed(2)}s`})]})}),t&&ze("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&H(Zr,{copyData:e.input,title:"Input",children:H("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:H(Fl,{data:e.input})})}),e.output!==null&&e.output!==void 0&&H(Qp,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&H(Zr,{copyData:e.error,defaultExpanded:!0,isError:!0,title:"Error",children:H("pre",{className:"overflow-auto rounded-lg border border-red-500/20 bg-red-500/5 p-3 font-mono text-red-600 text-xs leading-relaxed",children:e.error})}),!(e.input||e.output||e.error)&&H("div",{className:"rounded-lg border bg-muted/30 py-4 text-center text-muted-foreground text-xs",children:"No data recorded"})]})]})]},e.id)}function bn({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=ts(Ue),[r,s]=ts(no),[,a]=ts(Jo),[d,i]=Oo([]),[l,c]=Oo({}),[u,f]=Oo(new Set),[h,k]=Oo(new Set),[b,y]=Oo(!0),p=Kp(null),v=Yn(async(L=!0)=>{if(!n){y(!1);return}try{L&&y(!0);let W=await q.workflow.getExecutions(n);i(W)}catch(W){console.error("Failed to load executions:",W),i([])}finally{L&&y(!1)}},[n]);Qr(()=>{t&&(t.current=()=>v(!1))},[v,t]),Qr(()=>{v()},[v]);let g=Yn((L,W)=>L.map($=>({id:$.id,nodeId:$.nodeId,nodeName:$.nodeName,nodeType:$.nodeType,status:$.status,startedAt:new Date($.startedAt),completedAt:$.completedAt?new Date($.completedAt):null,duration:$.duration,input:$.input,output:$.output,error:$.error})),[]),C=Yn(async L=>{try{let W=await q.workflow.getExecutionLogs(L),$=g(W.logs,W.execution.workflow);c(P=>({...P,[L]:$})),L===r&&a(os($))}catch(W){console.error("Failed to load execution logs:",W),c($=>({...$,[L]:[]}))}},[g,r,a]);Qr(()=>{if(d.length===0)return;let L=d[0];L.status==="running"&&L.id!==p.current&&(p.current=L.id,s(L.id),f(W=>{let $=new Set(W);return $.add(L.id),$}),C(L.id),o&&o(L.id))},[d,s,C,o]);let I=Yn(async L=>{try{let W=await q.workflow.getExecutionLogs(L),$=g(W.logs,W.execution.workflow);c(P=>({...P,[L]:$})),L===r&&a(os($))}catch(W){console.error(`Failed to refresh logs for ${L}:`,W)}},[g,r,a]);Qr(()=>{if(!(e&&n))return;let W=setInterval(async()=>{try{let $=await q.workflow.getExecutions(n);i($);for(let P of u)await I(P)}catch($){console.error("Failed to poll executions:",$)}},2e3);return()=>clearInterval(W)},[e,n,u,I]);let A=Yn(async L=>{try{await q.workflow.cancelExecution(L),await v(!1)}catch(W){console.error("Failed to cancel execution:",W)}},[v]),w=async L=>{let W=new Set(u);W.has(L)?W.delete(L):(W.add(L),await C(L)),f(W)},m=L=>{if(r===L){s(null),a({});return}s(L);let W=l[L]||[];a(os(W))},S=L=>{let W=new Set(h);W.has(L)?W.delete(L):W.add(L),k(W)},X=L=>{switch(L){case"success":return H(Ml,{className:"h-3 w-3 text-white"});case"error":return H(Up,{className:"h-3 w-3 text-white"});case"cancelled":return H(Ol,{className:"h-3 w-3 text-white"});case"running":return H($p,{className:"h-3 w-3 animate-spin text-white"});default:return H(Vp,{className:"h-3 w-3 text-white"})}},le=L=>{switch(L){case"success":return"bg-green-600";case"error":return"bg-red-600";case"cancelled":return"bg-yellow-600";case"running":return"bg-blue-600";default:return"bg-muted-foreground"}};return b?H("div",{className:"flex items-center justify-center py-12",children:H(Tt,{})}):d.length===0?ze("div",{className:"flex flex-col items-center justify-center py-16",children:[H("div",{className:"mb-3 rounded-lg border border-dashed p-4",children:H(_p,{className:"h-6 w-6 text-muted-foreground"})}),H("div",{className:"font-medium text-foreground text-sm",children:"No runs yet"}),H("div",{className:"mt-1 text-muted-foreground text-xs",children:"Execute your workflow to see runs here"})]}):H("div",{className:"space-y-3",children:d.map((L,W)=>{let $=u.has(L.id),P=r===L.id,V=(l[L.id]||[]).sort((J,F)=>new Date(J.startedAt).getTime()-new Date(F.startedAt).getTime());return ze("div",{className:x("overflow-hidden rounded-lg border bg-card transition-all",P&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[ze("div",{className:"flex w-full items-center gap-3 p-4",children:[H("button",{className:"flex size-5 shrink-0 items-center justify-center rounded-full border-0 transition-colors hover:bg-muted",onClick:()=>w(L.id),type:"button",children:H("div",{className:x("flex size-5 items-center justify-center rounded-full border-0",le(L.status)),children:X(L.status)})}),ze("button",{className:"min-w-0 flex-1 text-left transition-colors hover:opacity-80",onClick:()=>m(L.id),type:"button",children:[H("div",{className:"mb-1 flex items-center gap-2",children:ze("span",{className:"font-semibold text-sm",children:["Run #",d.length-W]})}),ze("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[H("span",{children:Rl(L.startedAt)}),L.duration&&ze(ea,{children:[H("span",{children:"\u2022"}),H("span",{className:"tabular-nums",children:Number.parseInt(L.duration,10)<1e3?`${L.duration}ms`:`${(Number.parseInt(L.duration,10)/1e3).toFixed(2)}s`})]}),V.length>0&&ze(ea,{children:[H("span",{children:"\u2022"}),ze("span",{children:[V.length," ",V.length===1?"step":"steps"]})]})]})]}),(L.status==="running"||L.status==="pending")&&H("button",{className:"flex shrink-0 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",onClick:J=>{J.stopPropagation(),A(L.id)},title:"Stop execution",type:"button",children:H(Ol,{className:"h-3.5 w-3.5"})}),H("button",{className:"flex shrink-0 items-center justify-center rounded p-1 transition-colors hover:bg-muted",onClick:()=>w(L.id),type:"button",children:$?H(ns,{className:"h-4 w-4 text-muted-foreground"}):H(rs,{className:"h-4 w-4 text-muted-foreground"})})]}),$&&H("div",{className:"border-t bg-muted/20",children:V.length===0?H("div",{className:"py-8 text-center text-muted-foreground text-xs",children:"No steps recorded"}):H("div",{className:"p-4",children:V.map((J,F)=>H(Zp,{getStatusDotClass:le,getStatusIcon:X,isExpanded:h.has(J.id),isFirst:F===0,isLast:F===V.length-1,log:J,onToggle:()=>S(J.id)},J.id))})})]},L.id)})})}import{Fragment as go,jsx as O,jsxs as U}from"react/jsx-runtime";var rf=/[^a-zA-Z0-9\s]/g,af=/\s+/,Hl={"Database Query":"database"},sf=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=Xn(!1),s=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",d=[];e.length>0&&d.push(`${e.length} ${s}`),t.length>0&&d.push(`${t.length} ${a}`);let i=d.join(" and ");return U(go,{children:[U("div",{className:"flex size-full flex-col",children:[O("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:O("h2",{className:"font-semibold text-foreground",children:"Properties"})}),U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{children:"Selection"}),U("p",{className:"text-muted-foreground text-sm",children:[i," selected"]})]}),O("div",{className:"flex items-center gap-2 pt-4",children:U(D,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(Xo,{onOpenChange:r,open:n,children:U(Qo,{children:[U(Zo,{children:[O(tn,{children:"Delete Selected Items"}),U(on,{children:["Are you sure you want to delete ",i,"? This action cannot be undone."]})]}),U(en,{children:[O(rn,{children:"Cancel"}),O(nn,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},lf=()=>{let[e]=po(ke),[t]=po(_e),[o]=po(ne),n=as(ue),[r]=po(Nt),[s]=po(Ue),[a,d]=po(gt),i=as(oo),l=fo(ro),c=fo(ao),u=fo(so),f=fo(li),h=fo(di),k=fo(ci),b=fo(Cr),y=fo(wr),[p,v]=po(to),[g,C]=Xn(!1),[I,A]=Xn(!1),[w,m]=Xn(!1),[S,X]=Xn(!1),[le,L]=po(Bt),W=Gl(null),$=Gl({}),P=o.find(ee=>ee.id===e),V=n.find(ee=>ee.id===t),J=o.filter(ee=>ee.selected),F=n.filter(ee=>ee.selected),K=J.length+F.length>1;Vl(()=>{if(!P||le!=="code")return;let ee=P.data.config?.actionType==="Condition",xe=P.data.type==="trigger"&&P.data.config?.triggerType==="Manual";(ee||xe)&&L("properties")},[P,le,L]);let T=as(ft);Vl(()=>{if(!(P&&i))return;let ee=P.data.config?.actionType,xe=P.data.config?.integrationId;if(!(ee&&xe))return;let E=fe(ee)?.integration||Hl[ee];if(!E||T.some(ce=>ce.id===xe))return;let Y=T.filter(ce=>ce.type===E);if(Y.length===1){let ce={...P.data.config,integrationId:Y[0].id};l({id:P.id,data:{config:ce}})}else if(Y.length===0){let ce={...P.data.config,integrationId:void 0};l({id:P.id,data:{config:ce}})}},[P,T,i,l]);let z=nf(()=>{let xe=`${a.replace(rf,"").split(af).map((E,_)=>_===0?E.toLowerCase():E.charAt(0).toUpperCase()+E.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:Q}=cr(o,n,{functionName:xe});return Q},[o,n,a]),N=()=>{P&&navigator.clipboard.writeText(vn(P))},R=()=>{navigator.clipboard.writeText(z),ta.success("Code copied to clipboard")},G=()=>{e&&(c(e),C(!1))},oe=()=>{if(P){let ee=P.data.enabled??!0;l({id:P.id,data:{enabled:!ee}})}},de=()=>{t&&(u(t),A(!1))},B=async()=>{if(s)try{await q.workflow.deleteExecutions(s),b(),m(!1)}catch(ee){console.error("Failed to delete runs:",ee);let xe=ee instanceof Error?ee.message:"Failed to delete runs";ta.error(xe)}},Ae=ee=>{P&&l({id:P.id,data:{label:ee}})},Je=ee=>{P&&l({id:P.id,data:{description:ee}})},Ye=of(async(ee,xe,Q,E)=>{let Y=fe(xe)?.integration||Hl[xe];if(!Y){y(ce=>{let Ee=new Set(ce);return Ee.delete(ee),Ee});return}try{let ce=await q.integration.getAll();if(E.aborted)return;let Ee=ce.filter(Le=>Le.type===Y);if(Ee.length===1&&!E.aborted){let Le={...Q,actionType:xe,integrationId:Ee[0].id};l({id:ee,data:{config:Le}})}}catch(ce){console.error("Failed to auto-select integration:",ce)}finally{E.aborted||y(ce=>{let Ee=new Set(ce);return Ee.delete(ee),Ee})}},[l,y]),$e=(ee,xe)=>{if(P){let Q={...P.data.config,[ee]:xe};if(ee==="actionType"&&P.data.config?.integrationId&&(Q={...Q,integrationId:void 0}),l({id:P.id,data:{config:Q}}),ee==="actionType"){let E=$.current[P.id];E&&E.abort();let _=new AbortController;$.current[P.id]=_,y(Y=>new Set(Y).add(P.id)),Ye(P.id,xe,Q,_.signal)}}},Zt=async ee=>{if(d(ee),s)try{await q.workflow.update(s,{name:ee,nodes:o,edges:n})}catch(xe){console.error("Failed to update workflow name:",xe),ta.error("Failed to update workspace name")}},Et=async()=>{X(!0);try{W.current&&await W.current()}catch(ee){console.error("Failed to refresh runs:",ee),ta.error("Failed to refresh runs")}finally{X(!1)}};return K?O(sf,{onDelete:f,selectedEdges:F,selectedNodes:J}):V?U(go,{children:[U("div",{className:"flex size-full flex-col",children:[O("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:O("h2",{className:"font-semibold text-foreground",children:"Properties"})}),U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),O(se,{disabled:!0,id:"edge-id",value:V.id})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),O(se,{disabled:!0,id:"edge-source",value:V.source})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),O(se,{disabled:!0,id:"edge-target",value:V.target})]}),i&&O("div",{className:"flex items-center gap-2 pt-4",children:U(D,{className:"text-muted-foreground",onClick:()=>A(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(Xo,{onOpenChange:A,open:I,children:U(Qo,{children:[U(Zo,{children:[O(tn,{children:"Delete Edge"}),O(on,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),U(en,{children:[O(rn,{children:"Cancel"}),O(nn,{onClick:de,children:"Delete"})]})]})})]}):P?U(go,{children:[U(Ia,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:L,value:le,children:[U(Pa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),(P.data.type!=="trigger"||P.data.config?.triggerType!=="Manual")&&P.data.config?.actionType!=="Condition"?O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,i&&O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),U(ko,{className:"flex flex-col overflow-hidden",value:"properties",children:[P.data.type==="action"&&!P.data.config?.actionType&&i&&O("div",{className:"flex min-h-0 flex-1 flex-col px-4 pt-4",children:O(Yr,{disabled:r,isNewlyCreated:P?.id===p,onSelectAction:ee=>{$e("actionType",ee),P?.id===p&&v(null)}})}),!(P.data.type==="action"&&!P.data.config?.actionType&&i)&&U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),O(se,{readOnly:!0,id:"node-id",value:P?.id||""})]}),P.data.type==="trigger"&&O(Xr,{config:P.data.config||{},disabled:r||!i,onUpdateConfig:$e,workflowId:s??void 0}),P.data.type==="action"&&!P.data.config?.actionType&&!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"No action configured for this step."})}),P.data.type==="action"&&P.data.config?.actionType?O($r,{config:P.data.config||{},disabled:r||!i,isOwner:i,onUpdateConfig:$e}):null,P.data.type!=="action"||P.data.config?.actionType?U(go,{children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"label",children:"Label"}),O(se,{disabled:r||!i,id:"label",onChange:ee=>Ae(ee.target.value),value:P.data.label})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"description",children:"Description"}),O(se,{disabled:r||!i,id:"description",onChange:ee=>Je(ee.target.value),placeholder:"Optional description",value:P.data.description||""})]})]}):null,!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&U("div",{className:"flex items-center gap-2 pt-4",children:[P.data.type==="action"&&O(D,{className:"text-muted-foreground",onClick:oe,size:"sm",variant:"ghost",children:P.data.enabled===!1?U(go,{children:[O(tf,{className:"mr-2 size-4"}),"Disabled"]}):U(go,{children:[O(ef,{className:"mr-2 size-4"}),"Enabled"]})}),U(D,{className:"text-muted-foreground",onClick:()=>C(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),O(ko,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let ee=P.data.config?.triggerType,xe="",Q="typescript";return P.data.type==="trigger"?ee==="Schedule"?(xe="vercel.json",Q="json"):ee==="Webhook"&&(xe=`app/api${P.data.config?.webhookPath||"/webhook"}/route.ts`,Q="typescript"):xe=`steps/${P.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,U(go,{children:[xe&&U("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[U("div",{className:"flex items-center gap-2",children:[O(zl,{className:"size-3.5 text-muted-foreground"}),O("code",{className:"text-muted-foreground text-xs",children:xe})]}),U(D,{className:"text-muted-foreground",onClick:N,size:"sm",variant:"ghost",children:[O(Wl,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(yt,{height:"100%",language:Q,options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:vn(P)})})]})})()}),i&&U(ko,{className:"flex flex-col overflow-hidden",value:"runs",children:[U("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[U(D,{className:"text-muted-foreground",disabled:S,onClick:Et,size:"sm",variant:"ghost",children:[O(Bl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(D,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(bn,{isActive:le==="runs",onRefreshRef:W})})]})]}),O(Xo,{onOpenChange:m,open:w,children:U(Qo,{children:[U(Zo,{children:[O(tn,{children:"Delete All Runs"}),O(on,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U(en,{children:[O(rn,{children:"Cancel"}),O(nn,{onClick:B,children:"Delete"})]})]})}),O(Xo,{onOpenChange:C,open:g,children:U(Qo,{children:[U(Zo,{children:[O(tn,{children:"Delete Step"}),O(on,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),U(en,{children:[O(rn,{children:"Cancel"}),O(nn,{onClick:G,children:"Delete"})]})]})})]}):U(go,{children:[U(Ia,{className:"size-full",defaultValue:"properties",onValueChange:L,value:le,children:[U(Pa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),i&&O(No,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),O(ko,{className:"flex flex-col overflow-hidden",value:"properties",children:U("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),O(se,{disabled:!i,id:"workflow-name",onChange:ee=>Zt(ee.target.value),value:a})]}),U("div",{className:"space-y-2",children:[O(M,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),O(se,{disabled:!0,id:"workflow-id",value:s||"Not saved"})]}),!i&&O("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:O("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),i&&U("div",{className:"flex items-center gap-2 pt-4",children:[U(D,{className:"text-muted-foreground",onClick:()=>h(!0),size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear"]}),U(D,{className:"text-muted-foreground",onClick:()=>k(!0),size:"sm",variant:"ghost",children:[O(oa,{className:"mr-2 size-4"}),"Delete"]})]})]})}),i&&U(ko,{className:"flex flex-col overflow-hidden",value:"runs",children:[U("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[U(D,{className:"text-muted-foreground",disabled:S,onClick:Et,size:"sm",variant:"ghost",children:[O(Bl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(D,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(ss,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(bn,{isActive:le==="runs",onRefreshRef:W})})]}),U(ko,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:[U("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[U("div",{className:"flex items-center gap-2",children:[O(zl,{className:"size-3.5 text-muted-foreground"}),U("code",{className:"text-muted-foreground text-xs",children:["workflows/",a.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"workflow",".ts"]})]}),U(D,{className:"text-muted-foreground",onClick:R,size:"sm",variant:"ghost",children:[O(Wl,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(yt,{height:"100%",language:"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!0,wordWrap:"off",padding:{top:16,bottom:16}},value:z})})]})]}),O(Xo,{onOpenChange:m,open:w,children:U(Qo,{children:[U(Zo,{children:[O(tn,{children:"Delete All Runs"}),O(on,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U(en,{children:[O(rn,{children:"Cancel"}),O(nn,{onClick:B,children:"Delete"})]})]})})]})},is=()=>O("div",{className:"hidden size-full flex-col bg-background md:flex",children:O(lf,{})});import{jsx as It,jsxs as na}from"react/jsx-runtime";var cs=({workflowId:e})=>{let t=pf(),o=Vt(),[n,r]=$t(Nt),[s,a]=$t(kr),[d]=$t(ne),[i]=$t(ue),[l]=$t(Ue),[c]=$t(no),u=At(ne),f=At(ue),h=At(Ue),k=At(gt),b=At(ro),y=At(nt),[p,v]=$t(ui),g=At(xr),C=At(yr),I=At(vr),[A,w]=$t(hr),[m,S]=$t(ri),X=At(fr),[le,L]=$t(oo),W=At(ft),$=At(pr),P=df(Rt),[V,J]=ls(30),[F,K]=ls(A),[T,z]=ls(!1),N=Lo(!1),R=Lo(!1);St(()=>{if(R.current)return;R.current=!0;let E=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-width="));if(E){let Y=Number.parseFloat(E.split("=")[1]);!Number.isNaN(Y)&&Y>=20&&Y<=50&&J(Y)}let _=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-collapsed="));_&&S(_.split("=")[1]==="true")},[S]);let G=Lo(!1);St(()=>{if(!G.current){G.current=!0;return}document.cookie=`sidebar-width=${V}; path=/; max-age=31536000`},[V]),St(()=>{R.current&&(document.cookie=`sidebar-collapsed=${m}; path=/; max-age=31536000`)},[m]),St(()=>{let E=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),A||!E){K(!0),w(!0);return}I(!0);let _=setTimeout(()=>{K(!0),w(!0)},100),Y=setTimeout(()=>I(!1),400);return()=>{clearTimeout(_),clearTimeout(Y),I(!1)}},[A,w,I]),St(()=>{let E=_=>{(_.metaKey||_.ctrlKey)&&_.key==="b"&&(_.preventDefault(),I(!0),S(Y=>!Y),setTimeout(()=>I(!1),350))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[I,S]),St(()=>(C(!o&&F&&!m?`${V}%`:null),()=>{C(null)}),[o,C,V,F,m]);let oe=yo(E=>{E.preventDefault(),N.current=!0,z(!0);let _=ce=>{if(!N.current)return;let Ee=(window.innerWidth-ce.clientX)/window.innerWidth*100;J(Math.min(50,Math.max(20,Ee)))},Y=()=>{N.current=!1,z(!1),document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",_),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),de=Lo(null),B=Lo(null),Ae=Lo(d);St(()=>{Ae.current=d},[d]);let Je=yo(async E=>{r(!0),h(e),k("AI Generated Workflow");try{let _=await q.ai.generate(E),Y=(_.nodes||[]).map(ce=>({...ce,selected:!1}));u(Y),f(_.edges||[]),k(_.name||"AI Generated Workflow"),await q.workflow.update(e,{name:_.name,description:_.description,nodes:_.nodes,edges:_.edges})}catch(_){console.error("Failed to generate workflow:",_),ds.error("Failed to generate workflow")}finally{r(!1)}},[e,r,h,k,u,f]),Ye=yo(async()=>{try{let E=await q.workflow.getById(e);if(!E){v(!0);return}let _=E.nodes.map(Y=>({...Y,selected:!1,data:{...Y.data,status:"idle"}}));u(_),f(E.edges),h(E.id),k(E.name),X(E.visibility??"private"),L(E.isOwner!==!1),y(!1),v(!1)}catch(E){console.error("Failed to load workflow:",E),ds.error("Failed to load workflow")}},[e,u,f,h,k,X,L,y,v]),$e=Lo(null);St(()=>{(async()=>{let _=t?.get("generating")==="true",Y=sessionStorage.getItem("ai-prompt"),ce=sessionStorage.getItem("generating-workflow-id");l===e&&d.length>0||(_&&Y&&ce===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await Je(Y)):await Ye())})()},[e,t,l,d.length,Je,Ye]),St(()=>{if(d.length===0||!l||!le)return;let E=$e.current;if(E&&E.workflowId===l&&E.version===P)return;(async()=>{try{let Y=await q.integration.getAll();W(Y),$(!0);let ce=new Set(Y.map(Le=>Le.id)),Ee=d.map(Le=>yi(Le,Y,ce)).filter(Le=>Le!==null);for(let Le of Ee){let Ln=d.find(Na=>Na.id===Le.nodeId);Ln&&b({id:Le.nodeId,data:{config:{...Ln.data.config,integrationId:Le.newIntegrationId}}})}$e.current={workflowId:l,version:P},Ee.length>0&&y(!0)}catch(Y){console.error("Failed to auto-fix integrations:",Y)}})()},[d,l,P,le,b,W,$,y]);let Zt=yo(async()=>{if(!(!l||n)){a(!0);try{await q.workflow.update(l,{nodes:d,edges:i}),y(!1)}catch(E){console.error("Failed to save workflow:",E),ds.error("Failed to save workflow")}finally{a(!1)}}},[l,d,i,n,a,y]),Et=yo(E=>E.tagName==="INPUT"||E.tagName==="TEXTAREA",[]),ee=yo(E=>E.closest(".monaco-editor")!==null,[]),xe=yo(E=>(E.metaKey||E.ctrlKey)&&E.key==="s"?(E.preventDefault(),E.stopPropagation(),Zt(),!0):!1,[Zt]),Q=yo((E,_)=>(E.metaKey||E.ctrlKey)&&E.key==="Enter"?(Et(_)||ee(_)||(E.preventDefault(),E.stopPropagation(),g(!0)),!0):!1,[g,Et,ee]);return St(()=>{let E=_=>{let Y=_.target;xe(_)||Q(_,Y)};return document.addEventListener("keydown",E,!0),()=>document.removeEventListener("keydown",E,!0)},[xe,Q]),St(()=>()=>{de.current&&clearInterval(de.current),B.current&&clearInterval(B.current)},[]),St(()=>{if(B.current&&(clearInterval(B.current),B.current=null),!c){for(let _ of Ae.current)b({id:_.id,data:{status:"idle"}});return}let E=async()=>{try{let _=await q.workflow.getExecutionStatus(c);for(let Y of _.nodeStatuses)b({id:Y.nodeId,data:{status:Y.status}});_.status!=="running"&&B.current&&(clearInterval(B.current),B.current=null)}catch(_){console.error("Failed to poll selected execution status:",_),B.current&&(clearInterval(B.current),B.current=null)}};return E(),B.current=setInterval(E,500),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[c,b]),na("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[p&&It("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:na("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[It("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),It("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),It(D,{asChild:!0,children:It(mf,{href:"/",children:"New Workflow"})})]})}),!o&&m&&It("button",{className:"pointer-events-auto absolute top-1/2 right-0 z-20 flex size-6 -translate-y-1/2 items-center justify-center rounded-l-full border border-r-0 bg-background shadow-sm transition-colors hover:bg-muted",onClick:()=>{I(!0),S(!1),setTimeout(()=>I(!1),350)},type:"button",children:It(cf,{className:"size-4"})}),!o&&na("div",{className:"pointer-events-auto absolute inset-y-0 right-0 z-20 border-l bg-background transition-transform duration-300 ease-out",style:{width:`${V}%`,transform:F&&!m?"translateX(0)":"translateX(100%)"},children:[na("div",{"aria-orientation":"vertical","aria-valuenow":V,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:oe,role:"separator",tabIndex:0,children:[It("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(T||m)&&It("button",{className:"absolute top-1/2 left-0 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border bg-background opacity-0 shadow-sm transition-opacity hover:bg-muted group-hover:opacity-100",onClick:E=>{E.stopPropagation(),I(!0),S(!0),setTimeout(()=>I(!1),350)},onMouseDown:E=>E.stopPropagation(),type:"button",children:It(uf,{className:"size-4"})})]}),It(is,{})]}),o&&It(is,{})]})};import{useAtomValue as us,useSetAtom as Qn}from"jotai";import{nanoid as yf}from"nanoid";import{useRouter as vf}from"next/navigation";import{useCallback as _l,useEffect as ra,useRef as hf}from"react";import{toast as bf}from"sonner";import{anonymousClient as ff}from"better-auth/client/plugins";import{createAuthClient as gf}from"better-auth/react";var Mo=gf({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[ff()]}),{signIn:m0,signOut:$l,signUp:p0,useSession:wn}=Mo;function wf(){return{id:yf(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var Ul=()=>{let e=vf(),{data:t}=wn(),o=us(ne),n=us(ue),r=Qn(ne),s=Qn(ue),a=Qn(gt),d=Qn(hr),i=Qn(br),l=hf(!1),c=us(gt);ra(()=>{d(!1)},[d]),ra(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=_l(async()=>{t||(await Mo.signIn.anonymous(),await new Promise(h=>setTimeout(h,100)))},[t]),f=_l(()=>{let h=wf();r([h])},[r]);return ra(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:f},draggable:!1,selectable:!1}]),s([]),a("New Workflow"),l.current=!1},[r,s,a,f]),ra(()=>{(async()=>{let k=o.filter(b=>b.type!=="add");if(!(k.length===0||l.current)){l.current=!0;try{await u();let b=await q.workflow.create({name:"Untitled Workflow",description:"",nodes:k,edges:n});sessionStorage.setItem("animate-sidebar","true"),i(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${b.id}`)}catch(b){console.error("Failed to create workflow:",b),bf.error("Failed to create workflow")}}})()},[o,n,e,u,i]),null};import{useRouter as xf}from"next/navigation";import{useEffect as Nf}from"react";var Kl=()=>{let e=xf();return Nf(()=>{(async()=>{try{let n=(await q.workflow.getAll()).filter(r=>r.name!=="__current__");if(n.length>0){let r=n.sort((s,a)=>new Date(a.updatedAt).getTime()-new Date(s.updatedAt).getTime())[0];e.replace(`/workflows/${r.id}`)}else e.replace("/")}catch(o){console.error("Failed to load workflows:",o),e.replace("/")}})()},[e]),null};import{jsx as xn}from"react/jsx-runtime";var Tf=()=>{let t=Cf().slug;return!t||t.length===0?xn(Ul,{}):t[0]==="auth"&&t.length===2?xn("main",{className:"flex items-center justify-center min-h-screen",children:xn(kf,{path:t[1]})}):t[0]==="workflows"&&t.length===1?xn(Kl,{}):t[0]==="workflows"&&t.length===2?xn("div",{className:"pointer-events-none relative z-10",children:xn(cs,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as Qv}from"@xyflow/react";import{Provider as Zv,useSetAtom as eh}from"jotai";import*as xa from"react";import{AnimatePresence as If,LayoutGroup as Jl,motion as kn,useReducedMotion as Yl}from"motion/react";import{useCallback as er,useLayoutEffect as tr,useRef as vo,useState as Xl}from"react";import{Drawer as Zn}from"vaul";import{Dialog as Nn}from"radix-ui";import{XIcon as Af}from"lucide-react";import{jsx as Fo,jsxs as ms}from"react/jsx-runtime";function aa({...e}){return Fo(Nn.Root,{"data-slot":"dialog",...e})}function ps({...e}){return Fo(Nn.Portal,{"data-slot":"dialog-portal",...e})}function Sf({className:e,...t}){return Fo(Nn.Overlay,{"data-slot":"dialog-overlay",className:x("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function ql({className:e,children:t,showCloseButton:o=!0,...n}){return ms(ps,{"data-slot":"dialog-portal",children:[Fo(Sf,{}),ms(Nn.Content,{"data-slot":"dialog-content",className:x("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,o&&ms(Nn.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Fo(Af,{}),Fo("span",{className:"sr-only",children:"Close"})]})]})]})}function jl({className:e,...t}){return Fo(Nn.Title,{"data-slot":"dialog-title",className:x("text-lg leading-none font-semibold",e),...t})}import{jsx as Fe,jsxs as gs}from"react/jsx-runtime";var fs={type:"spring",stiffness:400,damping:35,mass:.8},Pf={type:"spring",stiffness:350,damping:30,mass:.8},Ef={hidden:{opacity:0,scale:.95},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:400,damping:30}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:[.4,0,1,1]}}};function Ql(e,t){return e?"0%":t?"-35%":"100%"}function Zl(e){let t=vo(e),o=vo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),tr(()=>{t.current=e},[e]),o.current}function Df(){let{stack:e,closeAll:t,pop:o}=re(),n=Yl(),[r,s]=Xl(0),a=vo(null),d=vo(!1),i=vo(e),l=Zl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,f=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:i.current.length,renderStackLength:u.length}),tr(()=>{let g=c&&!d.current;if(d.current=c,g&&s(0),a.current){let C=a.current.offsetHeight;C>0&&s(C)}},[e,c]);let h=e[e.length-1],k=n?{duration:.01}:fs,b=l===1,y=er(()=>{h?.options.closeOnBackdropClick!==!1&&t()},[h?.options.closeOnBackdropClick,t]),p=er(g=>{g.key==="Escape"&&h?.options.closeOnEscape!==!1&&o()},[h?.options.closeOnEscape,o]);tr(()=>{if(c)return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[c,p]);let v=er(()=>{console.log("[DesktopOverlay] handleExitComplete called"),i.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&i.current.length===0?null:Fe(If,{onExitComplete:v,children:c&&Fe(aa,{modal:!1,open:!0,children:gs(ps,{forceMount:!0,children:[Fe(kn.div,{animate:{opacity:1},className:"fixed inset-0 z-50 bg-black/60",exit:{opacity:0},initial:{opacity:0},onClick:y,transition:{duration:.2}}),Fe(kn.div,{animate:"visible",className:"fixed top-1/2 left-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 px-4",exit:"exit",initial:"hidden",variants:Ef,children:Fe(Jl,{children:Fe(kn.div,{className:"relative overflow-hidden rounded-xl border bg-background shadow-2xl ring-1 ring-black/5",layout:c,style:{minHeight:r>0?r:"auto"},transition:fs,children:Fe("div",{className:"relative",ref:a,children:u.map((g,C)=>{let I=C===f,A=C<f,m=I&&b&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Fe(kn.div,{animate:{x:Ql(I,A),scale:I?1:.94,opacity:I?1:0},"aria-hidden":!I,className:x("w-full",I?"relative":"pointer-events-none absolute inset-0"),initial:m,transition:k,children:Fe(g.component,{overlayId:g.id,...g.props})},g.id)})})})})})]})})})}function Rf(){let{stack:e,closeAll:t,pop:o}=re(),n=Yl(),[r,s]=Xl(0),a=vo(null),d=vo(!1),i=vo(e),l=Zl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,f=u.length-1;tr(()=>{let g=c&&!d.current;if(d.current=c,g&&s(0),a.current){let C=a.current.offsetHeight;C>0&&s(C)}},[e,c]);let h=e[e.length-1],k=u[f],b=n?{duration:.01}:fs,y=l===1,p=er(g=>{g.key==="Escape"&&h?.options.closeOnEscape!==!1&&o()},[h?.options.closeOnEscape,o]);tr(()=>{if(c)return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[c,p]);let v=er(()=>{c||(i.current=[])},[c]);return Fe(Zn.Root,{onAnimationEnd:v,onOpenChange:g=>{g||t()},open:c,children:gs(Zn.Portal,{children:[Fe(Zn.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),gs(Zn.Content,{className:x("fixed inset-x-0 bottom-0 z-50 flex max-h-[90vh] flex-col","rounded-t-2xl border-t bg-background shadow-2xl"),children:[Fe(Zn.Title,{className:"sr-only",children:k?.options.title||"Dialog"}),Fe("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),Fe(Jl,{children:Fe(kn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:Pf,children:Fe("div",{className:"relative",ref:a,children:u.map((g,C)=>{let I=C===f,A=C<f,m=I&&y&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Fe(kn.div,{animate:{x:Ql(I,A),scale:I?1:.94,opacity:I?1:0},"aria-hidden":!I,className:x("w-full",I?"relative":"pointer-events-none absolute inset-0"),initial:m,transition:b,children:Fe(g.component,{overlayId:g.id,...g.props})},g.id)})})})}),Fe("div",{className:"h-safe-area-inset-bottom"})]})]})})}function ed(){return Vt()?Fe(Rf,{}):Fe(Df,{})}import{useAtom as Of}from"jotai";import{useEffect as Lf,useRef as td}from"react";import{atom as qt}from"jotai";var je=qt([]),Y0=qt(e=>e(je).length>0),X0=qt(e=>e(je).length);function ys(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var Q0=qt(null,(e,t,o)=>{let n=ys(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[r]),n}),Z0=qt(null,(e,t,o)=>{let n=ys(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[...e(je),r]),n}),eT=qt(null,(e,t)=>{let o=e(je);if(o.length<=1){o[0]?.options.onClose?.(),t(je,[]);return}o[o.length-1]?.options.onClose?.(),t(je,o.slice(0,-1))}),tT=qt(null,(e,t,o)=>{let n=e(je),r=ys(),s={id:r,component:o.component,props:o.props??{},options:o.options??{}};return n.length===0?t(je,[s]):(n[n.length-1]?.options.onClose?.(),t(je,[...n.slice(0,-1),s])),r}),oT=qt(null,(e,t)=>{let o=e(je);for(let n of o)n.options.onClose?.();t(je,[])}),nT=qt(null,(e,t,o)=>{let n=e(je),r=n.findIndex(s=>s.id===o);if(r!==-1){for(let s=r;s<n.length;s++)n[s].options.onClose?.();t(je,n.slice(0,r))}});function od(){let{stack:e}=re(),[t,o]=Of(je),n=td(!1),r=td(!1);return Lf(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as Mf,jsx as nd,jsxs as Ff}from"react/jsx-runtime";var rd=()=>Ff(Mf,{children:[nd(ed,{}),nd(od,{})]});import{CircleCheckIcon as Wf,InfoIcon as zf,Loader2Icon as Bf,OctagonXIcon as Vf,TriangleAlertIcon as Gf}from"lucide-react";import{useTheme as Hf}from"next-themes";import{Toaster as $f}from"sonner";import{jsx as Cn}from"react/jsx-runtime";var ad=({...e})=>{let{theme:t="system"}=Hf();return Cn($f,{theme:t,className:"toaster group",icons:{success:Cn(Wf,{className:"size-4"}),info:Cn(zf,{className:"size-4"}),warning:Cn(Gf,{className:"size-4"}),error:Cn(Vf,{className:"size-4"}),loading:Cn(Bf,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},...e})};import{usePathname as Uv}from"next/navigation";import{ConnectionMode as Wv,MiniMap as zv,useReactFlow as Bv}from"@xyflow/react";import{useAtom as dr,useAtomValue as Hs,useSetAtom as wo}from"jotai";import{useCallback as xt,useEffect as wa,useMemo as Vv,useRef as Ho,useState as Sc}from"react";import{Background as _f,ReactFlow as Uf}from"@xyflow/react";import{useAtomValue as Kf}from"jotai";import"@xyflow/react/dist/style.css";import{jsx as qf,jsxs as jf}from"react/jsx-runtime";var sd=({children:e,...t})=>{let o=Kf(jo);return jf(Uf,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,snapToGrid:o.snapToGrid??!0,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[qf(_f,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]})};import{jsx as id,jsxs as Jf}from"react/jsx-runtime";var ld=({fromX:e,fromY:t,toX:o,toY:n})=>Jf("g",{children:[id("path",{className:"animated",d:`M${e},${t} C ${e+(o-e)*.5},${t} ${e+(o-e)*.5},${n} ${o},${n}`,fill:"none",stroke:"var(--color-ring)",strokeWidth:1}),id("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as Zf}from"@xyflow/react";import{useAtom as eg}from"jotai";import{MapPin as tg,MapPinXInside as og,Maximize2 as ng,ZoomIn as rg,ZoomOut as ag}from"lucide-react";import{cva as Yf}from"class-variance-authority";import{Slot as PT}from"radix-ui";import{jsx as Qf}from"react/jsx-runtime";var Xf=Yf("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function _t({className:e,orientation:t,...o}){return Qf("div",{role:"group","data-slot":"button-group","data-orientation":t,className:x(Xf({orientation:t}),e),...o})}import{jsx as jt,jsxs as sg}from"react/jsx-runtime";var dd=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=Zf(),[n,r]=eg(gr);return sg(_t,{orientation:"vertical",children:[jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{e()},size:"icon",title:"Zoom in",variant:"secondary",children:jt(rg,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{t()},size:"icon",title:"Zoom out",variant:"secondary",children:jt(ag,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{o({padding:.2,duration:300})},size:"icon",title:"Fit view",variant:"secondary",children:jt(ng,{className:"size-4"})}),jt(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{r(!n)},size:"icon",title:n?"Hide minimap":"Show minimap",variant:"secondary",children:n?jt(tg,{className:"size-4"}):jt(og,{className:"size-4"})})]})};import{useReactFlow as mg}from"@xyflow/react";import{useAtom as Tn,useAtomValue as pg}from"jotai";import{ArrowUp as fg}from"lucide-react";import{useCallback as gg,useEffect as yg,useRef as ud,useState as vs}from"react";import{toast as hs}from"sonner";import{motion as ig}from"motion/react";import{memo as lg,useMemo as dg}from"react";import{jsx as ug}from"react/jsx-runtime";var cg=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let s=ig.create(t),a=dg(()=>(e?.length??0)*r,[e,r]);return ug(s,{animate:{backgroundPosition:"0% center"},className:x("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",o),initial:{backgroundPosition:"100% center"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:n,ease:"linear"},children:e})},cd=lg(cg);import{Fragment as vg,jsx as Jt,jsxs as bs}from"react/jsx-runtime";function md({workflowId:e,onWorkflowCreated:t}){let[o,n]=Tn(Nt),[r,s]=vs(""),[a,d]=vs(!1),[i,l]=vs(!1),c=ud(null),u=ud(null),f=pg(ne),[h,k]=Tn(ue),[b,y]=Tn(ne),[p,v]=Tn(Ue),[g,C]=Tn(gt),[I,A]=Tn(ke),{fitView:w}=mg(),m=f.filter(W=>W.type!=="add"),S=m.length>0;yg(()=>{let W=$=>{($.metaKey||$.ctrlKey)&&$.key==="k"&&($.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",W),()=>{window.removeEventListener("keydown",W)}},[]);let X=()=>{d(!0),l(!0)},le=W=>{u.current?.contains(W.relatedTarget)||(l(!1),r.trim()||d(!1))},L=gg(async W=>{if(W.preventDefault(),!(!r.trim()||o)){n(!0);try{let $=S?{nodes:m,edges:h,name:g}:void 0;console.log("[AI Prompt] Generating workflow"),console.log("[AI Prompt] Has nodes:",S),console.log("[AI Prompt] Sending existing workflow:",!!$),$&&console.log("[AI Prompt] Existing workflow:",$.nodes.length,"nodes,",$.edges.length,"edges");let P=await q.ai.generateStream(r,F=>{let K=(F.edges||[]).map(N=>({...N,type:"animated"})),T=(F.nodes||[]).filter(N=>N.data?.type==="trigger"),z=K;if(T.length>1){let N=T[0],R=(F.nodes||[]).filter(oe=>oe.data?.type!=="trigger");F.nodes=[N,...R];let G=T.slice(1).map(oe=>oe.id);z=K.filter(oe=>!G.includes(oe.source)&&!G.includes(oe.target))}y(F.nodes||[]),k(z),F.name&&C(F.name),setTimeout(()=>{w({padding:.2,duration:200})},0)},$);console.log("[AI Prompt] Received final workflow data"),console.log("[AI Prompt] Nodes:",P.nodes?.length||0),console.log("[AI Prompt] Edges:",P.edges?.length||0);let V=(P.edges||[]).map(F=>({...F,type:"animated"}));console.log("[AI Prompt] Validating nodes:",P.nodes);let J=(P.nodes||[]).filter(F=>{let K=F.data?.type,T=F.data?.config||{};return console.log(`[AI Prompt] Checking node ${F.id}:`,{type:K,config:T,hasActionType:!!T.actionType,hasTriggerType:!!T.triggerType}),K==="trigger"?!T.triggerType:K==="action"?!T.actionType:!1});if(J.length>0)throw console.error("[AI Prompt] AI generated incomplete nodes:",J),console.error("[AI Prompt] Full workflow data:",JSON.stringify(P,null,2)),new Error(`Cannot create workflow: The AI tried to create ${J.length} incomplete node(s). The requested action type may not be supported. Please try a different description using supported actions: Send Email, Send Slack Message, Create Ticket, Database Query, HTTP Request, Generate Text, Generate Image, Scrape, or Search.`);if(e){v(e),console.log("[AI Prompt] Updating existing workflow:",e),console.log("[AI Prompt] Has existingWorkflow context:",!!$),$?(console.log("[AI Prompt] REPLACING workflow with AI response"),console.log("[AI Prompt] Replacing",m.length,"nodes with",P.nodes?.length||0,"nodes")):(console.log("[AI Prompt] Setting workflow for empty canvas"),hs.success("Generated workflow"));let F=P.nodes?.find(K=>K.selected);F&&A(F.id),await q.workflow.update(e,{name:P.name,description:P.description,nodes:P.nodes,edges:V})}else{let F=await q.workflow.create({name:P.name||"AI Generated Workflow",description:P.description||"",nodes:P.nodes||[],edges:V});v(F.id),hs.success("Created workflow"),t&&t(F.id)}s(""),d(!1),l(!1),c.current?.blur()}catch($){console.error("Failed to generate workflow:",$),hs.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,S,f,h,n,v,y,k,C,A,t,w]);return Jt(vg,{children:Jt("div",{ref:u,className:"pointer-events-auto absolute bottom-4 left-1/2 z-10 -translate-x-1/2 px-4",style:{width:a?"min(100%, 42rem)":"20rem",transition:"width 150ms ease-out"},children:bs("form",{"aria-busy":o,"aria-label":"AI workflow prompt",className:"relative flex items-center gap-2 rounded-lg border bg-background pl-3 pr-2 py-2 shadow-lg cursor-text",onClick:W=>{(W.target===W.currentTarget||W.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:W=>{W.target===W.currentTarget&&W.preventDefault()},onSubmit:L,role:"search",children:[o&&r?Jt(cd,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Jt("textarea",{"aria-label":"Describe your workflow",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground resize-none h-[22px] min-h-[22px] max-h-[200px] py-0 leading-[22px]",disabled:o,onBlur:le,onChange:W=>{s(W.target.value),W.target.style.height="auto",W.target.style.height=`${W.target.scrollHeight}px`},onFocus:X,onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey?(W.preventDefault(),L(W)):W.key==="Escape"&&(W.preventDefault(),s(""),d(!1),l(!1),c.current?.blur())},placeholder:i?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Jt("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),bs("div",{className:"relative size-8 shrink-0 self-end",children:[Jt(D,{"aria-label":"Focus prompt input (\u2318K)",className:"absolute inset-0 h-8 px-0 text-xs text-muted-foreground hover:bg-transparent transition-[opacity,filter] ease-out",onClick:()=>c.current?.focus(),style:!r.trim()&&!o&&!i?{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"}:{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"},type:"button",variant:"ghost",children:bs("kbd",{"aria-hidden":"true",className:"pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100",children:[Jt("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Jt(D,{"aria-label":o?"Generating workflow...":"Generate workflow",className:"size-8 transition-[opacity,filter] ease-out shrink-0",disabled:!r.trim()||o,size:"sm",style:!r.trim()&&!o&&!i?{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"}:{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"},type:"submit",children:Jt(fg,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as py}from"@xyflow/react";import{useAtom as et,useAtomValue as Zd,useSetAtom as Ut}from"jotai";import{Check as ga,ChevronDown as fy,Copy as gy,Download as yy,Globe as ec,Loader2 as va,Lock as tc,Play as vy,Plus as oc,Redo2 as nc,Save as hy,Settings2 as by,Trash2 as wy,Undo2 as rc}from"lucide-react";import{nanoid as xy}from"nanoid";import{useRouter as Ny}from"next/navigation";import{useEffect as Ms,useRef as ky,useState as Ls}from"react";import{toast as dt}from"sonner";import{Panel as hg}from"@xyflow/react";import{jsx as bg}from"react/jsx-runtime";var sa=({className:e,...t})=>bg(hg,{className:x("m-4 rounded-md border bg-card p-1",e),...t});var ws="https://vercel.new/workflow-builder",iA=`[](${ws})`;import{jsx as or,jsxs as pd}from"react/jsx-runtime";function fd(){return or(D,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:pd("a",{href:ws,rel:"noopener noreferrer",target:"_blank",children:[pd("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[or("title",{children:"Vercel logomark"}),or("path",{d:"m38 0 38 66H0z"})]}),or("span",{className:"text-sm sm:hidden",children:"Deploy"}),or("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as gd}from"react/jsx-runtime";function yd({className:e}){return gd("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:gd("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})})}function vd(e){if(e>=1e6){let t=(e/1e6).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e6)}M`:`${t}M`}if(e>=1e3){let t=(e/1e3).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e3)}k`:`${t}k`}return e.toString()}import{createContext as wg,useContext as xg}from"react";import{jsx as hA}from"react/jsx-runtime";var Ng=wg(null);function hd(){return xg(Ng)}import{jsx as bd,jsxs as wd}from"react/jsx-runtime";var kg="https://github.com/vercel-labs/workflow-builder-template";function xd(){let e=hd();return bd(D,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:wd("a",{className:"flex items-center",href:kg,rel:"noopener noreferrer",target:"_blank",children:[bd(yd,{className:"size-4.5"}),e!==null&&wd("span",{className:"hidden text-sm sm:inline",children:[vd(e)," stars"]})]})})}import{useAtom as Yt,useAtomValue as Nd,useSetAtom as nr}from"jotai";import{Code as kd,Copy as Cd,Eraser as xs,Eye as Cg,EyeOff as Tg,FileCode as Td,Play as Ad,RefreshCw as Sd,Settings2 as Id,Trash2 as Ns}from"lucide-react";import{useCallback as An,useEffect as Ag,useRef as Sg,useState as Ig}from"react";import{toast as Sn}from"sonner";import{Fragment as ks,jsx as Z,jsxs as ie}from"react/jsx-runtime";var Pg={"Database Query":"database"},Eg=/[^a-zA-Z0-9\s]/g,Dg=/\s+/;function Rg(e){return e.data.type==="trigger"?e.data.config?.triggerType==="Schedule"?"vercel.json":`app/api${e.data.config?.webhookPath||"/webhook"}/route.ts`:`steps/${(e.data.config?.actionType||"action").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-step.ts`}function ia({overlayId:e}){let{push:t,closeAll:o}=re(),[n]=Yt(ke),[r]=Yt(_e),[s]=Yt(ne),[a]=Yt(ue),[d]=Yt(Nt),[i]=Yt(Ue),[l,c]=Yt(gt),u=Nd(oo),f=nr(ro),h=nr(ao),k=nr(so),b=nr(Cr),y=nr(Nr),[p,v]=Yt(to),[g,C]=Yt(Bt),[I,A]=Ig(!1),w=Sg(null),m=s.find(B=>B.id===n),S=a.find(B=>B.id===r),X=Nd(ft);Ag(()=>{if(!(m&&u))return;let B=m.data.config?.actionType,Ae=m.data.config?.integrationId;if(!(B&&Ae))return;let Ye=fe(B)?.integration||Pg[B];if(!Ye)return;let $e=X.filter(Et=>Et.type===Ye);!$e.some(Et=>Et.id===Ae)&&$e.length>0&&f({id:m.id,data:{config:{...m.data.config,integrationId:$e[0].id}}})},[m,X,u,f]);let le=An((B,Ae)=>{m&&f({id:m.id,data:{config:{...m.data.config,[B]:Ae}}})},[m,f]),L=An(B=>{m&&f({id:m.id,data:{label:B}})},[m,f]),W=An(B=>{m&&f({id:m.id,data:{description:B}})},[m,f]),$=An(()=>{m&&f({id:m.id,data:{enabled:m.data.enabled===!1}})},[m,f]),P=An(()=>{t(Me,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{m&&(h(m.id),o())}})},[m,h,o,t]),V=An(()=>{m&&(navigator.clipboard.writeText(vn(m,i)),Sn.success("Code copied to clipboard"))},[m]),J=async()=>{w.current&&(A(!0),await w.current(),A(!1))},F=()=>{t(Me,{title:"Delete All Runs",message:"Are you sure you want to delete all workflow runs? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:async()=>{if(i)try{await q.workflow.deleteExecutions(i),b(),w.current&&await w.current(),Sn.success("All runs deleted")}catch(B){console.error("Failed to delete runs:",B),Sn.error("Failed to delete runs")}}})},K=m&&(m.data.type!=="trigger"||m.data.config?.triggerType!=="Manual")&&m.data.config?.actionType!=="Condition",T=()=>{if(!m)switch(g==="properties"||g==="code"||g==="runs"&&u?g:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(g){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},z=async B=>{if(c(B),i)try{await q.workflow.update(i,{name:B})}catch(Ae){console.error("Failed to update workflow name:",Ae)}},N=()=>{t(Me,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{y()}})},R=()=>{t(Me,{title:"Delete Workflow",message:`Are you sure you want to delete "${l}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(i)try{await q.workflow.delete(i),o(),Sn.success("Workflow deleted successfully"),window.location.href="/"}catch(B){console.error("Failed to delete workflow:",B),Sn.error("Failed to delete workflow. Please try again.")}}})},G=(()=>{let Ae=`${l.replace(Eg,"").split(Dg).map((Ye,$e)=>$e===0?Ye.toLowerCase():Ye.charAt(0).toUpperCase()+Ye.slice(1).toLowerCase()).join("")}Workflow`,{code:Je}=cr(s,a,{functionName:Ae});return Je})(),oe=()=>{navigator.clipboard.writeText(G),Sn.success("Code copied to clipboard")},de=()=>{r&&t(Me,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{k(r),o()}})};if(S&&!m)return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(un,{overlayId:e,title:"Connection"}),ie("div",{className:"flex-1 space-y-4 overflow-y-auto px-6 pt-4 pb-6",children:[ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-id",children:"Connection ID"}),Z(se,{disabled:!0,id:"edge-id",value:S.id})]}),ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-source",children:"Source"}),Z(se,{disabled:!0,id:"edge-source",value:S.source})]}),ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"edge-target",children:"Target"}),Z(se,{disabled:!0,id:"edge-target",value:S.target})]}),u&&Z("div",{className:"pt-2",children:ie(D,{onClick:de,variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!m){let B=g==="properties"||g==="code"||g==="runs"&&u?g:"properties";return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(un,{overlayId:e,title:T()}),ie("div",{className:"flex-1 overflow-y-auto",children:[B==="properties"&&ie("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"workflow-name",children:"Workflow Name"}),Z(se,{disabled:!u,id:"workflow-name",onChange:Ae=>z(Ae.target.value),value:l})]}),ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"workflow-id",children:"Workflow ID"}),Z(se,{disabled:!0,id:"workflow-id",value:i||"Not saved"})]}),!u&&Z("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:Z("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),u&&ie("div",{className:"flex items-center gap-2 pt-2",children:[ie(D,{onClick:N,variant:"ghost",children:[Z(xs,{className:"mr-2 size-4"}),"Clear"]}),ie(D,{onClick:R,variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete"]})]})]}),B==="code"&&ie("div",{className:"flex flex-col",children:[ie("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[ie("div",{className:"flex items-center gap-2",children:[Z(Td,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),ie(D,{className:"h-7 text-xs",onClick:oe,size:"sm",variant:"ghost",children:[Z(Cd,{className:"mr-1 size-3"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(yt,{defaultLanguage:"typescript",height:"100%",options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,wordWrap:"on"},value:G})})]}),B==="runs"&&u&&ie("div",{className:"flex h-full flex-col",children:[ie("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[Z(D,{className:"text-muted-foreground",disabled:I,onClick:J,size:"icon",variant:"ghost",children:Z(Sd,{className:`size-4 ${I?"animate-spin":""}`})}),Z(D,{className:"text-muted-foreground",onClick:F,size:"icon",variant:"ghost",children:Z(xs,{className:"size-4"})})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(bn,{isActive:B==="runs",onRefreshRef:w})})]})]}),ie("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("properties"),type:"button",children:[Z(Id,{className:"size-5"}),"Workflow"]}),ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("code"),type:"button",children:[Z(kd,{className:"size-5"}),"Code"]}),u&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${B==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("runs"),type:"button",children:[Z(Ad,{className:"size-5"}),"Runs"]})]})]})}return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(un,{overlayId:e,title:T()}),ie("div",{className:"flex-1 overflow-y-auto",children:[g==="properties"&&ie("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[m.data.type==="action"&&!m.data.config?.actionType&&u&&Z(Yr,{disabled:d,isNewlyCreated:m?.id===p,onSelectAction:B=>{le("actionType",B),m?.id===p&&v(null)}}),m.data.type==="trigger"&&Z(Xr,{config:m.data.config||{},disabled:d||!u,onUpdateConfig:le,workflowId:i??void 0}),m.data.type==="action"&&m.data.config?.actionType!==void 0&&Z($r,{config:m.data.config||{},disabled:d||!u,isOwner:u,onUpdateConfig:le}),(m.data.type!=="action"||m.data.config?.actionType!==void 0)&&ie(ks,{children:[ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"label",children:"Label"}),Z(se,{disabled:d||!u,id:"label",onChange:B=>L(B.target.value),value:m.data.label})]}),ie("div",{className:"space-y-2",children:[Z(M,{htmlFor:"description",children:"Description"}),Z(se,{disabled:d||!u,id:"description",onChange:B=>W(B.target.value),placeholder:"Optional description",value:m.data.description||""})]})]}),u&&ie("div",{className:"flex items-center gap-2 pt-2",children:[m.data.type==="action"&&Z(D,{className:"text-muted-foreground",onClick:$,size:"sm",variant:"ghost",children:m.data.enabled===!1?ie(ks,{children:[Z(Tg,{className:"mr-2 size-4"}),"Disabled"]}):ie(ks,{children:[Z(Cg,{className:"mr-2 size-4"}),"Enabled"]})}),ie(D,{className:"text-muted-foreground",onClick:P,size:"sm",variant:"ghost",children:[Z(Ns,{className:"mr-2 size-4"}),"Delete"]})]})]}),K&&ie("div",{className:`flex flex-col ${g==="code"?"":"invisible absolute -z-10"}`,children:[ie("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[ie("div",{className:"flex items-center gap-2",children:[Z(Td,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:Rg(m)})]}),ie(D,{className:"text-muted-foreground",onClick:V,size:"sm",variant:"ghost",children:[Z(Cd,{className:"mr-2 size-4"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(yt,{height:"100%",language:m.data.type==="trigger"&&m.data.config?.triggerType==="Schedule"?"json":"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:vn(m,i)})})]}),g==="runs"&&u&&ie("div",{className:"flex h-full flex-col",children:[ie("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[ie(D,{className:"text-muted-foreground",disabled:I,onClick:J,size:"sm",variant:"ghost",children:[Z(Sd,{className:`mr-2 size-4 ${I?"animate-spin":""}`}),"Refresh"]}),ie(D,{className:"text-muted-foreground",onClick:F,size:"sm",variant:"ghost",children:[Z(xs,{className:"mr-2 size-4"}),"Clear All"]})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(bn,{isActive:g==="runs",onRefreshRef:w})})]})]}),ie("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("properties"),type:"button",children:[Z(Id,{className:"size-5"}),"Properties"]}),K&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("code"),type:"button",children:[Z(kd,{className:"size-5"}),"Code"]}),u&&ie("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>C("runs"),type:"button",children:[Z(Ad,{className:"size-5"}),"Runs"]})]})]})}import{Download as Mg,FlaskConical as Fg}from"lucide-react";import{cva as Og}from"class-variance-authority";import{jsx as Cs}from"react/jsx-runtime";var Lg=Og("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Pd({className:e,variant:t,...o}){return Cs("div",{"data-slot":"alert",role:"alert",className:x(Lg({variant:t}),e),...o})}function Ed({className:e,...t}){return Cs("div",{"data-slot":"alert-title",className:x("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Dd({className:e,...t}){return Cs("div",{"data-slot":"alert-description",className:x("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}import{jsx as In,jsxs as la}from"react/jsx-runtime";function Rd({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=re();return la(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:o?"Exporting...":"Export Project",onClick:()=>{n(),t()},loading:o}],overlayId:e,title:"Export Workflow as Code",children:[la("div",{className:"flex items-center gap-2 text-muted-foreground",children:[In(Mg,{className:"size-5"}),In("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),In("p",{className:"mt-4 text-muted-foreground text-sm",children:"This will generate a complete Next.js project containing your workflow code. Once exported, you can run your workflow outside of the Workflow Builder, deploy it to Vercel, or integrate it into your existing applications."}),la(Pd,{className:"mt-4",children:[In(Fg,{className:"size-4"}),In(Ed,{children:"Experimental Feature"}),la(Dd,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",In("a",{className:"font-medium text-foreground underline underline-offset-4 hover:text-primary",href:"https://github.com/vercel-labs/workflow-builder-template/issues",rel:"noopener noreferrer",target:"_blank",children:"report them on GitHub"}),"."]})]})]})}import{Globe as Wg}from"lucide-react";import{jsx as ho,jsxs as da}from"react/jsx-runtime";function Od({overlayId:e,onConfirm:t}){let{closeAll:o}=re();return da(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[da("div",{className:"flex items-center gap-2 text-muted-foreground",children:[ho(Wg,{className:"size-5 shrink-0"}),ho("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),da("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[ho("li",{children:"View the workflow structure and steps"}),ho("li",{children:"See action types and configurations"}),ho("li",{children:"Duplicate the workflow to their own account"})]}),ho("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),da("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[ho("li",{children:"Your integration credentials (API keys, tokens)"}),ho("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as Ld,useSetAtom as zg}from"jotai";import{AlertTriangle as Bg}from"lucide-react";import{jsx as Ze,jsxs as pt}from"react/jsx-runtime";function Md({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:s}=re(),a=zg(Rt),d=Vt(),i=Ld(Kt),l=Ld(Ao),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:f}=t,h=c.length+u.length+f.length,k=(v,g)=>{o(v,g),d?r(ia,{}):s()},b=v=>{r(co,{type:v,onSuccess:()=>{a(g=>g+1)}})},y=v=>{i?.integrationType===v&&l?.enabled&&l?.isVercelUser&&i?r(i.ConsentOverlay,{onConsent:()=>{a(I=>I+1)},onManualEntry:()=>b(v)}):b(v)};return pt(Oe,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{s(),n()}},{label:"Cancel",onClick:s}],overlayId:e,title:`Workflow Issues (${h})`,children:[pt("div",{className:"flex items-center gap-2 text-orange-500",children:[Ze(Bg,{className:"size-5"}),Ze("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),pt("div",{className:"mt-4 space-y-4",children:[f.length>0&&pt("div",{className:"space-y-1",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),f.map(v=>pt("div",{className:"flex items-center gap-3 py-1",children:[Ze(Mt,{className:"size-4 shrink-0",integration:v.integrationType}),pt("p",{className:"min-w-0 flex-1 text-sm",children:[Ze("span",{className:"font-medium",children:v.integrationLabel}),pt("span",{className:"text-muted-foreground",children:[" \u2014 ",v.nodeNames.length>3?`${v.nodeNames.slice(0,3).join(", ")} +${v.nodeNames.length-3} more`:v.nodeNames.join(", ")]})]}),Ze(D,{className:"shrink-0",onClick:()=>y(v.integrationType),size:"sm",variant:"outline",children:"Add"})]},v.integrationType))]}),c.length>0&&pt("div",{className:"space-y-2",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(v=>pt("div",{children:[Ze("p",{className:"font-medium text-sm",children:v.nodeLabel}),Ze("div",{className:"mt-1 space-y-0.5",children:v.brokenReferences.map((g,C)=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[pt("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[Ze("span",{className:"font-mono",children:g.displayText})," in ",g.fieldLabel]}),Ze(D,{className:"shrink-0",onClick:()=>k(v.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${v.nodeId}-${g.fieldKey}-${C}`))})]},v.nodeId))]}),u.length>0&&pt("div",{className:"space-y-2",children:[Ze("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Required Fields"}),u.map(v=>pt("div",{children:[Ze("p",{className:"font-medium text-sm",children:v.nodeLabel}),Ze("div",{className:"mt-1 space-y-0.5",children:v.missingFields.map(g=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[Ze("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:g.fieldLabel}),Ze(D,{className:"shrink-0",onClick:()=>k(v.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${v.nodeId}-${g.fieldKey}`))})]},v.nodeId))]})]})]})}import{jsx as Ts,jsxs as Vg}from"react/jsx-runtime";function Fd({className:e}){return Vg("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[Ts("path",{className:"fill-foreground",d:"M125.776 0C120.929 1.64945e-05 117 3.9291 117 8.77539V61.4248C117 66.2711 120.929 70.2002 125.776 70.2002H160.875L161.253 70.2051C169.032 70.4023 175.301 76.6734 175.495 84.4531L175.5 84.8252V143.325C175.5 148.171 179.429 152.101 184.276 152.101H219.375L219.753 152.105C227.53 152.303 233.798 158.571 233.995 166.348L234 166.726V225.225C234 230.071 237.929 234 242.776 234H295.425C300.271 234 304.2 230.071 304.2 225.225V172.575C304.2 167.729 300.271 163.8 295.425 163.8H260.25C252.334 163.76 245.905 157.43 245.705 149.553L245.7 149.176V90.6758C245.7 85.8295 241.771 81.9004 236.925 81.9004H201.825C193.874 81.9004 187.405 75.5551 187.205 67.6523L187.2 67.2754V8.77539C187.2 3.9291 183.271 1.64951e-05 178.425 0H125.776Z"}),Ts("path",{className:"fill-foreground",d:"M67.2755 81.9004C62.4293 81.9004 58.5002 85.8295 58.5002 90.6758V143.325C58.5004 148.171 62.4294 152.101 67.2755 152.101H102.375L102.753 152.105C110.53 152.303 116.798 158.571 116.995 166.348L117 166.726V225.225C117 230.071 120.929 234 125.776 234H178.425C183.271 234 187.2 230.071 187.2 225.225V172.575C187.2 167.729 183.271 163.8 178.425 163.8H143.25C135.334 163.76 128.905 157.43 128.705 149.553L128.7 149.176V90.6758C128.7 85.8295 124.771 81.9004 119.925 81.9004H67.2755Z"}),Ts("path",{className:"fill-foreground",d:"M8.77454 163.8C3.92844 163.8 0.00012207 167.729 0.00012207 172.575V225.225C0.00012207 230.071 3.92844 234 8.77454 234H61.4249C66.2712 234 70.2003 230.071 70.2003 225.225V172.575C70.2003 167.729 66.2712 163.8 61.4249 163.8H8.77454Z"})]})}import{Key as ay,LogOut as sy,Moon as iy,Plug as ly,Settings as dy,Sun as cy}from"lucide-react";import{useTheme as uy}from"next-themes";import my from"next/link";import{useEffect as Yd,useState as Xd}from"react";import{Copy as Gg,Key as Hg,Trash2 as $g}from"lucide-react";import{useCallback as _g,useEffect as Ug,useState as Pn}from"react";import{toast as En}from"sonner";import{jsx as Ve,jsxs as Pt}from"react/jsx-runtime";function Kg({overlayId:e,onCreated:t}){let{pop:o}=re(),[n,r]=Pn(""),[s,a]=Pn(!1);return Pt(Oe,{actions:[{label:"Create",onClick:async()=>{a(!0);try{let i=await fetch("/api/api-keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n||null})});if(!i.ok){let c=await i.json();throw new Error(c.error||"Failed to create API key")}let l=await i.json();t(l),En.success("API key created successfully"),o()}catch(i){console.error("Failed to create API key:",i),En.error(i instanceof Error?i.message:"Failed to create API key")}finally{a(!1)}},loading:s}],overlayId:e,title:"Create API Key",children:[Ve("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),Pt("div",{className:"space-y-2",children:[Ve(M,{htmlFor:"key-name",children:"Label (optional)"}),Ve(se,{id:"key-name",onChange:i=>r(i.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function Wd({overlayId:e}){let{push:t,closeAll:o}=re(),[n,r]=Pn(!0),[s,a]=Pn([]),[d,i]=Pn(null),[l,c]=Pn(null),u=_g(async()=>{r(!0);try{let p=await fetch("/api/api-keys");if(!p.ok)throw new Error("Failed to load API keys");let v=await p.json();a(v)}catch(p){console.error("Failed to load API keys:",p),En.error("Failed to load API keys")}finally{r(!1)}},[]);Ug(()=>{u()},[u]);let f=p=>{i(p.key??null),a(v=>[p,...v])},h=async p=>{c(p);try{if(!(await fetch(`/api/api-keys/${p}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(g=>g.filter(C=>C.id!==p)),En.success("API key deleted")}catch(v){console.error("Failed to delete API key:",v),En.error("Failed to delete API key")}finally{c(null)}},k=p=>{t(Me,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any webhooks using this key will stop working immediately.",confirmLabel:"Delete",confirmVariant:"destructive",destructive:!0,onConfirm:()=>h(p)})},b=p=>{navigator.clipboard.writeText(p),En.success("Copied to clipboard")},y=p=>new Date(p).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return Pt(Oe,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(Kg,{onCreated:f})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Ve("div",{className:"flex items-center justify-center py-8",children:Ve(Tt,{})}):Pt("div",{className:"space-y-4",children:[d&&Pt("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Ve("p",{className:"mb-2 font-medium text-sm text-yellow-600 dark:text-yellow-400",children:"Copy your API key now. You won't be able to see it again!"}),Pt("div",{className:"flex items-center gap-2",children:[Ve("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:d}),Ve(D,{onClick:()=>b(d),size:"sm",variant:"outline",children:Ve(Gg,{className:"size-4"})})]}),Ve(D,{className:"mt-2",onClick:()=>i(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),s.length===0?Pt("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Ve(Hg,{className:"mx-auto mb-2 size-8 opacity-50"}),Ve("p",{children:"No API keys yet"}),Ve("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Ve("div",{className:"space-y-2",children:s.map(p=>Pt("div",{className:"flex items-center justify-between rounded-md border p-3",children:[Pt("div",{className:"min-w-0 flex-1",children:[Pt("div",{className:"flex items-center gap-2",children:[Pt("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[p.keyPrefix,"..."]}),p.name&&Ve("span",{className:"truncate text-sm",children:p.name})]}),Pt("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",y(p.createdAt),p.lastUsedAt&&` \xB7 Last used ${y(p.lastUsedAt)}`]})]}),Ve(D,{disabled:l===p.id,onClick:()=>k(p.id),size:"sm",variant:"ghost",children:l===p.id?Ve(Tt,{className:"size-4"}):Ve($g,{className:"size-4 text-destructive"})})]},p.id))})]})]})}import{useSetAtom as Zg}from"jotai";import{Search as ey}from"lucide-react";import{useCallback as Is,useEffect as ty,useRef as oy,useState as Bd}from"react";import{Pencil as qg,Trash2 as jg}from"lucide-react";import{useCallback as Jg,useEffect as Yg,useMemo as Xg,useState as As}from"react";import{toast as ca}from"sonner";import{jsx as He,jsxs as Ss}from"react/jsx-runtime";var Qg={database:"Database"};function zd({onIntegrationChange:e,filter:t=""}){let{push:o}=re(),[n,r]=As([]),[s,a]=As(!0),[d,i]=As(null),l=Jg(async()=>{try{a(!0);let b=await q.integration.getAll();r(b)}catch(b){console.error("Failed to load integrations:",b),ca.error("Failed to load integrations")}finally{a(!1)}},[]);Yg(()=>{l()},[l]);let c=Xg(()=>{let b=eo(),y=t.toLowerCase();return n.map(p=>({...p,label:b[p.type]||Qg[p.type]||p.type})).filter(p=>t?p.label.toLowerCase().includes(y)||p.name.toLowerCase().includes(y)||p.type.toLowerCase().includes(y):!0).sort((p,v)=>{let g=p.label.localeCompare(v.label);return g!==0?g:p.name.localeCompare(v.name)})},[n,t]),u=b=>{o(Vr,{integration:b,onSuccess:()=>{l(),e?.()},onDelete:()=>{l(),e?.()}})},f=b=>{o(_a,{integration:b,onSuccess:()=>{l(),e?.()}})},h=async b=>{try{i(b);let y=await q.integration.testConnection(b);y.status==="success"?ca.success(y.message||"Connection successful"):ca.error(y.message||"Connection test failed")}catch(y){console.error("Connection test failed:",y),ca.error(y instanceof Error?y.message:"Connection test failed")}finally{i(null)}};return s?He("div",{className:"flex items-center justify-center py-8",children:He(Tt,{})}):He("div",{className:"space-y-1",children:n.length===0?He("div",{className:"py-8 text-center",children:He("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?He("div",{className:"py-8 text-center",children:He("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):He("div",{className:"space-y-1",children:c.map(b=>Ss("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[Ss("div",{className:"flex items-center gap-2",children:[He(Mt,{className:"size-4",integration:b.type==="ai-gateway"?"vercel":b.type}),He("span",{className:"font-medium text-sm",children:b.label}),He("span",{className:"text-muted-foreground text-sm",children:b.name})]}),Ss("div",{className:"flex items-center gap-1",children:[He(D,{className:"h-7 px-2",disabled:d===b.id,onClick:()=>h(b.id),size:"sm",variant:"outline",children:d===b.id?He(Tt,{className:"size-3"}):He("span",{className:"text-xs",children:"Test"})}),He(D,{className:"size-7",onClick:()=>u(b),size:"icon",variant:"outline",children:He(qg,{className:"size-3"})}),He(D,{className:"size-7",onClick:()=>f(b),size:"icon",variant:"outline",children:He(jg,{className:"size-3"})})]})]},b.id))})})}import{jsx as Wo,jsxs as Ps}from"react/jsx-runtime";function Vd({overlayId:e}){let{push:t,closeAll:o}=re(),[n,r]=Bd(!0),[s,a]=Bd(""),d=Zg(Rt),i=oy(!1),l=Is(async()=>{r(!0);try{await new Promise(h=>setTimeout(h,0))}finally{r(!1)}},[]);ty(()=>{l(),i.current=!1,a("")},[l]);let c=Is(()=>{i.current&&d(h=>h+1),o()},[o,d]),u=Is(()=>{i.current=!0},[]);return Ps(Oe,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(Xi,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[Wo("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?Wo("div",{className:"flex items-center justify-center py-8",children:Wo(Tt,{})}):Ps("div",{className:"space-y-4",children:[Ps("div",{className:"relative",children:[Wo(ey,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Wo(se,{className:"pl-9",onChange:h=>a(h.target.value),placeholder:"Filter connections...",value:s})]}),Wo("div",{className:"max-h-[300px] overflow-y-auto",children:Wo(zd,{filter:s,onIntegrationChange:u})})]})]})}import{useCallback as _d,useEffect as ny,useState as pa}from"react";import{toast as Ud}from"sonner";import{jsx as ma}from"react/jsx-runtime";function ua({className:e,...t}){return ma("div",{"data-slot":"card",className:x("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Gd({className:e,...t}){return ma("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function Hd({className:e,...t}){return ma("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function Es({className:e,...t}){return ma("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import{jsx as rr,jsxs as Ds}from"react/jsx-runtime";function $d({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return rr(ua,{className:"border-0 py-0 shadow-none",children:Ds(Es,{className:"space-y-4 p-0",children:[Ds("div",{className:"space-y-2",children:[rr(M,{className:"ml-1",htmlFor:"accountName",children:"Name"}),rr(se,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),Ds("div",{className:"space-y-2",children:[rr(M,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),rr(se,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as fa,jsxs as ry}from"react/jsx-runtime";function Kd({overlayId:e}){let{closeAll:t}=re(),[o,n]=pa(!0),[r,s]=pa(!1),[a,d]=pa(""),[i,l]=pa(""),c=_d(async()=>{try{let h=await q.user.get();d(h.name||""),l(h.email||"")}catch(h){console.error("Failed to load account:",h)}},[]),u=_d(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return ny(()=>{u()},[u]),ry(Oe,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{s(!0),await q.user.update({name:a,email:i}),await c(),Ud.success("Settings saved"),t()}catch(h){console.error("Failed to save account:",h),Ud.error("Failed to save settings")}finally{s(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[fa("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?fa("div",{className:"flex items-center justify-center py-8",children:fa(Tt,{})}):fa($d,{accountEmail:i,accountName:a,onEmailChange:l,onNameChange:d})]})}import{Avatar as Rs}from"radix-ui";import{jsx as Os}from"react/jsx-runtime";function qd({className:e,...t}){return Os(Rs.Root,{"data-slot":"avatar",className:x("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function jd({className:e,...t}){return Os(Rs.Image,{"data-slot":"avatar-image",className:x("aspect-square size-full",e),...t})}function Jd({className:e,...t}){return Os(Rs.Fallback,{"data-slot":"avatar-fallback",className:x("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as Ne,jsxs as Ft}from"react/jsx-runtime";var Qd=()=>{let{data:e,isPending:t}=wn(),{theme:o,setTheme:n}=uy(),{open:r}=re(),[s,a]=Xd(null),[d,i]=Xd(!1);Yd(()=>{i(!0)},[]),Yd(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&q.user.get().then(h=>a(h.providerId)).catch(()=>a(null))},[e?.user]);let l=async()=>{await $l()},c=s==="vercel"||s==="github"||s==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!d?Ne("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?Ne("div",{className:"flex items-center gap-2",children:Ne(D,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:Ne(my,{href:"/auth/sign-in",children:"Sign In"})})}):Ft(Eo,{children:[Ne(Do,{asChild:!0,children:Ne(D,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ft(qd,{className:"h-9 w-9",children:[Ne(jd,{alt:e?.user?.name||"",src:e?.user?.image||""}),Ne(Jd,{children:u()})]})})}),Ft(Ro,{align:"end",className:"w-56",children:[Ne(vl,{children:Ft("div",{className:"flex flex-col space-y-1",children:[Ne("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),Ne("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),Ne(qn,{}),!c&&Ft(wt,{onClick:()=>r(Kd),children:[Ne(dy,{className:"size-4"}),Ne("span",{children:"Settings"})]}),Ft(wt,{onClick:()=>r(Vd),children:[Ne(ly,{className:"size-4"}),Ne("span",{children:"Connections"})]}),Ft(wt,{onClick:()=>r(Wd),children:[Ne(ay,{className:"size-4"}),Ne("span",{children:"API Keys"})]}),Ft(hl,{children:[Ft(bl,{children:[Ne(cy,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),Ne(iy,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),Ne("span",{children:"Theme"})]}),Ne(wl,{children:Ft(yl,{onValueChange:n,value:o,children:[Ne(Jr,{value:"light",children:"Light"}),Ne(Jr,{value:"dark",children:"Dark"}),Ne(Jr,{value:"system",children:"System"})]})})]}),Ne(qn,{}),Ft(wt,{onClick:l,children:[Ne(sy,{className:"size-4"}),Ne("span",{children:"Logout"})]})]})]})};import{Fragment as ya,jsx as j,jsxs as Pe}from"react/jsx-runtime";function ac(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var Cy={"Database Query":"database"},Ty={database:"Database"};function Ay(e){if(typeof e!="string")return[];let t=/\{\{@([^:]+):([^}]+)\}\}/g,o=e.matchAll(t);return Array.from(o).map(n=>({nodeId:n[1],displayText:n[2]}))}function lc(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Ay(r);for(let d of a)o.push({field:s,...d})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...lc(r,s))}return o}function Sy(e){let t=new Set(e.map(n=>n.id)),o=[];for(let n of e){if(n.data.enabled===!1)continue;let r=n.data.config;if(!r||typeof r!="object")continue;let a=lc(r).filter(d=>!t.has(d.nodeId));if(a.length>0){let d=r.actionType,i=d?fe(d):void 0,l=i?Ca(i.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||i?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=l.find(f=>f.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function Iy(e){return e==null||typeof e=="string"&&e.trim()===""}function Py(e,t){return e.showWhen?t[e.showWhen.field]===e.showWhen.equals:!0}function Ey(e){if(e.data.enabled===!1)return null;let t=e.data.config,o=t?.actionType;if(!o)return null;let n=fe(o);if(!n)return null;let s=Ca(n.configFields).filter(a=>a.required&&Py(a,t||{})&&Iy(t?.[a.key])).map(a=>({fieldKey:a.key,fieldLabel:a.label}));return s.length===0?null:{nodeId:e.id,nodeLabel:e.data.label||n.label||"Unnamed Step",missingFields:s}}function Dy(e){return e.map(Ey).filter(t=>t!==null)}function Ry(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,s=eo();for(let a of e){if(a.data.enabled===!1)continue;let d=a.data.config?.actionType;if(!d)continue;let l=fe(d)?.integration||Cy[d];if(!l||!_o(l))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(l)){let f=r.get(l)||[],h=fe(d);f.push(a.data.label||h?.label||d),r.set(l,f)}}return Array.from(r.entries()).map(([a,d])=>({integrationType:a,integrationLabel:s[a]||Ty[a]||a,nodeNames:d}))}async function Oy({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:s}){ac(t,o,"idle");for(let a of t)a.data.type==="trigger"&&o({id:a.id,data:{status:"running"}});try{let a=await fetch(`/api/workflow/${e}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:{}})});if(!a.ok)throw new Error("Failed to execute workflow");let d=await a.json();s(d.executionId);let i=setInterval(async()=>{try{let l=await q.workflow.getExecutionStatus(d.executionId);for(let c of l.nodeStatuses)o({id:c.nodeId,data:{status:c.status}});l.status!=="running"&&(n.current&&(clearInterval(n.current),n.current=null),r(!1))}catch(l){console.error("Failed to poll execution status:",l)}},500);n.current=i}catch(a){console.error("Failed to execute workflow:",a),dt.error(a instanceof Error?a.message:"Failed to execute workflow"),ac(t,o,"error"),r(!1)}}function Ly({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:s,setIsSaving:a,setHasUnsavedChanges:d,setActiveTab:i,setNodes:l,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:f,userIntegrations:h}){let{open:k}=re(),b=ky(null);Ms(()=>()=>{b.current&&clearInterval(b.current)},[]);let y=async()=>{if(e){a(!0);try{await q.workflow.update(e,{nodes:t,edges:o}),d(!1)}catch(C){console.error("Failed to save workflow:",C),dt.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},p=async()=>{if(!e){dt.error("Please save the workflow before executing");return}i("runs"),l(t.map(C=>({...C,selected:!1}))),c(o.map(C=>({...C,selected:!1}))),u(null),s(!0),await Oy({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:b,setIsExecuting:s,setSelectedExecutionId:f})},v=(C,I)=>{u(C),i("properties"),I&&setTimeout(()=>{let A=document.getElementById(I);A&&(A.focus(),A.scrollIntoView({behavior:"smooth",block:"center"}))},100)};return{handleSave:y,handleExecute:async()=>{if(r)return;let C=Sy(t),I=Dy(t),A=Ry(t,h);if(C.length>0||I.length>0||A.length>0){k(Md,{issues:{brokenReferences:C,missingRequiredFields:I,missingIntegrations:A},onGoToStep:v,onRunAnyway:p});return}await p()}}}function My(){let[e,t]=et(ne),[o,n]=et(ue),[r,s]=et(ni),[a]=et(Nt),d=Ut(Nr),i=Ut(ro),[l]=et(Ue),[c,u]=et(gt),[f,h]=et(fr),k=Zd(oo),b=Ny(),[y,p]=et(kr),[v,g]=et(nt),C=Ut(mi),I=Ut(pi),A=Ut(Yo),[w]=et(fi),[m]=et(gi),{data:S}=wn(),X=Ut(Bt),le=Ut(ke),L=Ut(no),W=Zd(ft),[$,P]=et(xr),[V,J]=Ls(!1),[F,K]=Ls(!1),[T,z]=Ls([]);return Ms(()=>{(async()=>{try{let R=await q.workflow.getAll();z(R)}catch(R){console.error("Failed to load workflows:",R)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:s,isGenerating:a,clearWorkflow:d,updateNodeData:i,currentWorkflowId:l,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:f,setWorkflowVisibility:h,isOwner:k,router:b,isSaving:y,setIsSaving:p,hasUnsavedChanges:v,setHasUnsavedChanges:g,undo:C,redo:I,addNode:A,canUndo:w,canRedo:m,session:S,isDownloading:V,setIsDownloading:J,isDuplicating:F,setIsDuplicating:K,allWorkflows:T,setAllWorkflows:z,setActiveTab:X,setNodes:t,setEdges:n,setSelectedNodeId:le,setSelectedExecutionId:L,userIntegrations:W,triggerExecute:$,setTriggerExecute:P}}function Fy(e){let{open:t}=re(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:f,setAllWorkflows:h,setIsDownloading:k,setIsDuplicating:b,setActiveTab:y,setNodes:p,setEdges:v,setSelectedNodeId:g,setSelectedExecutionId:C,userIntegrations:I,triggerExecute:A,setTriggerExecute:w,router:m,session:S}=e,{handleSave:X,handleExecute:le}=Ly({currentWorkflowId:o,nodes:r,edges:s,updateNodeData:a,isExecuting:d,setIsExecuting:i,setIsSaving:l,setHasUnsavedChanges:c,setActiveTab:y,setNodes:p,setEdges:v,setSelectedNodeId:g,setSelectedExecutionId:C,userIntegrations:I});return Ms(()=>{A&&(w(!1),le())},[A,w,le]),{handleSave:X,handleExecute:le,handleClearWorkflow:()=>{t(Me,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{u()}})},handleDeleteWorkflow:()=>{t(Me,{title:"Delete Workflow",message:`Are you sure you want to delete "${n}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(o)try{await q.workflow.delete(o),dt.success("Workflow deleted successfully"),window.location.href="/"}catch(F){console.error("Failed to delete workflow:",F),dt.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){dt.error("Please save the workflow before downloading");return}k(!0),dt.info("Preparing workflow files for download...");try{let F=await q.workflow.download(o);if(!F.success)throw new Error(F.error||"Failed to prepare download");if(!F.files)throw new Error("No files to download");let K=(await import("jszip")).default,T=new K;for(let[G,oe]of Object.entries(F.files))T.file(G,oe);let z=await T.generateAsync({type:"blob"}),N=URL.createObjectURL(z),R=document.createElement("a");R.href=N,R.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(N),dt.success("Workflow downloaded successfully!")}catch(F){dt.error(F instanceof Error?F.message:"Failed to download workflow")}finally{k(!1)}},loadWorkflows:async()=>{try{let F=await q.workflow.getAll();h(F)}catch(F){console.error("Failed to load workflows:",F)}},handleToggleVisibility:async F=>{if(o){if(F==="public"){t(Od,{onConfirm:async()=>{try{await q.workflow.update(o,{visibility:"public"}),f("public"),dt.success("Workflow is now public")}catch(K){console.error("Failed to update visibility:",K),dt.error("Failed to update visibility. Please try again.")}}});return}try{await q.workflow.update(o,{visibility:F}),f(F),dt.success("Workflow is now private")}catch(K){console.error("Failed to update visibility:",K),dt.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){b(!0);try{S?.user||(await Mo.signIn.anonymous(),await new Promise(K=>setTimeout(K,100)));let F=await q.workflow.duplicate(o);dt.success("Workflow duplicated successfully"),m.push(`/workflows/${F.id}`)}catch(F){console.error("Failed to duplicate workflow:",F),dt.error("Failed to duplicate workflow. Please try again.")}finally{b(!1)}}}}}function Wy({workflowId:e,state:t,actions:o}){let{open:n,push:r}=re(),[s]=et(ke),[a]=et(_e),[d]=et(ne),[i]=et(ue),l=Ut(ao),c=Ut(so),{screenToFlowPosition:u}=py(),f=d.find(p=>p.id===s),h=i.find(p=>p.id===a),k=f||h;if(e&&!t.isOwner||!e)return null;let b=()=>{let v=!!s?"Node":"Connection";r(Me,{title:`Delete ${v}`,message:`Are you sure you want to delete this ${v.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{s?l(s):a&&c(a)}})},y=()=>{let p=document.querySelector(".react-flow");if(!p)return;let v=p.getBoundingClientRect(),g=v.left+v.width/2,C=v.top+v.height/2,I=u({x:g,y:C}),A=192,w=192;I.x-=A/2,I.y-=w/2;let m=20,S=20,X={...I},le=!0,L=0,W=20;for(;le&&L<W;)le=t.nodes.some(P=>{let V=Math.abs(P.position.x-X.x),J=Math.abs(P.position.y-X.y);return V<S&&J<S}),le&&(X.x+=m,X.y+=m,L+=1);let $={id:xy(),type:"action",position:X,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode($),t.setSelectedNodeId($.id),t.setActiveTab("properties")};return Pe(ya,{children:[j(_t,{className:"flex lg:hidden",orientation:"vertical",children:j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:j(oc,{className:"size-4"})})}),Pe(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(ia,{}),size:"icon",title:"Configuration",variant:"secondary",children:j(by,{className:"size-4"})}),k&&j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:b,size:"icon",title:"Delete",variant:"secondary",children:j(wy,{className:"size-4"})})]}),j(_t,{className:"hidden lg:flex",orientation:"horizontal",children:j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:j(oc,{className:"size-4"})})}),Pe(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:j(rc,{className:"size-4"})}),j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:j(nc,{className:"size-4"})})]}),Pe(_t,{className:"hidden lg:flex",orientation:"horizontal",children:[j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:j(rc,{className:"size-4"})}),j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:j(nc,{className:"size-4"})})]}),Pe(_t,{className:"flex lg:hidden",orientation:"vertical",children:[j(sc,{handleSave:o.handleSave,state:t}),j(ic,{actions:o,state:t})]}),Pe(_t,{className:"hidden lg:flex",orientation:"horizontal",children:[j(sc,{handleSave:o.handleSave,state:t}),j(ic,{actions:o,state:t})]}),j(zy,{actions:o,state:t}),j(By,{actions:o,state:t})]})}function sc({state:e,handleSave:t}){return Pe(D,{className:"relative border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!e.currentWorkflowId||e.isGenerating||e.isSaving,onClick:t,size:"icon",title:e.isSaving?"Saving...":"Save workflow",variant:"secondary",children:[e.isSaving?j(va,{className:"size-4 animate-spin"}):j(hy,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&j("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function ic({state:e,actions:t}){let{open:o}=re(),n=()=>{o(Rd,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isDownloading||e.nodes.length===0||e.isGenerating||!e.currentWorkflowId,onClick:n,size:"icon",title:e.isDownloading?"Preparing download...":"Export workflow as code",variant:"secondary",children:e.isDownloading?j(va,{className:"size-4 animate-spin"}):j(yy,{className:"size-4"})})}function zy({state:e,actions:t}){let o=e.workflowVisibility==="public";return Pe(Eo,{children:[j(Do,{asChild:!0,children:j(D,{className:"border hover:bg-black/5 dark:hover:bg-white/5",disabled:!e.currentWorkflowId||e.isGenerating,size:"icon",title:o?"Public workflow":"Private workflow",variant:"secondary",children:o?j(ec,{className:"size-4"}):j(tc,{className:"size-4"})})}),Pe(Ro,{align:"end",children:[Pe(wt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[j(tc,{className:"size-4"}),"Private",!o&&j(ga,{className:"ml-auto size-4"})]}),Pe(wt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[j(ec,{className:"size-4"}),"Public",o&&j(ga,{className:"ml-auto size-4"})]})]})]})}function By({state:e,actions:t}){return j(D,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isExecuting||e.nodes.length===0||e.isGenerating,onClick:()=>t.handleExecute(),size:"icon",title:"Run Workflow",variant:"secondary",children:e.isExecuting?j(va,{className:"size-4 animate-spin"}):j(vy,{className:"size-4"})})}function Vy({isDuplicating:e,onDuplicate:t}){return Pe(D,{className:"h-9 border hover:bg-black/5 dark:hover:bg-white/5",disabled:e,onClick:t,size:"sm",title:"Duplicate to your workflows",variant:"secondary",children:[e?j(va,{className:"mr-2 size-4 animate-spin"}):j(gy,{className:"mr-2 size-4"}),"Duplicate"]})}function Gy({workflowId:e,state:t,actions:o}){return Pe("div",{className:"flex flex-col gap-1",children:[j("div",{className:"flex h-9 max-w-[160px] items-center overflow-hidden rounded-md border bg-secondary text-secondary-foreground sm:max-w-none",children:Pe(Eo,{onOpenChange:n=>n&&o.loadWorkflows(),children:[Pe(Do,{className:"flex h-full cursor-pointer items-center gap-2 px-3 font-medium text-sm transition-all hover:bg-black/5 dark:hover:bg-white/5",children:[j(Fd,{className:"size-4 shrink-0"}),j("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:Pe(ya,{children:[j("span",{className:"sm:hidden",children:"New"}),j("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),j(fy,{className:"size-3 shrink-0 opacity-50"})]}),Pe(Ro,{align:"start",className:"w-64",children:[j(wt,{asChild:!0,className:"flex items-center justify-between",children:Pe("a",{href:"/",children:["New Workflow"," ",!e&&j(ga,{className:"size-4 shrink-0"})]})}),j(qn,{}),t.allWorkflows.length===0?j(wt,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>Pe(wt,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[j("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&j(ga,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&j("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var dc=({workflowId:e})=>{let t=My(),o=Fy(t);return Pe(ya,{children:[j(sa,{className:"flex flex-col gap-2 rounded-none border-none bg-transparent p-0 lg:flex-row lg:items-center",position:"top-left",children:Pe("div",{className:"flex items-center gap-2",children:[j(Gy,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&j("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),j("div",{className:"pointer-events-auto absolute top-4 right-4 z-10",children:Pe("div",{className:"flex flex-col-reverse items-end gap-2 lg:flex-row lg:items-center",children:[j(Wy,{actions:o,state:t,workflowId:e}),Pe("div",{className:"flex items-center gap-2",children:[!e&&Pe(ya,{children:[j(xd,{}),j(fd,{})]}),e&&!t.isOwner&&j(Vy,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),j(Qd,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as Gv,Zap as Hv}from"lucide-react";import{nanoid as $s}from"nanoid";import{BaseEdge as mc,getBezierPath as Hy,getSimpleBezierPath as $y,getSmoothStepPath as _y,Position as zo,useInternalNode as cc}from"@xyflow/react";import{useAtomValue as Uy}from"jotai";import{jsx as pc}from"react/jsx-runtime";var Ky=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:s,targetPosition:a,selected:d})=>{let[i]=$y({sourceX:t,sourceY:o,sourcePosition:s,targetX:n,targetY:r,targetPosition:a});return pc(mc,{className:"stroke-1",id:e,path:i,style:{stroke:d?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},uc=(e,t)=>{let o=t===zo.Left?"target":"source",n=e.internals.handleBounds?.[o]?.find(i=>i.position===t);if(!n)return[0,0];let r=n.width/2,s=n.height/2;switch(t){case zo.Left:r=0;break;case zo.Right:r=n.width;break;case zo.Top:s=0;break;case zo.Bottom:s=n.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let a=e.internals.positionAbsolute.x+n.x+r,d=e.internals.positionAbsolute.y+n.y+s;return[a,d]},qy=(e,t)=>{let o=zo.Right,[n,r]=uc(e,o),s=zo.Left,[a,d]=uc(t,s);return{sx:n,sy:r,tx:a,ty:d,sourcePos:o,targetPos:s}},jy=({id:e,source:t,target:o,style:n,selected:r})=>{let s=Uy(jo),a=cc(t),d=cc(o);if(!(a&&d))return null;let{sx:i,sy:l,tx:c,ty:u,sourcePos:f,targetPos:h}=qy(a,d),k={sourceX:i,sourceY:l,sourcePosition:f,targetX:c,targetY:u,targetPosition:h},[b]=s.edgeStyle==="bezier"?Hy(k):_y(k);return pc(mc,{id:e,path:b,style:{...n,stroke:r?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},Fs={Temporary:Ky,Animated:jy};import{useAtomValue as sr}from"jotai";import{AlertTriangle as lv,Check as dv,Code as cv,EyeOff as bc,XCircle as uv,Zap as Nc}from"lucide-react";import wc from"next/image";import{memo as mv,useState as pv}from"react";import{useAtomValue as Xy}from"jotai";import{Check as vc,Circle as Qy,EyeOff as Zy,ListOrdered as ev,Loader2 as tv,XCircle as hc}from"lucide-react";import{memo as ov,useEffect as nv,useState as rv}from"react";import{Handle as gc,Position as yc}from"@xyflow/react";import{Fragment as Jy,jsx as bo,jsxs as Ws}from"react/jsx-runtime";var fc=({className:e})=>Ws(Jy,{children:[bo("style",{children:`
|
|
201
|
+
}`:""}function Hp(e){if(!e)return ns;if(Ll[e])return Ll[e];let t=ge(e);return t&&t.codegenTemplate||ns}var Nn=(e,t)=>e.data.type==="trigger"?Vp(e.data.config,t):e.data.type==="action"?Hp(e.data.config?.actionType):Bp;import{useAtom as rs}from"jotai";import{Check as zl,ChevronDown as ss,ChevronRight as is,Clock as _p,Copy as Up,ExternalLink as Kp,Loader2 as qp,Play as jp,Square as Wl,X as Jp}from"lucide-react";import Fl from"next/image";import{useCallback as tr,useEffect as ea,useRef as Yp,useState as Mo}from"react";function kn(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function Ml(e){let t=new Date,o=new Date(e),n=Math.floor((t.getTime()-o.getTime())/1e3);if(n<60)return"just now";let r=Math.floor(n/60);if(r<60)return kn(r,"min");let i=Math.floor(r/60);if(i<24)return kn(i,"hour");let a=Math.floor(i/24);if(a<7)return kn(a,"day");let l=Math.floor(a/7);if(l<4)return kn(l,"week");let s=Math.floor(a/30);if(s<12)return kn(s,"month");let d=Math.floor(a/365);return kn(d,"year")}import{Loader2Icon as Gp}from"lucide-react";import{jsx as $p}from"react/jsx-runtime";function St({className:e,...t}){let{ref:o,...n}=t;return $p(Gp,{role:"status","aria-label":"Loading",className:N("size-4 animate-spin",e),...n})}import{Fragment as oa,jsx as U,jsxs as ze}from"react/jsx-runtime";function Xp(e){return Js(e)}function Qp(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function Zp(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function as(e){let t={};for(let o of e)t[o.nodeId]={nodeId:o.nodeId,nodeName:o.nodeName,nodeType:o.nodeType,status:o.status,output:o.output};return t}function ef(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function Bl({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return U(oa,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(ef(r))return U("a",{className:"text-blue-500 underline hover:text-blue-400",href:r,rel:"noopener noreferrer",target:"_blank",children:n},r)}return n})})}function tf({data:e,isError:t=!1}){let[o,n]=Mo(!1);return U(E,{className:"h-7 px-2",onClick:async i=>{i.stopPropagation();try{let a=t?String(e):JSON.stringify(e,null,2);await navigator.clipboard.writeText(a),n(!0),setTimeout(()=>n(!1),2e3)}catch(a){console.error("Failed to copy:",a)}},size:"sm",type:"button",variant:"ghost",children:o?U(zl,{className:"h-3 w-3 text-green-600"}):U(Up,{className:"h-3 w-3"})})}function ta({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:i}){let[a,l]=Mo(o);return ze("div",{children:[ze("div",{className:"mb-2 flex w-full items-center justify-between",children:[ze("button",{className:"flex items-center gap-1.5",onClick:()=>l(!a),type:"button",children:[a?U(ss,{className:"h-3 w-3 text-muted-foreground"}):U(is,{className:"h-3 w-3 text-muted-foreground"}),U("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),ze("div",{className:"flex items-center gap-1",children:[i&&U(E,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:U("a",{href:i,rel:"noopener noreferrer",target:"_blank",children:U(Kp,{className:"h-3 w-3"})})}),n!==void 0&&U(tf,{data:n,isError:r})]})]}),a&&t]})}function of({output:e,input:t,actionType:o}){let r=(o?ge(o):void 0)?.outputConfig,i=o?Xp(o):void 0,a=r?.type!=="component"?r:i,l=a?Qp(e,a):void 0,s=!(r||i)&&Zp(e),c=(()=>{if(r?.type==="component"){let v=r.component;return U("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:U(v,{input:t,output:e})})}if(a&&l)switch(a.type){case"image":{let v=a.field==="base64"&&!l.startsWith("data:")?`data:image/png;base64,${l}`:l;return U("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:U(Fl,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:v,unoptimized:!0,width:384})})}case"video":return U("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:U("video",{className:"max-h-96 w-auto rounded",controls:!0,src:l,children:U("track",{kind:"captions"})})});case"url":return U("div",{className:"overflow-hidden rounded-lg border bg-muted/50",children:U("iframe",{className:"h-96 w-full rounded",sandbox:"allow-scripts allow-same-origin",src:l,title:"Output preview"})});default:return null}return s?U("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:U(Fl,{alt:"AI generated output",className:"max-h-96 w-auto rounded",height:384,src:`data:image/png;base64,${e.base64}`,unoptimized:!0,width:384})}):null})(),u=c!==null,f=a?.type==="url"&&l?l:void 0;return ze(oa,{children:[U(ta,{copyData:e,title:"Output",children:U("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:U(Bl,{data:e})})}),u&&U(ta,{defaultExpanded:!0,externalLink:f,title:"Result",children:c})]})}function nf({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:i,isLast:a}){return ze("div",{className:"relative flex gap-3",children:[ze("div",{className:"relative -ml-px flex flex-col items-center pt-2",children:[!i&&U("div",{className:"absolute bottom-full h-2 w-px bg-border"}),U("div",{className:N("z-10 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-0",r(e.status)),children:n(e.status)}),!a&&U("div",{className:"absolute top-[calc(0.5rem+1.25rem)] bottom-0 w-px bg-border"})]}),ze("div",{className:"min-w-0 flex-1",children:[U("button",{className:"group w-full rounded-lg py-2 text-left transition-colors hover:bg-muted/50",onClick:o,type:"button",children:ze("div",{className:"flex items-center gap-3",children:[U("div",{className:"min-w-0 flex-1",children:ze("div",{className:"flex items-center gap-2",children:[t?U(ss,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):U(is,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),U("span",{className:"truncate font-medium text-sm transition-colors group-hover:text-foreground",children:e.nodeName||e.nodeType})]})}),e.duration&&U("span",{className:"shrink-0 font-mono text-muted-foreground text-xs tabular-nums",children:Number.parseInt(e.duration,10)<1e3?`${e.duration}ms`:`${(Number.parseInt(e.duration,10)/1e3).toFixed(2)}s`})]})}),t&&ze("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&U(ta,{copyData:e.input,title:"Input",children:U("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:U(Bl,{data:e.input})})}),e.output!==null&&e.output!==void 0&&U(of,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&U(ta,{copyData:e.error,defaultExpanded:!0,isError:!0,title:"Error",children:U("pre",{className:"overflow-auto rounded-lg border border-red-500/20 bg-red-500/5 p-3 font-mono text-red-600 text-xs leading-relaxed",children:e.error})}),!(e.input||e.output||e.error)&&U("div",{className:"rounded-lg border bg-muted/30 py-4 text-center text-muted-foreground text-xs",children:"No data recorded"})]})]})]},e.id)}function Cn({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=rs(Ue),[r,i]=rs(ro),[,a]=rs(Xo),[l,s]=Mo([]),[d,c]=Mo({}),[u,f]=Mo(new Set),[v,C]=Mo(new Set),[h,y]=Mo(!0),m=Yp(null),b=tr(async(O=!0)=>{if(!n){y(!1);return}try{O&&y(!0);let W=await j.workflow.getExecutions(n);s(W)}catch(W){console.error("Failed to load executions:",W),s([])}finally{O&&y(!1)}},[n]);ea(()=>{t&&(t.current=()=>b(!1))},[b,t]),ea(()=>{b()},[b]);let g=tr((O,W)=>O.map($=>({id:$.id,nodeId:$.nodeId,nodeName:$.nodeName,nodeType:$.nodeType,status:$.status,startedAt:new Date($.startedAt),completedAt:$.completedAt?new Date($.completedAt):null,duration:$.duration,input:$.input,output:$.output,error:$.error})),[]),S=tr(async O=>{try{let W=await j.workflow.getExecutionLogs(O),$=g(W.logs,W.execution.workflow);c(T=>({...T,[O]:$})),O===r&&a(as($))}catch(W){console.error("Failed to load execution logs:",W),c($=>({...$,[O]:[]}))}},[g,r,a]);ea(()=>{if(l.length===0)return;let O=l[0];O.status==="running"&&O.id!==m.current&&(m.current=O.id,i(O.id),f(W=>{let $=new Set(W);return $.add(O.id),$}),S(O.id),o&&o(O.id))},[l,i,S,o]);let D=tr(async O=>{try{let W=await j.workflow.getExecutionLogs(O),$=g(W.logs,W.execution.workflow);c(T=>({...T,[O]:$})),O===r&&a(as($))}catch(W){console.error(`Failed to refresh logs for ${O}:`,W)}},[g,r,a]);ea(()=>{if(!(e&&n))return;let W=setInterval(async()=>{try{let $=await j.workflow.getExecutions(n);s($);for(let T of u)await D(T)}catch($){console.error("Failed to poll executions:",$)}},2e3);return()=>clearInterval(W)},[e,n,u,D]);let I=tr(async O=>{try{await j.workflow.cancelExecution(O),await b(!1)}catch(W){console.error("Failed to cancel execution:",W)}},[b]),x=async O=>{let W=new Set(u);W.has(O)?W.delete(O):(W.add(O),await S(O)),f(W)},p=O=>{if(r===O){i(null),a({});return}i(O);let W=d[O]||[];a(as(W))},w=O=>{let W=new Set(v);W.has(O)?W.delete(O):W.add(O),C(W)},G=O=>{switch(O){case"success":return U(zl,{className:"h-3 w-3 text-white"});case"error":return U(Jp,{className:"h-3 w-3 text-white"});case"cancelled":return U(Wl,{className:"h-3 w-3 text-white"});case"running":return U(qp,{className:"h-3 w-3 animate-spin text-white"});default:return U(_p,{className:"h-3 w-3 text-white"})}},te=O=>{switch(O){case"success":return"bg-green-600";case"error":return"bg-red-600";case"cancelled":return"bg-yellow-600";case"running":return"bg-blue-600";default:return"bg-muted-foreground"}};return h?U("div",{className:"flex items-center justify-center py-12",children:U(St,{})}):l.length===0?ze("div",{className:"flex flex-col items-center justify-center py-16",children:[U("div",{className:"mb-3 rounded-lg border border-dashed p-4",children:U(jp,{className:"h-6 w-6 text-muted-foreground"})}),U("div",{className:"font-medium text-foreground text-sm",children:"No runs yet"}),U("div",{className:"mt-1 text-muted-foreground text-xs",children:"Execute your workflow to see runs here"})]}):U("div",{className:"space-y-3",children:l.map((O,W)=>{let $=u.has(O.id),T=r===O.id,H=(d[O.id]||[]).sort((X,z)=>new Date(X.startedAt).getTime()-new Date(z.startedAt).getTime());return ze("div",{className:N("overflow-hidden rounded-lg border bg-card transition-all",T&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[ze("div",{className:"flex w-full items-center gap-3 p-4",children:[U("button",{className:"flex size-5 shrink-0 items-center justify-center rounded-full border-0 transition-colors hover:bg-muted",onClick:()=>x(O.id),type:"button",children:U("div",{className:N("flex size-5 items-center justify-center rounded-full border-0",te(O.status)),children:G(O.status)})}),ze("button",{className:"min-w-0 flex-1 text-left transition-colors hover:opacity-80",onClick:()=>p(O.id),type:"button",children:[U("div",{className:"mb-1 flex items-center gap-2",children:ze("span",{className:"font-semibold text-sm",children:["Run #",l.length-W]})}),ze("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[U("span",{children:Ml(O.startedAt)}),O.duration&&ze(oa,{children:[U("span",{children:"\u2022"}),U("span",{className:"tabular-nums",children:Number.parseInt(O.duration,10)<1e3?`${O.duration}ms`:`${(Number.parseInt(O.duration,10)/1e3).toFixed(2)}s`})]}),H.length>0&&ze(oa,{children:[U("span",{children:"\u2022"}),ze("span",{children:[H.length," ",H.length===1?"step":"steps"]})]})]})]}),(O.status==="running"||O.status==="pending")&&U("button",{className:"flex shrink-0 items-center justify-center rounded p-1 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive",onClick:X=>{X.stopPropagation(),I(O.id)},title:"Stop execution",type:"button",children:U(Wl,{className:"h-3.5 w-3.5"})}),U("button",{className:"flex shrink-0 items-center justify-center rounded p-1 transition-colors hover:bg-muted",onClick:()=>x(O.id),type:"button",children:$?U(ss,{className:"h-4 w-4 text-muted-foreground"}):U(is,{className:"h-4 w-4 text-muted-foreground"})})]}),$&&U("div",{className:"border-t bg-muted/20",children:H.length===0?U("div",{className:"py-8 text-center text-muted-foreground text-xs",children:"No steps recorded"}):U("div",{className:"p-4",children:H.map((X,z)=>U(nf,{getStatusDotClass:te,getStatusIcon:G,isExpanded:v.has(X.id),isFirst:z===0,isLast:z===H.length-1,log:X,onToggle:()=>w(X.id)},X.id))})})]},O.id)})})}import{Fragment as go,jsx as L,jsxs as K}from"react/jsx-runtime";var df=/[^a-zA-Z0-9\s]/g,cf=/\s+/,Ul={"Database Query":"database"},uf=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=or(!1),i=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",l=[];e.length>0&&l.push(`${e.length} ${i}`),t.length>0&&l.push(`${t.length} ${a}`);let s=l.join(" and ");return K(go,{children:[K("div",{className:"flex size-full flex-col",children:[L("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:L("h2",{className:"font-semibold text-foreground",children:"Properties"})}),K("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[K("div",{className:"space-y-2",children:[L(M,{children:"Selection"}),K("p",{className:"text-muted-foreground text-sm",children:[s," selected"]})]}),L("div",{className:"flex items-center gap-2 pt-4",children:K(E,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[L(na,{className:"mr-2 size-4"}),"Delete"]})})]})]}),L(nn,{onOpenChange:r,open:n,children:K(rn,{children:[K(an,{children:[L(ln,{children:"Delete Selected Items"}),K(dn,{children:["Are you sure you want to delete ",s,"? This action cannot be undone."]})]}),K(sn,{children:[L(un,{children:"Cancel"}),L(cn,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},mf=()=>{let[e]=fo(Ce),[t]=fo(_e),[o]=fo(re),n=ls(ce),[r]=fo(kt),[i]=fo(Ue),[a,l]=fo(gt),s=ls(no),d=Wo(ao),c=Wo(so),u=Wo(io),f=Wo(ui),v=Wo(Zo),{open:C}=oe(),h=Wo(Ir),y=Wo(Tr),[m,b]=fo(oo),[g,S]=or(!1),[D,I]=or(!1),[x,p]=or(!1),[w,G]=or(!1),[te,O]=fo(Ht),W=_l(null),$=_l({}),T=o.find(Q=>Q.id===e),H=n.find(Q=>Q.id===t),X=o.filter(Q=>Q.selected),z=n.filter(Q=>Q.selected),q=X.length+z.length>1;$l(()=>{if(!T||te!=="code")return;let Q=T.data.config?.actionType==="Condition",we=T.data.type==="trigger"&&T.data.config?.triggerType==="Manual";(Q||we)&&O("properties")},[T,te,O]);let A=ls(ft);$l(()=>{if(!(T&&s))return;let Q=T.data.config?.actionType,we=T.data.config?.integrationId;if(!(Q&&we))return;let F=ge(Q)?.integration||Ul[Q];if(!F||A.some(me=>me.id===we))return;let pe=A.filter(me=>me.type===F);if(pe.length===1){let me={...T.data.config,integrationId:pe[0].id};d({id:T.id,data:{config:me}})}else if(pe.length===0){let me={...T.data.config,integrationId:void 0};d({id:T.id,data:{config:me}})}},[T,A,s,d]);let B=lf(()=>{let we=`${a.replace(df,"").split(cf).map((F,Y)=>Y===0?F.toLowerCase():F.charAt(0).toUpperCase()+F.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:P}=gr(o,n,{functionName:we});return P},[o,n,a]),k=()=>{T&&navigator.clipboard.writeText(Nn(T))},R=()=>{navigator.clipboard.writeText(B),Tn.success("Code copied to clipboard")},_=()=>{e&&(c(e),S(!1))},ne=()=>{if(T){let Q=T.data.enabled??!0;d({id:T.id,data:{enabled:!Q}})}},le=()=>{t&&(u(t),I(!1))},V=async()=>{if(i)try{await j.workflow.deleteExecutions(i),h(),p(!1)}catch(Q){console.error("Failed to delete runs:",Q);let we=Q instanceof Error?Q.message:"Failed to delete runs";Tn.error(we)}},Ae=Q=>{T&&d({id:T.id,data:{label:Q}})},tt=Q=>{T&&d({id:T.id,data:{description:Q}})},Ye=sf(async(Q,we,P,F)=>{let pe=ge(we)?.integration||Ul[we];if(!pe){y(me=>{let Ne=new Set(me);return Ne.delete(Q),Ne});return}try{let me=await j.integration.getAll();if(F.aborted)return;let Ne=me.filter(ct=>ct.type===pe);if(Ne.length===1&&!F.aborted){let ct={...P,actionType:we,integrationId:Ne[0].id};d({id:Q,data:{config:ct}})}}catch(me){console.error("Failed to auto-select integration:",me)}finally{F.aborted||y(me=>{let Ne=new Set(me);return Ne.delete(Q),Ne})}},[d,y]),ot=Q=>{if(T){let we={...T.data.config,...Q};d({id:T.id,data:{config:we}})}},Bt=(Q,we)=>{if(T){let P={...T.data.config,[Q]:we};if(Q==="actionType"&&T.data.config?.integrationId&&(P={...P,integrationId:void 0}),d({id:T.id,data:{config:P}}),Q==="actionType"){let F=$.current[T.id];F&&F.abort();let Y=new AbortController;$.current[T.id]=Y,y(pe=>new Set(pe).add(T.id)),Ye(T.id,we,P,Y.signal)}}},Dt=async Q=>{if(l(Q),i)try{await j.workflow.update(i,{name:Q,nodes:o,edges:n})}catch(we){console.error("Failed to update workflow name:",we),Tn.error("Failed to update workspace name")}},ko=async()=>{G(!0);try{W.current&&await W.current()}catch(Q){console.error("Failed to refresh runs:",Q),Tn.error("Failed to refresh runs")}finally{G(!1)}};return q?L(uf,{onDelete:f,selectedEdges:z,selectedNodes:X}):H?K(go,{children:[K("div",{className:"flex size-full flex-col",children:[L("div",{className:"flex h-14 w-full shrink-0 items-center border-b bg-transparent px-4",children:L("h2",{className:"font-semibold text-foreground",children:"Properties"})}),K("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),L(ae,{disabled:!0,id:"edge-id",value:H.id})]}),K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),L(ae,{disabled:!0,id:"edge-source",value:H.source})]}),K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),L(ae,{disabled:!0,id:"edge-target",value:H.target})]}),s&&L("div",{className:"flex items-center gap-2 pt-4",children:K(E,{className:"text-muted-foreground",onClick:()=>I(!0),size:"sm",variant:"ghost",children:[L(na,{className:"mr-2 size-4"}),"Delete"]})})]})]}),L(nn,{onOpenChange:I,open:D,children:K(rn,{children:[K(an,{children:[L(ln,{children:"Delete Edge"}),L(dn,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),K(sn,{children:[L(un,{children:"Cancel"}),L(cn,{onClick:le,children:"Delete"})]})]})})]}):T?K(go,{children:[K(Ma,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:O,value:te,children:[K(Wa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),(T.data.type!=="trigger"||T.data.config?.triggerType!=="Manual")&&T.data.config?.actionType!=="Condition"?L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,s&&L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),K(So,{className:"flex flex-col overflow-hidden",value:"properties",children:[T.data.type==="action"&&!T.data.config?.actionType&&s&&L("div",{className:"flex min-h-0 flex-1 flex-col px-4 pt-4",children:L(Qr,{disabled:r,isNewlyCreated:T?.id===m,onSelectAction:Q=>{Bt("actionType",Q),T?.id===m&&b(null)}})}),!(T.data.type==="action"&&!T.data.config?.actionType&&s)&&K("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),L(ae,{readOnly:!0,id:"node-id",value:T?.id||""})]}),T.data.type==="trigger"&&L(Zr,{config:T.data.config||{},disabled:r||!s,onUpdateConfig:Bt,workflowId:i??void 0}),T.data.type==="action"&&!T.data.config?.actionType&&!s&&L("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:L("p",{className:"text-muted-foreground text-sm",children:"No action configured for this step."})}),T.data.type==="action"&&T.data.config?.actionType?L(qr,{config:T.data.config||{},disabled:r||!s,isOwner:s,onUpdateConfig:Bt,onUpdateMultipleConfig:ot}):null,T.data.type!=="action"||T.data.config?.actionType?K(go,{children:[K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"label",children:"Label"}),L(ae,{disabled:r||!s,id:"label",onChange:Q=>Ae(Q.target.value),value:T.data.label})]}),K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"description",children:"Description"}),L(ae,{disabled:r||!s,id:"description",onChange:Q=>tt(Q.target.value),placeholder:"Optional description",value:T.data.description||""})]})]}):null,!s&&L("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:L("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),s&&K("div",{className:"flex items-center gap-2 pt-4",children:[T.data.type==="action"&&L(E,{className:"text-muted-foreground",onClick:ne,size:"sm",variant:"ghost",children:T.data.enabled===!1?K(go,{children:[L(af,{className:"mr-2 size-4"}),"Disabled"]}):K(go,{children:[L(rf,{className:"mr-2 size-4"}),"Enabled"]})}),K(E,{className:"text-muted-foreground",onClick:()=>S(!0),size:"sm",variant:"ghost",children:[L(na,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),L(So,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let Q=T.data.config?.triggerType,we="",P="typescript";return T.data.type==="trigger"?Q==="Schedule"?(we="vercel.json",P="json"):Q==="Webhook"&&(we=`app/api${T.data.config?.webhookPath||"/webhook"}/route.ts`,P="typescript"):we=`steps/${T.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,K(go,{children:[we&&K("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[K("div",{className:"flex items-center gap-2",children:[L(Hl,{className:"size-3.5 text-muted-foreground"}),L("code",{className:"text-muted-foreground text-xs",children:we})]}),K(E,{className:"text-muted-foreground",onClick:k,size:"sm",variant:"ghost",children:[L(Vl,{className:"mr-2 size-4"}),"Copy"]})]}),L("div",{className:"flex-1 overflow-hidden",children:L(yt,{height:"100%",language:P,options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:Nn(T)})})]})})()}),s&&K(So,{className:"flex flex-col overflow-hidden",value:"runs",children:[K("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[K(E,{className:"text-muted-foreground",disabled:w,onClick:ko,size:"sm",variant:"ghost",children:[L(Gl,{className:`mr-2 size-4 ${w?"animate-spin":""}`}),"Refresh"]}),K(E,{className:"text-muted-foreground",onClick:()=>p(!0),size:"sm",variant:"ghost",children:[L(ds,{className:"mr-2 size-4"}),"Clear All"]})]}),L("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:L(Cn,{isActive:te==="runs",onRefreshRef:W})})]})]}),L(nn,{onOpenChange:p,open:x,children:K(rn,{children:[K(an,{children:[L(ln,{children:"Delete All Runs"}),L(dn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),K(sn,{children:[L(un,{children:"Cancel"}),L(cn,{onClick:V,children:"Delete"})]})]})}),L(nn,{onOpenChange:S,open:g,children:K(rn,{children:[K(an,{children:[L(ln,{children:"Delete Step"}),L(dn,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),K(sn,{children:[L(un,{children:"Cancel"}),L(cn,{onClick:_,children:"Delete"})]})]})})]}):K(go,{children:[K(Ma,{className:"size-full",defaultValue:"properties",onValueChange:O,value:te,children:[K(Wa,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),s&&L(To,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),L(So,{className:"flex flex-col overflow-hidden",value:"properties",children:K("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),L(ae,{disabled:!s,id:"workflow-name",onChange:Q=>Dt(Q.target.value),value:a})]}),K("div",{className:"space-y-2",children:[L(M,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),L(ae,{disabled:!0,id:"workflow-id",value:i||"Not saved"})]}),!s&&L("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:L("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),s&&K("div",{className:"flex items-center gap-2 pt-4",children:[K(E,{className:"text-muted-foreground",onClick:()=>{C(Pe,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{v()}})},size:"sm",variant:"ghost",children:[L(ds,{className:"mr-2 size-4"}),"Clear"]}),K(E,{className:"text-muted-foreground",onClick:()=>{C(Pe,{title:"Delete Workflow",message:`Are you sure you want to delete "${a}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(i)try{await j.workflow.delete(i),Tn.success("Workflow deleted successfully"),window.location.href="/"}catch(Q){console.error("Failed to delete workflow:",Q),Tn.error("Failed to delete workflow. Please try again.")}}})},size:"sm",variant:"ghost",children:[L(na,{className:"mr-2 size-4"}),"Delete"]})]})]})}),s&&K(So,{className:"flex flex-col overflow-hidden",value:"runs",children:[K("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[K(E,{className:"text-muted-foreground",disabled:w,onClick:ko,size:"sm",variant:"ghost",children:[L(Gl,{className:`mr-2 size-4 ${w?"animate-spin":""}`}),"Refresh"]}),K(E,{className:"text-muted-foreground",onClick:()=>p(!0),size:"sm",variant:"ghost",children:[L(ds,{className:"mr-2 size-4"}),"Clear All"]})]}),L("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:L(Cn,{isActive:te==="runs",onRefreshRef:W})})]}),K(So,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:[K("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[K("div",{className:"flex items-center gap-2",children:[L(Hl,{className:"size-3.5 text-muted-foreground"}),K("code",{className:"text-muted-foreground text-xs",children:["workflows/",a.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"workflow",".ts"]})]}),K(E,{className:"text-muted-foreground",onClick:R,size:"sm",variant:"ghost",children:[L(Vl,{className:"mr-2 size-4"}),"Copy"]})]}),L("div",{className:"flex-1 overflow-hidden",children:L(yt,{height:"100%",language:"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!0,wordWrap:"off",padding:{top:16,bottom:16}},value:B})})]})]}),L(nn,{onOpenChange:p,open:x,children:K(rn,{children:[K(an,{children:[L(ln,{children:"Delete All Runs"}),L(dn,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),K(sn,{children:[L(un,{children:"Cancel"}),L(cn,{onClick:V,children:"Delete"})]})]})})]})},cs=()=>L("div",{className:"hidden size-full flex-col bg-background md:flex",children:L(mf,{})});import{jsx as Pt,jsxs as ra}from"react/jsx-runtime";var ps=({workflowId:e})=>{let t=vf(),o=Gt(),[n,r]=Ut(kt),[i,a]=Ut(Ar),[l]=Ut(re),[s]=Ut(ce),[d]=Ut(Ue),[c]=Ut(ro),u=At(re),f=At(ce),v=At(Ue),C=At(gt),h=At(ao),y=At(rt),[m,b]=Ut(mi),g=At(Sr),S=At(xr),D=At(Nr),[I,x]=Ut(kr),[p,w]=Ut(ii),G=At(br),[te,O]=Ut(no),W=At(ft),$=At(hr),T=pf(Ot),[H,X]=us(30),[z,q]=us(I),[A,B]=us(!1),k=Fo(!1),R=Fo(!1);It(()=>{if(R.current)return;R.current=!0;let P=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-width="));if(P){let Y=Number.parseFloat(P.split("=")[1]);!Number.isNaN(Y)&&Y>=20&&Y<=50&&X(Y)}let F=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-collapsed="));F&&w(F.split("=")[1]==="true")},[w]);let _=Fo(!1);It(()=>{if(!_.current){_.current=!0;return}document.cookie=`sidebar-width=${H}; path=/; max-age=31536000`},[H]),It(()=>{R.current&&(document.cookie=`sidebar-collapsed=${p}; path=/; max-age=31536000`)},[p]),It(()=>{let P=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),I||!P){q(!0),x(!0);return}D(!0);let F=setTimeout(()=>{q(!0),x(!0)},100),Y=setTimeout(()=>D(!1),400);return()=>{clearTimeout(F),clearTimeout(Y),D(!1)}},[I,x,D]),It(()=>{let P=F=>{(F.metaKey||F.ctrlKey)&&F.key==="b"&&(F.preventDefault(),D(!0),w(Y=>!Y),setTimeout(()=>D(!1),350))};return window.addEventListener("keydown",P),()=>window.removeEventListener("keydown",P)},[D,w]),It(()=>(S(!o&&z&&!p?`${H}%`:null),()=>{S(null)}),[o,S,H,z,p]);let ne=yo(P=>{P.preventDefault(),k.current=!0,B(!0);let F=pe=>{if(!k.current)return;let me=(window.innerWidth-pe.clientX)/window.innerWidth*100;X(Math.min(50,Math.max(20,me)))},Y=()=>{k.current=!1,B(!1),document.removeEventListener("mousemove",F),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",F),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),le=Fo(null),V=Fo(null),Ae=Fo(l);It(()=>{Ae.current=l},[l]);let tt=yo(async P=>{r(!0),v(e),C("AI Generated Workflow");try{let F=await j.ai.generate(P),Y=(F.nodes||[]).map(pe=>({...pe,selected:!1}));u(Y),f(F.edges||[]),C(F.name||"AI Generated Workflow"),await j.workflow.update(e,{name:F.name,description:F.description,nodes:F.nodes,edges:F.edges})}catch(F){console.error("Failed to generate workflow:",F),ms.error("Failed to generate workflow")}finally{r(!1)}},[e,r,v,C,u,f]),Ye=yo(async()=>{try{let P=await j.workflow.getById(e);if(!P){b(!0);return}let F=P.nodes.map(Y=>({...Y,selected:!1,data:{...Y.data,status:"idle"}}));u(F),f(P.edges),v(P.id),C(P.name),G(P.visibility??"private"),O(P.isOwner!==!1),y(!1),b(!1)}catch(P){console.error("Failed to load workflow:",P),ms.error("Failed to load workflow")}},[e,u,f,v,C,G,O,y,b]),ot=Fo(null);It(()=>{(async()=>{let F=t?.get("generating")==="true",Y=sessionStorage.getItem("ai-prompt"),pe=sessionStorage.getItem("generating-workflow-id");d===e&&l.length>0||(F&&Y&&pe===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await tt(Y)):await Ye())})()},[e,t,d,l.length,tt,Ye]),It(()=>{if(l.length===0||!d||!te)return;let P=ot.current;if(P&&P.workflowId===d&&P.version===T)return;(async()=>{try{let Y=await j.integration.getAll();W(Y),$(!0);let pe=new Set(Y.map(Ne=>Ne.id)),me=l.map(Ne=>vi(Ne,Y,pe)).filter(Ne=>Ne!==null);for(let Ne of me){let ct=l.find(fr=>fr.id===Ne.nodeId);ct&&h({id:Ne.nodeId,data:{config:{...ct.data.config,integrationId:Ne.newIntegrationId}}})}ot.current={workflowId:d,version:T},me.length>0&&y(!0)}catch(Y){console.error("Failed to auto-fix integrations:",Y)}})()},[l,d,T,te,h,W,$,y]);let Bt=yo(async()=>{if(!(!d||n)){a(!0);try{await j.workflow.update(d,{nodes:l,edges:s}),y(!1)}catch(P){console.error("Failed to save workflow:",P),ms.error("Failed to save workflow")}finally{a(!1)}}},[d,l,s,n,a,y]),Dt=yo(P=>P.tagName==="INPUT"||P.tagName==="TEXTAREA",[]),ko=yo(P=>P.closest(".monaco-editor")!==null,[]),Q=yo(P=>(P.metaKey||P.ctrlKey)&&P.key==="s"?(P.preventDefault(),P.stopPropagation(),Bt(),!0):!1,[Bt]),we=yo((P,F)=>(P.metaKey||P.ctrlKey)&&P.key==="Enter"?(Dt(F)||ko(F)||(P.preventDefault(),P.stopPropagation(),g(!0)),!0):!1,[g,Dt,ko]);return It(()=>{let P=F=>{let Y=F.target;Q(F)||we(F,Y)};return document.addEventListener("keydown",P,!0),()=>document.removeEventListener("keydown",P,!0)},[Q,we]),It(()=>()=>{le.current&&clearInterval(le.current),V.current&&clearInterval(V.current)},[]),It(()=>{if(V.current&&(clearInterval(V.current),V.current=null),!c){for(let F of Ae.current)h({id:F.id,data:{status:"idle"}});return}let P=async()=>{try{let F=await j.workflow.getExecutionStatus(c);for(let Y of F.nodeStatuses)h({id:Y.nodeId,data:{status:Y.status}});F.status!=="running"&&V.current&&(clearInterval(V.current),V.current=null)}catch(F){console.error("Failed to poll selected execution status:",F),V.current&&(clearInterval(V.current),V.current=null)}};return P(),V.current=setInterval(P,500),()=>{V.current&&(clearInterval(V.current),V.current=null)}},[c,h]),ra("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[m&&Pt("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:ra("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[Pt("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),Pt("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),Pt(E,{asChild:!0,children:Pt(yf,{href:"/",children:"New Workflow"})})]})}),!o&&p&&Pt("button",{className:"pointer-events-auto absolute top-1/2 right-0 z-20 flex size-6 -translate-y-1/2 items-center justify-center rounded-l-full border border-r-0 bg-background shadow-sm transition-colors hover:bg-muted",onClick:()=>{D(!0),w(!1),setTimeout(()=>D(!1),350)},type:"button",children:Pt(ff,{className:"size-4"})}),!o&&ra("div",{className:"pointer-events-auto absolute inset-y-0 right-0 z-20 border-l bg-background transition-transform duration-300 ease-out",style:{width:`${H}%`,transform:z&&!p?"translateX(0)":"translateX(100%)"},children:[ra("div",{"aria-orientation":"vertical","aria-valuenow":H,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:ne,role:"separator",tabIndex:0,children:[Pt("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(A||p)&&Pt("button",{className:"absolute top-1/2 left-0 flex size-6 -translate-x-1/2 -translate-y-1/2 items-center justify-center rounded-full border bg-background opacity-0 shadow-sm transition-opacity hover:bg-muted group-hover:opacity-100",onClick:P=>{P.stopPropagation(),D(!0),w(!0),setTimeout(()=>D(!1),350)},onMouseDown:P=>P.stopPropagation(),type:"button",children:Pt(gf,{className:"size-4"})})]}),Pt(cs,{})]}),o&&Pt(cs,{})]})};import{useAtomValue as fs,useSetAtom as nr}from"jotai";import{nanoid as wf}from"nanoid";import{useRouter as xf}from"next/navigation";import{useCallback as ql,useEffect as aa,useRef as Nf}from"react";import{toast as kf}from"sonner";import{anonymousClient as hf}from"better-auth/client/plugins";import{createAuthClient as bf}from"better-auth/react";var zo=bf({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[hf()]}),{signIn:k0,signOut:Kl,signUp:C0,useSession:Sn}=zo;function Cf(){return{id:wf(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var jl=()=>{let e=xf(),{data:t}=Sn(),o=fs(re),n=fs(ce),r=nr(re),i=nr(ce),a=nr(gt),l=nr(kr),s=nr(Cr),d=Nf(!1),c=fs(gt);aa(()=>{l(!1)},[l]),aa(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=ql(async()=>{t||(await zo.signIn.anonymous(),await new Promise(v=>setTimeout(v,100)))},[t]),f=ql(()=>{let v=Cf();r([v])},[r]);return aa(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:f},draggable:!1,selectable:!1}]),i([]),a("New Workflow"),d.current=!1},[r,i,a,f]),aa(()=>{(async()=>{let C=o.filter(h=>h.type!=="add");if(!(C.length===0||d.current)){d.current=!0;try{await u();let h=await j.workflow.create({name:"Untitled Workflow",description:"",nodes:C,edges:n});sessionStorage.setItem("animate-sidebar","true"),s(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${h.id}`)}catch(h){console.error("Failed to create workflow:",h),kf.error("Failed to create workflow")}}})()},[o,n,e,u,s]),null};import{useRouter as Tf}from"next/navigation";import{useEffect as Sf}from"react";var Jl=()=>{let e=Tf();return Sf(()=>{(async()=>{try{let n=(await j.workflow.getAll()).filter(r=>r.name!=="__current__");if(n.length>0){let r=n.sort((i,a)=>new Date(a.updatedAt).getTime()-new Date(i.updatedAt).getTime())[0];e.replace(`/workflows/${r.id}`)}else e.replace("/")}catch(o){console.error("Failed to load workflows:",o),e.replace("/")}})()},[e]),null};import{jsx as An}from"react/jsx-runtime";var Pf=()=>{let t=If().slug;return!t||t.length===0?An(jl,{}):t[0]==="auth"&&t.length===2?An("main",{className:"flex items-center justify-center min-h-screen",children:An(Af,{path:t[1]})}):t[0]==="workflows"&&t.length===1?An(Jl,{}):t[0]==="workflows"&&t.length===2?An("div",{className:"pointer-events-none relative z-10",children:An(ps,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as th}from"@xyflow/react";import{Provider as oh,useSetAtom as nh}from"jotai";import*as Ca from"react";import{AnimatePresence as Rf,LayoutGroup as Ql,motion as Pn,useReducedMotion as Zl}from"motion/react";import{useCallback as ar,useLayoutEffect as sr,useRef as vo,useState as ed}from"react";import{Drawer as rr}from"vaul";import{Dialog as In}from"radix-ui";import{XIcon as Ef}from"lucide-react";import{jsx as Bo,jsxs as gs}from"react/jsx-runtime";function sa({...e}){return Bo(In.Root,{"data-slot":"dialog",...e})}function ys({...e}){return Bo(In.Portal,{"data-slot":"dialog-portal",...e})}function Df({className:e,...t}){return Bo(In.Overlay,{"data-slot":"dialog-overlay",className:N("data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",e),...t})}function Yl({className:e,children:t,showCloseButton:o=!0,...n}){return gs(ys,{"data-slot":"dialog-portal",children:[Bo(Df,{}),gs(In.Content,{"data-slot":"dialog-content",className:N("bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",e),...n,children:[t,o&&gs(In.Close,{"data-slot":"dialog-close",className:"ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[Bo(Ef,{}),Bo("span",{className:"sr-only",children:"Close"})]})]})]})}function Xl({className:e,...t}){return Bo(In.Title,{"data-slot":"dialog-title",className:N("text-lg leading-none font-semibold",e),...t})}import{jsx as We,jsxs as hs}from"react/jsx-runtime";var vs={type:"spring",stiffness:400,damping:35,mass:.8},Of={type:"spring",stiffness:350,damping:30,mass:.8},Lf={hidden:{opacity:0,scale:.95},visible:{opacity:1,scale:1,transition:{type:"spring",stiffness:400,damping:30}},exit:{opacity:0,scale:.95,transition:{duration:.15,ease:[.4,0,1,1]}}};function td(e,t){return e?"0%":t?"-35%":"100%"}function od(e){let t=vo(e),o=vo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),sr(()=>{t.current=e},[e]),o.current}function Mf(){let{stack:e,closeAll:t,pop:o}=oe(),n=Zl(),[r,i]=ed(0),a=vo(null),l=vo(!1),s=vo(e),d=od(e.length),c=e.length>0;c&&(s.current=e);let u=s.current,f=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:s.current.length,renderStackLength:u.length}),sr(()=>{let g=c&&!l.current;if(l.current=c,g&&i(0),a.current){let S=a.current.offsetHeight;S>0&&i(S)}},[e,c]);let v=e[e.length-1],C=n?{duration:.01}:vs,h=d===1,y=ar(()=>{v?.options.closeOnBackdropClick!==!1&&t()},[v?.options.closeOnBackdropClick,t]),m=ar(g=>{g.key==="Escape"&&v?.options.closeOnEscape!==!1&&o()},[v?.options.closeOnEscape,o]);sr(()=>{if(c)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[c,m]);let b=ar(()=>{console.log("[DesktopOverlay] handleExitComplete called"),s.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&s.current.length===0?null:We(Rf,{onExitComplete:b,children:c&&We(sa,{modal:!1,open:!0,children:hs(ys,{forceMount:!0,children:[We(Pn.div,{animate:{opacity:1},className:"fixed inset-0 z-50 bg-black/60",exit:{opacity:0},initial:{opacity:0},onClick:y,transition:{duration:.2}}),We(Pn.div,{animate:"visible",className:"fixed top-1/2 left-1/2 z-50 w-full max-w-lg -translate-x-1/2 -translate-y-1/2 px-4",exit:"exit",initial:"hidden",variants:Lf,children:We(Ql,{children:We(Pn.div,{className:"relative overflow-hidden rounded-xl border bg-background shadow-2xl ring-1 ring-black/5",layout:c,style:{minHeight:r>0?r:"auto"},transition:vs,children:We("div",{className:"relative",ref:a,children:u.map((g,S)=>{let D=S===f,I=S<f,p=D&&h&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return We(Pn.div,{animate:{x:td(D,I),scale:D?1:.94,opacity:D?1:0},"aria-hidden":!D,className:N("w-full",D?"relative":"pointer-events-none absolute inset-0"),initial:p,transition:C,children:We(g.component,{overlayId:g.id,...g.props})},g.id)})})})})})]})})})}function Wf(){let{stack:e,closeAll:t,pop:o}=oe(),n=Zl(),[r,i]=ed(0),a=vo(null),l=vo(!1),s=vo(e),d=od(e.length),c=e.length>0;c&&(s.current=e);let u=s.current,f=u.length-1;sr(()=>{let g=c&&!l.current;if(l.current=c,g&&i(0),a.current){let S=a.current.offsetHeight;S>0&&i(S)}},[e,c]);let v=e[e.length-1],C=u[f],h=n?{duration:.01}:vs,y=d===1,m=ar(g=>{g.key==="Escape"&&v?.options.closeOnEscape!==!1&&o()},[v?.options.closeOnEscape,o]);sr(()=>{if(c)return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[c,m]);let b=ar(()=>{c||(s.current=[])},[c]);return We(rr.Root,{onAnimationEnd:b,onOpenChange:g=>{g||t()},open:c,children:hs(rr.Portal,{children:[We(rr.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),hs(rr.Content,{className:N("fixed inset-x-0 bottom-0 z-50 flex max-h-[90vh] flex-col","rounded-t-2xl border-t bg-background shadow-2xl"),children:[We(rr.Title,{className:"sr-only",children:C?.options.title||"Dialog"}),We("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),We(Ql,{children:We(Pn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:Of,children:We("div",{className:"relative",ref:a,children:u.map((g,S)=>{let D=S===f,I=S<f,p=D&&y&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return We(Pn.div,{animate:{x:td(D,I),scale:D?1:.94,opacity:D?1:0},"aria-hidden":!D,className:N("w-full",D?"relative":"pointer-events-none absolute inset-0"),initial:p,transition:h,children:We(g.component,{overlayId:g.id,...g.props})},g.id)})})})}),We("div",{className:"h-safe-area-inset-bottom"})]})]})})}function nd(){return Gt()?We(Wf,{}):We(Mf,{})}import{useAtom as Ff}from"jotai";import{useEffect as zf,useRef as rd}from"react";import{atom as Jt}from"jotai";var Je=Jt([]),iT=Jt(e=>e(Je).length>0),lT=Jt(e=>e(Je).length);function bs(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var dT=Jt(null,(e,t,o)=>{let n=bs(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(Je,[r]),n}),cT=Jt(null,(e,t,o)=>{let n=bs(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(Je,[...e(Je),r]),n}),uT=Jt(null,(e,t)=>{let o=e(Je);if(o.length<=1){o[0]?.options.onClose?.(),t(Je,[]);return}o[o.length-1]?.options.onClose?.(),t(Je,o.slice(0,-1))}),mT=Jt(null,(e,t,o)=>{let n=e(Je),r=bs(),i={id:r,component:o.component,props:o.props??{},options:o.options??{}};return n.length===0?t(Je,[i]):(n[n.length-1]?.options.onClose?.(),t(Je,[...n.slice(0,-1),i])),r}),pT=Jt(null,(e,t)=>{let o=e(Je);for(let n of o)n.options.onClose?.();t(Je,[])}),fT=Jt(null,(e,t,o)=>{let n=e(Je),r=n.findIndex(i=>i.id===o);if(r!==-1){for(let i=r;i<n.length;i++)n[i].options.onClose?.();t(Je,n.slice(0,r))}});function ad(){let{stack:e}=oe(),[t,o]=Ff(Je),n=rd(!1),r=rd(!1);return zf(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as Bf,jsx as sd,jsxs as Vf}from"react/jsx-runtime";var id=()=>Vf(Bf,{children:[sd(nd,{}),sd(ad,{})]});import{CircleCheckIcon as Hf,InfoIcon as Gf,Loader2Icon as $f,OctagonXIcon as _f,TriangleAlertIcon as Uf}from"lucide-react";import{useTheme as Kf}from"next-themes";import{Toaster as qf}from"sonner";import{jsx as En}from"react/jsx-runtime";var ld=({...e})=>{let{theme:t="system"}=Kf();return En(qf,{theme:t,className:"toaster group",icons:{success:En(Hf,{className:"size-4"}),info:En(Gf,{className:"size-4"}),warning:En(Uf,{className:"size-4"}),error:En(_f,{className:"size-4"}),loading:En($f,{className:"size-4 animate-spin"})},style:{"--normal-bg":"var(--popover)","--normal-text":"var(--popover-foreground)","--normal-border":"var(--border)","--border-radius":"var(--radius)"},...e})};import{usePathname as jv}from"next/navigation";import{ConnectionMode as Vv,MiniMap as Hv,useReactFlow as Gv}from"@xyflow/react";import{useAtom as pr,useAtomValue as Ks,useSetAtom as wo}from"jotai";import{useCallback as Nt,useEffect as ka,useMemo as $v,useRef as xo,useState as Ic}from"react";import{Background as jf,ReactFlow as Jf}from"@xyflow/react";import{useAtomValue as Yf}from"jotai";import"@xyflow/react/dist/style.css";import{jsx as Xf,jsxs as Qf}from"react/jsx-runtime";var dd=({children:e,...t})=>{let o=Yf(Yo);return Qf(Jf,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,snapToGrid:o.snapToGrid??!0,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[Xf(jf,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]})};import{jsx as cd,jsxs as Zf}from"react/jsx-runtime";var ud=({fromX:e,fromY:t,toX:o,toY:n})=>Zf("g",{children:[cd("path",{className:"animated",d:`M${e},${t} C ${e+(o-e)*.5},${t} ${e+(o-e)*.5},${n} ${o},${n}`,fill:"none",stroke:"var(--color-ring)",strokeWidth:1}),cd("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as ng}from"@xyflow/react";import{useAtom as rg}from"jotai";import{MapPin as ag,MapPinXInside as sg,Maximize2 as ig,ZoomIn as lg,ZoomOut as dg}from"lucide-react";import{cva as eg}from"class-variance-authority";import{Slot as VT}from"radix-ui";import{jsx as og}from"react/jsx-runtime";var tg=eg("flex w-fit items-stretch [&>*]:focus-visible:z-10 [&>*]:focus-visible:relative [&>[data-slot=select-trigger]:not([class*='w-'])]:w-fit [&>input]:flex-1 has-[select[aria-hidden=true]:last-child]:[&>[data-slot=select-trigger]:last-of-type]:rounded-r-md has-[>[data-slot=button-group]]:gap-2",{variants:{orientation:{horizontal:"[&>*:not(:first-child)]:rounded-l-none [&>*:not(:first-child)]:border-l-0 [&>*:not(:last-child)]:rounded-r-none",vertical:"flex-col [&>*:not(:first-child)]:rounded-t-none [&>*:not(:first-child)]:border-t-0 [&>*:not(:last-child)]:rounded-b-none"}},defaultVariants:{orientation:"horizontal"}});function Kt({className:e,orientation:t,...o}){return og("div",{role:"group","data-slot":"button-group","data-orientation":t,className:N(tg({orientation:t}),e),...o})}import{jsx as Yt,jsxs as cg}from"react/jsx-runtime";var md=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=ng(),[n,r]=rg(wr);return cg(Kt,{orientation:"vertical",children:[Yt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{e()},size:"icon",title:"Zoom in",variant:"secondary",children:Yt(lg,{className:"size-4"})}),Yt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{t()},size:"icon",title:"Zoom out",variant:"secondary",children:Yt(dg,{className:"size-4"})}),Yt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{o({padding:.2,duration:300})},size:"icon",title:"Fit view",variant:"secondary",children:Yt(ig,{className:"size-4"})}),Yt(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",onClick:()=>{r(!n)},size:"icon",title:n?"Hide minimap":"Show minimap",variant:"secondary",children:n?Yt(ag,{className:"size-4"}):Yt(sg,{className:"size-4"})})]})};import{useReactFlow as yg}from"@xyflow/react";import{useAtom as Dn,useAtomValue as vg}from"jotai";import{ArrowUp as hg}from"lucide-react";import{useCallback as bg,useEffect as wg,useRef as fd,useState as ws}from"react";import{toast as xs}from"sonner";import{motion as ug}from"motion/react";import{memo as mg,useMemo as pg}from"react";import{jsx as gg}from"react/jsx-runtime";var fg=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let i=ug.create(t),a=pg(()=>(e?.length??0)*r,[e,r]);return gg(i,{animate:{backgroundPosition:"0% center"},className:N("relative inline-block bg-[length:250%_100%,auto] bg-clip-text text-transparent","[--bg:linear-gradient(90deg,#0000_calc(50%-var(--spread)),var(--color-background),#0000_calc(50%+var(--spread)))] [background-repeat:no-repeat,padding-box]",o),initial:{backgroundPosition:"100% center"},style:{"--spread":`${a}px`,backgroundImage:"var(--bg), linear-gradient(var(--color-muted-foreground), var(--color-muted-foreground))"},transition:{repeat:Number.POSITIVE_INFINITY,duration:n,ease:"linear"},children:e})},pd=mg(fg);import{Fragment as xg,jsx as Xt,jsxs as Ns}from"react/jsx-runtime";function gd({workflowId:e,onWorkflowCreated:t}){let[o,n]=Dn(kt),[r,i]=ws(""),[a,l]=ws(!1),[s,d]=ws(!1),c=fd(null),u=fd(null),f=vg(re),[v,C]=Dn(ce),[h,y]=Dn(re),[m,b]=Dn(Ue),[g,S]=Dn(gt),[D,I]=Dn(Ce),{fitView:x}=yg(),p=f.filter(W=>W.type!=="add"),w=p.length>0;wg(()=>{let W=$=>{($.metaKey||$.ctrlKey)&&$.key==="k"&&($.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",W),()=>{window.removeEventListener("keydown",W)}},[]);let G=()=>{l(!0),d(!0)},te=W=>{u.current?.contains(W.relatedTarget)||(d(!1),r.trim()||l(!1))},O=bg(async W=>{if(W.preventDefault(),!(!r.trim()||o)){n(!0);try{let $=w?{nodes:p,edges:v,name:g}:void 0;console.log("[AI Prompt] Generating workflow"),console.log("[AI Prompt] Has nodes:",w),console.log("[AI Prompt] Sending existing workflow:",!!$),$&&console.log("[AI Prompt] Existing workflow:",$.nodes.length,"nodes,",$.edges.length,"edges");let T=await j.ai.generateStream(r,z=>{let q=(z.edges||[]).map(k=>({...k,type:"animated"})),A=(z.nodes||[]).filter(k=>k.data?.type==="trigger"),B=q;if(A.length>1){let k=A[0],R=(z.nodes||[]).filter(ne=>ne.data?.type!=="trigger");z.nodes=[k,...R];let _=A.slice(1).map(ne=>ne.id);B=q.filter(ne=>!_.includes(ne.source)&&!_.includes(ne.target))}y(z.nodes||[]),C(B),z.name&&S(z.name),setTimeout(()=>{x({padding:.2,duration:200})},0)},$);console.log("[AI Prompt] Received final workflow data"),console.log("[AI Prompt] Nodes:",T.nodes?.length||0),console.log("[AI Prompt] Edges:",T.edges?.length||0);let H=(T.edges||[]).map(z=>({...z,type:"animated"}));console.log("[AI Prompt] Validating nodes:",T.nodes);let X=(T.nodes||[]).filter(z=>{let q=z.data?.type,A=z.data?.config||{};return console.log(`[AI Prompt] Checking node ${z.id}:`,{type:q,config:A,hasActionType:!!A.actionType,hasTriggerType:!!A.triggerType}),q==="trigger"?!A.triggerType:q==="action"?!A.actionType:!1});if(X.length>0)throw console.error("[AI Prompt] AI generated incomplete nodes:",X),console.error("[AI Prompt] Full workflow data:",JSON.stringify(T,null,2)),new Error(`Cannot create workflow: The AI tried to create ${X.length} incomplete node(s). The requested action type may not be supported. Please try a different description using supported actions: Send Email, Send Slack Message, Create Ticket, Database Query, HTTP Request, Generate Text, Generate Image, Scrape, or Search.`);if(e){b(e),console.log("[AI Prompt] Updating existing workflow:",e),console.log("[AI Prompt] Has existingWorkflow context:",!!$),$?(console.log("[AI Prompt] REPLACING workflow with AI response"),console.log("[AI Prompt] Replacing",p.length,"nodes with",T.nodes?.length||0,"nodes")):(console.log("[AI Prompt] Setting workflow for empty canvas"),xs.success("Generated workflow"));let z=T.nodes?.find(q=>q.selected);z&&I(z.id),await j.workflow.update(e,{name:T.name,description:T.description,nodes:T.nodes,edges:H})}else{let z=await j.workflow.create({name:T.name||"AI Generated Workflow",description:T.description||"",nodes:T.nodes||[],edges:H});b(z.id),xs.success("Created workflow"),t&&t(z.id)}i(""),l(!1),d(!1),c.current?.blur()}catch($){console.error("Failed to generate workflow:",$),xs.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,w,f,v,n,b,y,C,S,I,t,x]);return Xt(xg,{children:Xt("div",{ref:u,className:"pointer-events-auto absolute bottom-4 left-1/2 z-10 -translate-x-1/2 px-4",style:{width:a?"min(100%, 42rem)":"20rem",transition:"width 150ms ease-out"},children:Ns("form",{"aria-busy":o,"aria-label":"AI workflow prompt",className:"relative flex items-center gap-2 rounded-lg border bg-background pl-3 pr-2 py-2 shadow-lg cursor-text",onClick:W=>{(W.target===W.currentTarget||W.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:W=>{W.target===W.currentTarget&&W.preventDefault()},onSubmit:O,role:"search",children:[o&&r?Xt(pd,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Xt("textarea",{"aria-label":"Describe your workflow",className:"flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground resize-none h-[22px] min-h-[22px] max-h-[200px] py-0 leading-[22px]",disabled:o,onBlur:te,onChange:W=>{i(W.target.value),W.target.style.height="auto",W.target.style.height=`${W.target.scrollHeight}px`},onFocus:G,onKeyDown:W=>{W.key==="Enter"&&!W.shiftKey?(W.preventDefault(),O(W)):W.key==="Escape"&&(W.preventDefault(),i(""),l(!1),d(!1),c.current?.blur())},placeholder:s?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Xt("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),Ns("div",{className:"relative size-8 shrink-0 self-end",children:[Xt(E,{"aria-label":"Focus prompt input (\u2318K)",className:"absolute inset-0 h-8 px-0 text-xs text-muted-foreground hover:bg-transparent transition-[opacity,filter] ease-out",onClick:()=>c.current?.focus(),style:!r.trim()&&!o&&!s?{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"}:{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"},type:"button",variant:"ghost",children:Ns("kbd",{"aria-hidden":"true",className:"pointer-events-none inline-flex h-5 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium text-muted-foreground opacity-100",children:[Xt("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Xt(E,{"aria-label":o?"Generating workflow...":"Generate workflow",className:"size-8 transition-[opacity,filter] ease-out shrink-0",disabled:!r.trim()||o,size:"sm",style:!r.trim()&&!o&&!s?{opacity:0,filter:"blur(2px)",pointerEvents:"none",visibility:"hidden"}:{opacity:1,filter:"blur(0px)",pointerEvents:"auto",visibility:"visible"},type:"submit",children:Xt(hg,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as vy}from"@xyflow/react";import{useAtom as Ze,useAtomValue as oc,useSetAtom as qt}from"jotai";import{Check as ya,ChevronDown as hy,Copy as by,Download as wy,Globe as nc,Loader2 as ha,Lock as rc,Play as xy,Plus as ac,Redo2 as sc,Save as Ny,Settings2 as ky,Trash2 as Cy,Undo2 as ic}from"lucide-react";import{nanoid as Ty}from"nanoid";import{useRouter as Sy}from"next/navigation";import{useEffect as zs,useRef as Ay,useState as Fs}from"react";import{toast as dt}from"sonner";import{Panel as Ng}from"@xyflow/react";import{jsx as kg}from"react/jsx-runtime";var ia=({className:e,...t})=>kg(Ng,{className:N("m-4 rounded-md border bg-card p-1",e),...t});var ks="https://vercel.new/workflow-builder",hS=`[](${ks})`;import{jsx as ir,jsxs as yd}from"react/jsx-runtime";function vd(){return ir(E,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:yd("a",{href:ks,rel:"noopener noreferrer",target:"_blank",children:[yd("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[ir("title",{children:"Vercel logomark"}),ir("path",{d:"m38 0 38 66H0z"})]}),ir("span",{className:"text-sm sm:hidden",children:"Deploy"}),ir("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as hd}from"react/jsx-runtime";function bd({className:e}){return hd("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:hd("path",{d:"M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"})})}function wd(e){if(e>=1e6){let t=(e/1e6).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e6)}M`:`${t}M`}if(e>=1e3){let t=(e/1e3).toFixed(1);return t.endsWith(".0")?`${Math.floor(e/1e3)}k`:`${t}k`}return e.toString()}import{createContext as Cg,useContext as Tg}from"react";import{jsx as PS}from"react/jsx-runtime";var Sg=Cg(null);function xd(){return Tg(Sg)}import{jsx as Nd,jsxs as kd}from"react/jsx-runtime";var Ag="https://github.com/vercel-labs/workflow-builder-template";function Cd(){let e=xd();return Nd(E,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:kd("a",{className:"flex items-center",href:Ag,rel:"noopener noreferrer",target:"_blank",children:[Nd(bd,{className:"size-4.5"}),e!==null&&kd("span",{className:"hidden text-sm sm:inline",children:[wd(e)," stars"]})]})})}import{useAtom as Qt,useAtomValue as Td,useSetAtom as lr}from"jotai";import{Code as Sd,Copy as Ad,Eraser as Cs,Eye as Ig,EyeOff as Pg,FileCode as Id,Play as Pd,RefreshCw as Ed,Settings2 as Dd,Trash2 as Ts}from"lucide-react";import{useCallback as Rn,useEffect as Eg,useRef as Dg,useState as Rg}from"react";import{toast as On}from"sonner";import{Fragment as Ss,jsx as ee,jsxs as se}from"react/jsx-runtime";var Og={"Database Query":"database"},Lg=/[^a-zA-Z0-9\s]/g,Mg=/\s+/;function Wg(e){return e.data.type==="trigger"?e.data.config?.triggerType==="Schedule"?"vercel.json":`app/api${e.data.config?.webhookPath||"/webhook"}/route.ts`:`steps/${(e.data.config?.actionType||"action").toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")}-step.ts`}function la({overlayId:e}){let{push:t,closeAll:o}=oe(),[n]=Qt(Ce),[r]=Qt(_e),[i]=Qt(re),[a]=Qt(ce),[l]=Qt(kt),[s]=Qt(Ue),[d,c]=Qt(gt),u=Td(no),f=lr(ao),v=lr(so),C=lr(io),h=lr(Ir),y=lr(Zo),[m,b]=Qt(oo),[g,S]=Qt(Ht),[D,I]=Rg(!1),x=Dg(null),p=i.find(V=>V.id===n),w=a.find(V=>V.id===r),G=Td(ft);Eg(()=>{if(!(p&&u))return;let V=p.data.config?.actionType,Ae=p.data.config?.integrationId;if(!(V&&Ae))return;let Ye=ge(V)?.integration||Og[V];if(!Ye)return;let ot=G.filter(Dt=>Dt.type===Ye);!ot.some(Dt=>Dt.id===Ae)&&ot.length>0&&f({id:p.id,data:{config:{...p.data.config,integrationId:ot[0].id}}})},[p,G,u,f]);let te=Rn((V,Ae)=>{p&&f({id:p.id,data:{config:{...p.data.config,[V]:Ae}}})},[p,f]),O=Rn(V=>{p&&f({id:p.id,data:{label:V}})},[p,f]),W=Rn(V=>{p&&f({id:p.id,data:{description:V}})},[p,f]),$=Rn(()=>{p&&f({id:p.id,data:{enabled:p.data.enabled===!1}})},[p,f]),T=Rn(()=>{t(Pe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{p&&(v(p.id),o())}})},[p,v,o,t]),H=Rn(()=>{p&&(navigator.clipboard.writeText(Nn(p,s)),On.success("Code copied to clipboard"))},[p]),X=async()=>{x.current&&(I(!0),await x.current(),I(!1))},z=()=>{t(Pe,{title:"Delete All Runs",message:"Are you sure you want to delete all workflow runs? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:async()=>{if(s)try{await j.workflow.deleteExecutions(s),h(),x.current&&await x.current(),On.success("All runs deleted")}catch(V){console.error("Failed to delete runs:",V),On.error("Failed to delete runs")}}})},q=p&&(p.data.type!=="trigger"||p.data.config?.triggerType!=="Manual")&&p.data.config?.actionType!=="Condition",A=()=>{if(!p)switch(g==="properties"||g==="code"||g==="runs"&&u?g:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(g){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},B=async V=>{if(c(V),s)try{await j.workflow.update(s,{name:V})}catch(Ae){console.error("Failed to update workflow name:",Ae)}},k=()=>{t(Pe,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{y()}})},R=()=>{t(Pe,{title:"Delete Workflow",message:`Are you sure you want to delete "${d}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(s)try{await j.workflow.delete(s),o(),On.success("Workflow deleted successfully"),window.location.href="/"}catch(V){console.error("Failed to delete workflow:",V),On.error("Failed to delete workflow. Please try again.")}}})},_=(()=>{let Ae=`${d.replace(Lg,"").split(Mg).map((Ye,ot)=>ot===0?Ye.toLowerCase():Ye.charAt(0).toUpperCase()+Ye.slice(1).toLowerCase()).join("")}Workflow`,{code:tt}=gr(i,a,{functionName:Ae});return tt})(),ne=()=>{navigator.clipboard.writeText(_),On.success("Code copied to clipboard")},le=()=>{r&&t(Pe,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{C(r),o()}})};if(w&&!p)return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(on,{overlayId:e,title:"Connection"}),se("div",{className:"flex-1 space-y-4 overflow-y-auto px-6 pt-4 pb-6",children:[se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"edge-id",children:"Connection ID"}),ee(ae,{disabled:!0,id:"edge-id",value:w.id})]}),se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"edge-source",children:"Source"}),ee(ae,{disabled:!0,id:"edge-source",value:w.source})]}),se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"edge-target",children:"Target"}),ee(ae,{disabled:!0,id:"edge-target",value:w.target})]}),u&&ee("div",{className:"pt-2",children:se(E,{onClick:le,variant:"ghost",children:[ee(Ts,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!p){let V=g==="properties"||g==="code"||g==="runs"&&u?g:"properties";return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(on,{overlayId:e,title:A()}),se("div",{className:"flex-1 overflow-y-auto",children:[V==="properties"&&se("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"workflow-name",children:"Workflow Name"}),ee(ae,{disabled:!u,id:"workflow-name",onChange:Ae=>B(Ae.target.value),value:d})]}),se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"workflow-id",children:"Workflow ID"}),ee(ae,{disabled:!0,id:"workflow-id",value:s||"Not saved"})]}),!u&&ee("div",{className:"rounded-lg border border-muted bg-muted/30 p-3",children:ee("p",{className:"text-muted-foreground text-sm",children:"You are viewing a public workflow. Duplicate it to make changes."})}),u&&se("div",{className:"flex items-center gap-2 pt-2",children:[se(E,{onClick:k,variant:"ghost",children:[ee(Cs,{className:"mr-2 size-4"}),"Clear"]}),se(E,{onClick:R,variant:"ghost",children:[ee(Ts,{className:"mr-2 size-4"}),"Delete"]})]})]}),V==="code"&&se("div",{className:"flex flex-col",children:[se("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[se("div",{className:"flex items-center gap-2",children:[ee(Id,{className:"size-3.5 text-muted-foreground"}),ee("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),se(E,{className:"h-7 text-xs",onClick:ne,size:"sm",variant:"ghost",children:[ee(Ad,{className:"mr-1 size-3"}),"Copy"]})]}),ee("div",{className:"h-[400px]",children:ee(yt,{defaultLanguage:"typescript",height:"100%",options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,wordWrap:"on"},value:_})})]}),V==="runs"&&u&&se("div",{className:"flex h-full flex-col",children:[se("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[ee(E,{className:"text-muted-foreground",disabled:D,onClick:X,size:"icon",variant:"ghost",children:ee(Ed,{className:`size-4 ${D?"animate-spin":""}`})}),ee(E,{className:"text-muted-foreground",onClick:z,size:"icon",variant:"ghost",children:ee(Cs,{className:"size-4"})})]}),ee("div",{className:"flex-1 overflow-y-auto p-4",children:ee(Cn,{isActive:V==="runs",onRefreshRef:x})})]})]}),se("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("properties"),type:"button",children:[ee(Dd,{className:"size-5"}),"Workflow"]}),se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("code"),type:"button",children:[ee(Sd,{className:"size-5"}),"Code"]}),u&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${V==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("runs"),type:"button",children:[ee(Pd,{className:"size-5"}),"Runs"]})]})]})}return se("div",{className:"flex h-full max-h-[80vh] flex-col",children:[ee(on,{overlayId:e,title:A()}),se("div",{className:"flex-1 overflow-y-auto",children:[g==="properties"&&se("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[p.data.type==="action"&&!p.data.config?.actionType&&u&&ee(Qr,{disabled:l,isNewlyCreated:p?.id===m,onSelectAction:V=>{te("actionType",V),p?.id===m&&b(null)}}),p.data.type==="trigger"&&ee(Zr,{config:p.data.config||{},disabled:l||!u,onUpdateConfig:te,workflowId:s??void 0}),p.data.type==="action"&&p.data.config?.actionType!==void 0&&ee(qr,{config:p.data.config||{},disabled:l||!u,isOwner:u,onUpdateConfig:te}),(p.data.type!=="action"||p.data.config?.actionType!==void 0)&&se(Ss,{children:[se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"label",children:"Label"}),ee(ae,{disabled:l||!u,id:"label",onChange:V=>O(V.target.value),value:p.data.label})]}),se("div",{className:"space-y-2",children:[ee(M,{htmlFor:"description",children:"Description"}),ee(ae,{disabled:l||!u,id:"description",onChange:V=>W(V.target.value),placeholder:"Optional description",value:p.data.description||""})]})]}),u&&se("div",{className:"flex items-center gap-2 pt-2",children:[p.data.type==="action"&&ee(E,{className:"text-muted-foreground",onClick:$,size:"sm",variant:"ghost",children:p.data.enabled===!1?se(Ss,{children:[ee(Pg,{className:"mr-2 size-4"}),"Disabled"]}):se(Ss,{children:[ee(Ig,{className:"mr-2 size-4"}),"Enabled"]})}),se(E,{className:"text-muted-foreground",onClick:T,size:"sm",variant:"ghost",children:[ee(Ts,{className:"mr-2 size-4"}),"Delete"]})]})]}),q&&se("div",{className:`flex flex-col ${g==="code"?"":"invisible absolute -z-10"}`,children:[se("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[se("div",{className:"flex items-center gap-2",children:[ee(Id,{className:"size-3.5 text-muted-foreground"}),ee("code",{className:"text-muted-foreground text-xs",children:Wg(p)})]}),se(E,{className:"text-muted-foreground",onClick:H,size:"sm",variant:"ghost",children:[ee(Ad,{className:"mr-2 size-4"}),"Copy"]})]}),ee("div",{className:"h-[400px]",children:ee(yt,{height:"100%",language:p.data.type==="trigger"&&p.data.config?.triggerType==="Schedule"?"json":"typescript",options:{readOnly:!0,minimap:{enabled:!1},scrollBeyondLastLine:!1,fontSize:13,lineNumbers:"on",folding:!1,wordWrap:"off",padding:{top:16,bottom:16}},value:Nn(p,s)})})]}),g==="runs"&&u&&se("div",{className:"flex h-full flex-col",children:[se("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[se(E,{className:"text-muted-foreground",disabled:D,onClick:X,size:"sm",variant:"ghost",children:[ee(Ed,{className:`mr-2 size-4 ${D?"animate-spin":""}`}),"Refresh"]}),se(E,{className:"text-muted-foreground",onClick:z,size:"sm",variant:"ghost",children:[ee(Cs,{className:"mr-2 size-4"}),"Clear All"]})]}),ee("div",{className:"flex-1 overflow-y-auto p-4",children:ee(Cn,{isActive:g==="runs",onRefreshRef:x})})]})]}),se("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("properties"),type:"button",children:[ee(Dd,{className:"size-5"}),"Properties"]}),q&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("code"),type:"button",children:[ee(Sd,{className:"size-5"}),"Code"]}),u&&se("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${g==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>S("runs"),type:"button",children:[ee(Pd,{className:"size-5"}),"Runs"]})]})]})}import{Download as Bg,FlaskConical as Vg}from"lucide-react";import{cva as Fg}from"class-variance-authority";import{jsx as As}from"react/jsx-runtime";var zg=Fg("relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",{variants:{variant:{default:"bg-card text-card-foreground",destructive:"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"}},defaultVariants:{variant:"default"}});function Rd({className:e,variant:t,...o}){return As("div",{"data-slot":"alert",role:"alert",className:N(zg({variant:t}),e),...o})}function Od({className:e,...t}){return As("div",{"data-slot":"alert-title",className:N("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function Ld({className:e,...t}){return As("div",{"data-slot":"alert-description",className:N("text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",e),...t})}import{jsx as Ln,jsxs as da}from"react/jsx-runtime";function Md({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=oe();return da(Re,{actions:[{label:"Cancel",variant:"outline",onClick:n},{label:o?"Exporting...":"Export Project",onClick:()=>{n(),t()},loading:o}],overlayId:e,title:"Export Workflow as Code",children:[da("div",{className:"flex items-center gap-2 text-muted-foreground",children:[Ln(Bg,{className:"size-5"}),Ln("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),Ln("p",{className:"mt-4 text-muted-foreground text-sm",children:"This will generate a complete Next.js project containing your workflow code. Once exported, you can run your workflow outside of the Workflow Builder, deploy it to Vercel, or integrate it into your existing applications."}),da(Rd,{className:"mt-4",children:[Ln(Vg,{className:"size-4"}),Ln(Od,{children:"Experimental Feature"}),da(Ld,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",Ln("a",{className:"font-medium text-foreground underline underline-offset-4 hover:text-primary",href:"https://github.com/vercel-labs/workflow-builder-template/issues",rel:"noopener noreferrer",target:"_blank",children:"report them on GitHub"}),"."]})]})]})}import{Globe as Hg}from"lucide-react";import{jsx as ho,jsxs as ca}from"react/jsx-runtime";function Wd({overlayId:e,onConfirm:t}){let{closeAll:o}=oe();return ca(Re,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[ca("div",{className:"flex items-center gap-2 text-muted-foreground",children:[ho(Hg,{className:"size-5 shrink-0"}),ho("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),ca("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[ho("li",{children:"View the workflow structure and steps"}),ho("li",{children:"See action types and configurations"}),ho("li",{children:"Duplicate the workflow to their own account"})]}),ho("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),ca("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[ho("li",{children:"Your integration credentials (API keys, tokens)"}),ho("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as Fd,useSetAtom as Gg}from"jotai";import{AlertTriangle as $g}from"lucide-react";import{jsx as Qe,jsxs as pt}from"react/jsx-runtime";function zd({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:i}=oe(),a=Gg(Ot),l=Gt(),s=Fd(jt),d=Fd(Po),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:f}=t,v=c.length+u.length+f.length,C=(b,g)=>{o(b,g),l?r(la,{}):i()},h=b=>{r(uo,{type:b,onSuccess:()=>{a(g=>g+1)}})},y=b=>{s?.integrationType===b&&d?.enabled&&d?.isVercelUser&&s?r(s.ConsentOverlay,{onConsent:()=>{a(D=>D+1)},onManualEntry:()=>h(b)}):h(b)};return pt(Re,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{i(),n()}},{label:"Cancel",onClick:i}],overlayId:e,title:`Workflow Issues (${v})`,children:[pt("div",{className:"flex items-center gap-2 text-orange-500",children:[Qe($g,{className:"size-5"}),Qe("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),pt("div",{className:"mt-4 space-y-4",children:[f.length>0&&pt("div",{className:"space-y-1",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),f.map(b=>pt("div",{className:"flex items-center gap-3 py-1",children:[Qe(Wt,{className:"size-4 shrink-0",integration:b.integrationType}),pt("p",{className:"min-w-0 flex-1 text-sm",children:[Qe("span",{className:"font-medium",children:b.integrationLabel}),pt("span",{className:"text-muted-foreground",children:[" \u2014 ",b.nodeNames.length>3?`${b.nodeNames.slice(0,3).join(", ")} +${b.nodeNames.length-3} more`:b.nodeNames.join(", ")]})]}),Qe(E,{className:"shrink-0",onClick:()=>y(b.integrationType),size:"sm",variant:"outline",children:"Add"})]},b.integrationType))]}),c.length>0&&pt("div",{className:"space-y-2",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(b=>pt("div",{children:[Qe("p",{className:"font-medium text-sm",children:b.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:b.brokenReferences.map((g,S)=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[pt("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[Qe("span",{className:"font-mono",children:g.displayText})," in ",g.fieldLabel]}),Qe(E,{className:"shrink-0",onClick:()=>C(b.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${b.nodeId}-${g.fieldKey}-${S}`))})]},b.nodeId))]}),u.length>0&&pt("div",{className:"space-y-2",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Required Fields"}),u.map(b=>pt("div",{children:[Qe("p",{className:"font-medium text-sm",children:b.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:b.missingFields.map(g=>pt("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[Qe("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:g.fieldLabel}),Qe(E,{className:"shrink-0",onClick:()=>C(b.nodeId,g.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${b.nodeId}-${g.fieldKey}`))})]},b.nodeId))]})]})]})}import{jsx as Is,jsxs as _g}from"react/jsx-runtime";function Bd({className:e}){return _g("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[Is("path",{className:"fill-foreground",d:"M125.776 0C120.929 1.64945e-05 117 3.9291 117 8.77539V61.4248C117 66.2711 120.929 70.2002 125.776 70.2002H160.875L161.253 70.2051C169.032 70.4023 175.301 76.6734 175.495 84.4531L175.5 84.8252V143.325C175.5 148.171 179.429 152.101 184.276 152.101H219.375L219.753 152.105C227.53 152.303 233.798 158.571 233.995 166.348L234 166.726V225.225C234 230.071 237.929 234 242.776 234H295.425C300.271 234 304.2 230.071 304.2 225.225V172.575C304.2 167.729 300.271 163.8 295.425 163.8H260.25C252.334 163.76 245.905 157.43 245.705 149.553L245.7 149.176V90.6758C245.7 85.8295 241.771 81.9004 236.925 81.9004H201.825C193.874 81.9004 187.405 75.5551 187.205 67.6523L187.2 67.2754V8.77539C187.2 3.9291 183.271 1.64951e-05 178.425 0H125.776Z"}),Is("path",{className:"fill-foreground",d:"M67.2755 81.9004C62.4293 81.9004 58.5002 85.8295 58.5002 90.6758V143.325C58.5004 148.171 62.4294 152.101 67.2755 152.101H102.375L102.753 152.105C110.53 152.303 116.798 158.571 116.995 166.348L117 166.726V225.225C117 230.071 120.929 234 125.776 234H178.425C183.271 234 187.2 230.071 187.2 225.225V172.575C187.2 167.729 183.271 163.8 178.425 163.8H143.25C135.334 163.76 128.905 157.43 128.705 149.553L128.7 149.176V90.6758C128.7 85.8295 124.771 81.9004 119.925 81.9004H67.2755Z"}),Is("path",{className:"fill-foreground",d:"M8.77454 163.8C3.92844 163.8 0.00012207 167.729 0.00012207 172.575V225.225C0.00012207 230.071 3.92844 234 8.77454 234H61.4249C66.2712 234 70.2003 230.071 70.2003 225.225V172.575C70.2003 167.729 66.2712 163.8 61.4249 163.8H8.77454Z"})]})}import{Key as dy,LogOut as cy,Moon as uy,Plug as my,Settings as py,Sun as fy}from"lucide-react";import{useTheme as gy}from"next-themes";import yy from"next/link";import{useEffect as Zd,useState as ec}from"react";import{Copy as Ug,Key as Kg,Trash2 as qg}from"lucide-react";import{useCallback as jg,useEffect as Jg,useState as Mn}from"react";import{toast as Wn}from"sonner";import{jsx as Ve,jsxs as Et}from"react/jsx-runtime";function Yg({overlayId:e,onCreated:t}){let{pop:o}=oe(),[n,r]=Mn(""),[i,a]=Mn(!1);return Et(Re,{actions:[{label:"Create",onClick:async()=>{a(!0);try{let s=await fetch("/api/api-keys",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:n||null})});if(!s.ok){let c=await s.json();throw new Error(c.error||"Failed to create API key")}let d=await s.json();t(d),Wn.success("API key created successfully"),o()}catch(s){console.error("Failed to create API key:",s),Wn.error(s instanceof Error?s.message:"Failed to create API key")}finally{a(!1)}},loading:i}],overlayId:e,title:"Create API Key",children:[Ve("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),Et("div",{className:"space-y-2",children:[Ve(M,{htmlFor:"key-name",children:"Label (optional)"}),Ve(ae,{id:"key-name",onChange:s=>r(s.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function Vd({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Mn(!0),[i,a]=Mn([]),[l,s]=Mn(null),[d,c]=Mn(null),u=jg(async()=>{r(!0);try{let m=await fetch("/api/api-keys");if(!m.ok)throw new Error("Failed to load API keys");let b=await m.json();a(b)}catch(m){console.error("Failed to load API keys:",m),Wn.error("Failed to load API keys")}finally{r(!1)}},[]);Jg(()=>{u()},[u]);let f=m=>{s(m.key??null),a(b=>[m,...b])},v=async m=>{c(m);try{if(!(await fetch(`/api/api-keys/${m}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(g=>g.filter(S=>S.id!==m)),Wn.success("API key deleted")}catch(b){console.error("Failed to delete API key:",b),Wn.error("Failed to delete API key")}finally{c(null)}},C=m=>{t(Pe,{title:"Delete API Key",message:"Are you sure you want to delete this API key? Any webhooks using this key will stop working immediately.",confirmLabel:"Delete",confirmVariant:"destructive",destructive:!0,onConfirm:()=>v(m)})},h=m=>{navigator.clipboard.writeText(m),Wn.success("Copied to clipboard")},y=m=>new Date(m).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return Et(Re,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(Yg,{onCreated:f})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Ve("div",{className:"flex items-center justify-center py-8",children:Ve(St,{})}):Et("div",{className:"space-y-4",children:[l&&Et("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Ve("p",{className:"mb-2 font-medium text-sm text-yellow-600 dark:text-yellow-400",children:"Copy your API key now. You won't be able to see it again!"}),Et("div",{className:"flex items-center gap-2",children:[Ve("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:l}),Ve(E,{onClick:()=>h(l),size:"sm",variant:"outline",children:Ve(Ug,{className:"size-4"})})]}),Ve(E,{className:"mt-2",onClick:()=>s(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),i.length===0?Et("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Ve(Kg,{className:"mx-auto mb-2 size-8 opacity-50"}),Ve("p",{children:"No API keys yet"}),Ve("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Ve("div",{className:"space-y-2",children:i.map(m=>Et("div",{className:"flex items-center justify-between rounded-md border p-3",children:[Et("div",{className:"min-w-0 flex-1",children:[Et("div",{className:"flex items-center gap-2",children:[Et("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[m.keyPrefix,"..."]}),m.name&&Ve("span",{className:"truncate text-sm",children:m.name})]}),Et("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",y(m.createdAt),m.lastUsedAt&&` \xB7 Last used ${y(m.lastUsedAt)}`]})]}),Ve(E,{disabled:d===m.id,onClick:()=>C(m.id),size:"sm",variant:"ghost",children:d===m.id?Ve(St,{className:"size-4"}):Ve(qg,{className:"size-4 text-destructive"})})]},m.id))})]})]})}import{useSetAtom as ny}from"jotai";import{Search as ry}from"lucide-react";import{useCallback as Ds,useEffect as ay,useRef as sy,useState as Gd}from"react";import{Pencil as Xg,Trash2 as Qg}from"lucide-react";import{useCallback as Zg,useEffect as ey,useMemo as ty,useState as Ps}from"react";import{toast as ua}from"sonner";import{jsx as $e,jsxs as Es}from"react/jsx-runtime";var oy={database:"Database"};function Hd({onIntegrationChange:e,filter:t=""}){let{push:o}=oe(),[n,r]=Ps([]),[i,a]=Ps(!0),[l,s]=Ps(null),d=Zg(async()=>{try{a(!0);let h=await j.integration.getAll();r(h)}catch(h){console.error("Failed to load integrations:",h),ua.error("Failed to load integrations")}finally{a(!1)}},[]);ey(()=>{d()},[d]);let c=ty(()=>{let h=to(),y=t.toLowerCase();return n.map(m=>({...m,label:h[m.type]||oy[m.type]||m.type})).filter(m=>t?m.label.toLowerCase().includes(y)||m.name.toLowerCase().includes(y)||m.type.toLowerCase().includes(y):!0).sort((m,b)=>{let g=m.label.localeCompare(b.label);return g!==0?g:m.name.localeCompare(b.name)})},[n,t]),u=h=>{o(_r,{integration:h,onSuccess:()=>{d(),e?.()},onDelete:()=>{d(),e?.()}})},f=h=>{o(qa,{integration:h,onSuccess:()=>{d(),e?.()}})},v=async h=>{try{s(h);let y=await j.integration.testConnection(h);y.status==="success"?ua.success(y.message||"Connection successful"):ua.error(y.message||"Connection test failed")}catch(y){console.error("Connection test failed:",y),ua.error(y instanceof Error?y.message:"Connection test failed")}finally{s(null)}};return i?$e("div",{className:"flex items-center justify-center py-8",children:$e(St,{})}):$e("div",{className:"space-y-1",children:n.length===0?$e("div",{className:"py-8 text-center",children:$e("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?$e("div",{className:"py-8 text-center",children:$e("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):$e("div",{className:"space-y-1",children:c.map(h=>Es("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[Es("div",{className:"flex items-center gap-2",children:[$e(Wt,{className:"size-4",integration:h.type==="ai-gateway"?"vercel":h.type}),$e("span",{className:"font-medium text-sm",children:h.label}),$e("span",{className:"text-muted-foreground text-sm",children:h.name})]}),Es("div",{className:"flex items-center gap-1",children:[$e(E,{className:"h-7 px-2",disabled:l===h.id,onClick:()=>v(h.id),size:"sm",variant:"outline",children:l===h.id?$e(St,{className:"size-3"}):$e("span",{className:"text-xs",children:"Test"})}),$e(E,{className:"size-7",onClick:()=>u(h),size:"icon",variant:"outline",children:$e(Xg,{className:"size-3"})}),$e(E,{className:"size-7",onClick:()=>f(h),size:"icon",variant:"outline",children:$e(Qg,{className:"size-3"})})]})]},h.id))})})}import{jsx as Vo,jsxs as Rs}from"react/jsx-runtime";function $d({overlayId:e}){let{push:t,closeAll:o}=oe(),[n,r]=Gd(!0),[i,a]=Gd(""),l=ny(Ot),s=sy(!1),d=Ds(async()=>{r(!0);try{await new Promise(v=>setTimeout(v,0))}finally{r(!1)}},[]);ay(()=>{d(),s.current=!1,a("")},[d]);let c=Ds(()=>{s.current&&l(v=>v+1),o()},[o,l]),u=Ds(()=>{s.current=!0},[]);return Rs(Re,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(el,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[Vo("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?Vo("div",{className:"flex items-center justify-center py-8",children:Vo(St,{})}):Rs("div",{className:"space-y-4",children:[Rs("div",{className:"relative",children:[Vo(ry,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Vo(ae,{className:"pl-9",onChange:v=>a(v.target.value),placeholder:"Filter connections...",value:i})]}),Vo("div",{className:"max-h-[300px] overflow-y-auto",children:Vo(Hd,{filter:i,onIntegrationChange:u})})]})]})}import{useCallback as qd,useEffect as iy,useState as fa}from"react";import{toast as jd}from"sonner";import{jsx as pa}from"react/jsx-runtime";function ma({className:e,...t}){return pa("div",{"data-slot":"card",className:N("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function _d({className:e,...t}){return pa("div",{"data-slot":"card-title",className:N("leading-none font-semibold",e),...t})}function Ud({className:e,...t}){return pa("div",{"data-slot":"card-description",className:N("text-muted-foreground text-sm",e),...t})}function Os({className:e,...t}){return pa("div",{"data-slot":"card-content",className:N("px-6",e),...t})}import{jsx as dr,jsxs as Ls}from"react/jsx-runtime";function Kd({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return dr(ma,{className:"border-0 py-0 shadow-none",children:Ls(Os,{className:"space-y-4 p-0",children:[Ls("div",{className:"space-y-2",children:[dr(M,{className:"ml-1",htmlFor:"accountName",children:"Name"}),dr(ae,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),Ls("div",{className:"space-y-2",children:[dr(M,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),dr(ae,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as ga,jsxs as ly}from"react/jsx-runtime";function Jd({overlayId:e}){let{closeAll:t}=oe(),[o,n]=fa(!0),[r,i]=fa(!1),[a,l]=fa(""),[s,d]=fa(""),c=qd(async()=>{try{let v=await j.user.get();l(v.name||""),d(v.email||"")}catch(v){console.error("Failed to load account:",v)}},[]),u=qd(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return iy(()=>{u()},[u]),ly(Re,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{i(!0),await j.user.update({name:a,email:s}),await c(),jd.success("Settings saved"),t()}catch(v){console.error("Failed to save account:",v),jd.error("Failed to save settings")}finally{i(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[ga("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?ga("div",{className:"flex items-center justify-center py-8",children:ga(St,{})}):ga(Kd,{accountEmail:s,accountName:a,onEmailChange:d,onNameChange:l})]})}import{Avatar as Ms}from"radix-ui";import{jsx as Ws}from"react/jsx-runtime";function Yd({className:e,...t}){return Ws(Ms.Root,{"data-slot":"avatar",className:N("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function Xd({className:e,...t}){return Ws(Ms.Image,{"data-slot":"avatar-image",className:N("aspect-square size-full",e),...t})}function Qd({className:e,...t}){return Ws(Ms.Fallback,{"data-slot":"avatar-fallback",className:N("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as ke,jsxs as Ft}from"react/jsx-runtime";var tc=()=>{let{data:e,isPending:t}=Sn(),{theme:o,setTheme:n}=gy(),{open:r}=oe(),[i,a]=ec(null),[l,s]=ec(!1);Zd(()=>{s(!0)},[]),Zd(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&j.user.get().then(v=>a(v.providerId)).catch(()=>a(null))},[e?.user]);let d=async()=>{await Kl()},c=i==="vercel"||i==="github"||i==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(v=>v[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!l?ke("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?ke("div",{className:"flex items-center gap-2",children:ke(E,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:ke(yy,{href:"/auth/sign-in",children:"Sign In"})})}):Ft(Ro,{children:[ke(Oo,{asChild:!0,children:ke(E,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ft(Yd,{className:"h-9 w-9",children:[ke(Xd,{alt:e?.user?.name||"",src:e?.user?.image||""}),ke(Qd,{children:u()})]})})}),Ft(Lo,{align:"end",className:"w-56",children:[ke(wl,{children:Ft("div",{className:"flex flex-col space-y-1",children:[ke("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),ke("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),ke(Qn,{}),!c&&Ft(xt,{onClick:()=>r(Jd),children:[ke(py,{className:"size-4"}),ke("span",{children:"Settings"})]}),Ft(xt,{onClick:()=>r($d),children:[ke(my,{className:"size-4"}),ke("span",{children:"Connections"})]}),Ft(xt,{onClick:()=>r(Vd),children:[ke(dy,{className:"size-4"}),ke("span",{children:"API Keys"})]}),Ft(xl,{children:[Ft(Nl,{children:[ke(fy,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),ke(uy,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),ke("span",{children:"Theme"})]}),ke(kl,{children:Ft(bl,{onValueChange:n,value:o,children:[ke(Xr,{value:"light",children:"Light"}),ke(Xr,{value:"dark",children:"Dark"}),ke(Xr,{value:"system",children:"System"})]})})]}),ke(Qn,{}),Ft(xt,{onClick:d,children:[ke(cy,{className:"size-4"}),ke("span",{children:"Logout"})]})]})]})};import{Fragment as va,jsx as J,jsxs as De}from"react/jsx-runtime";function lc(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var Iy={"Database Query":"database"},Py={database:"Database"};function Ey(e){if(typeof e!="string")return[];let t=/\{\{@([^:]+):([^}]+)\}\}/g,o=e.matchAll(t);return Array.from(o).map(n=>({nodeId:n[1],displayText:n[2]}))}function uc(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let i=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Ey(r);for(let l of a)o.push({field:i,...l})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...uc(r,i))}return o}function Dy(e){let t=new Set(e.map(n=>n.id)),o=[];for(let n of e){if(n.data.enabled===!1)continue;let r=n.data.config;if(!r||typeof r!="object")continue;let a=uc(r).filter(l=>!t.has(l.nodeId));if(a.length>0){let l=r.actionType,s=l?ge(l):void 0,d=s?Aa(s.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||s?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=d.find(f=>f.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function Ry(e){return e==null||typeof e=="string"&&e.trim()===""}function Oy(e,t){return e.showWhen?t[e.showWhen.field]===e.showWhen.equals:!0}function Ly(e){if(e.data.enabled===!1)return null;let t=e.data.config,o=t?.actionType;if(!o)return null;let n=ge(o);if(!n)return null;let i=Aa(n.configFields).filter(a=>a.required&&Oy(a,t||{})&&Ry(t?.[a.key])).map(a=>({fieldKey:a.key,fieldLabel:a.label}));return i.length===0?null:{nodeId:e.id,nodeLabel:e.data.label||n.label||"Unnamed Step",missingFields:i}}function My(e){return e.map(Ly).filter(t=>t!==null)}function Wy(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,i=to();for(let a of e){if(a.data.enabled===!1)continue;let l=a.data.config?.actionType;if(!l)continue;let d=ge(l)?.integration||Iy[l];if(!d||!Ko(d))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(d)){let f=r.get(d)||[],v=ge(l);f.push(a.data.label||v?.label||l),r.set(d,f)}}return Array.from(r.entries()).map(([a,l])=>({integrationType:a,integrationLabel:i[a]||Py[a]||a,nodeNames:l}))}async function Fy({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:i}){lc(t,o,"idle");for(let a of t)a.data.type==="trigger"&&o({id:a.id,data:{status:"running"}});try{let a=await fetch(`/api/workflow/${e}/execute`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({input:{}})});if(!a.ok)throw new Error("Failed to execute workflow");let l=await a.json();i(l.executionId);let s=setInterval(async()=>{try{let d=await j.workflow.getExecutionStatus(l.executionId);for(let c of d.nodeStatuses)o({id:c.nodeId,data:{status:c.status}});d.status!=="running"&&(n.current&&(clearInterval(n.current),n.current=null),r(!1))}catch(d){console.error("Failed to poll execution status:",d)}},500);n.current=s}catch(a){console.error("Failed to execute workflow:",a),dt.error(a instanceof Error?a.message:"Failed to execute workflow"),lc(t,o,"error"),r(!1)}}function zy({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:i,setIsSaving:a,setHasUnsavedChanges:l,setActiveTab:s,setNodes:d,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:f,userIntegrations:v}){let{open:C}=oe(),h=Ay(null);zs(()=>()=>{h.current&&clearInterval(h.current)},[]);let y=async()=>{if(e){a(!0);try{await j.workflow.update(e,{nodes:t,edges:o}),l(!1)}catch(S){console.error("Failed to save workflow:",S),dt.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},m=async()=>{if(!e){dt.error("Please save the workflow before executing");return}s("runs"),d(t.map(S=>({...S,selected:!1}))),c(o.map(S=>({...S,selected:!1}))),u(null),i(!0),await Fy({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:h,setIsExecuting:i,setSelectedExecutionId:f})},b=(S,D)=>{u(S),s("properties"),D&&setTimeout(()=>{let I=document.getElementById(D);I&&(I.focus(),I.scrollIntoView({behavior:"smooth",block:"center"}))},100)};return{handleSave:y,handleExecute:async()=>{if(r)return;let S=Dy(t),D=My(t),I=Wy(t,v);if(S.length>0||D.length>0||I.length>0){C(zd,{issues:{brokenReferences:S,missingRequiredFields:D,missingIntegrations:I},onGoToStep:b,onRunAnyway:m});return}await m()}}}function By(){let[e,t]=Ze(re),[o,n]=Ze(ce),[r,i]=Ze(si),[a]=Ze(kt),l=qt(Zo),s=qt(ao),[d]=Ze(Ue),[c,u]=Ze(gt),[f,v]=Ze(br),C=oc(no),h=Sy(),[y,m]=Ze(Ar),[b,g]=Ze(rt),S=qt(pi),D=qt(fi),I=qt(Qo),[x]=Ze(gi),[p]=Ze(yi),{data:w}=Sn(),G=qt(Ht),te=qt(Ce),O=qt(ro),W=oc(ft),[$,T]=Ze(Sr),[H,X]=Fs(!1),[z,q]=Fs(!1),[A,B]=Fs([]);return zs(()=>{(async()=>{try{let R=await j.workflow.getAll();B(R)}catch(R){console.error("Failed to load workflows:",R)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:i,isGenerating:a,clearWorkflow:l,updateNodeData:s,currentWorkflowId:d,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:f,setWorkflowVisibility:v,isOwner:C,router:h,isSaving:y,setIsSaving:m,hasUnsavedChanges:b,setHasUnsavedChanges:g,undo:S,redo:D,addNode:I,canUndo:x,canRedo:p,session:w,isDownloading:H,setIsDownloading:X,isDuplicating:z,setIsDuplicating:q,allWorkflows:A,setAllWorkflows:B,setActiveTab:G,setNodes:t,setEdges:n,setSelectedNodeId:te,setSelectedExecutionId:O,userIntegrations:W,triggerExecute:$,setTriggerExecute:T}}function Vy(e){let{open:t}=oe(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:i,updateNodeData:a,isExecuting:l,setIsExecuting:s,setIsSaving:d,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:f,setAllWorkflows:v,setIsDownloading:C,setIsDuplicating:h,setActiveTab:y,setNodes:m,setEdges:b,setSelectedNodeId:g,setSelectedExecutionId:S,userIntegrations:D,triggerExecute:I,setTriggerExecute:x,router:p,session:w}=e,{handleSave:G,handleExecute:te}=zy({currentWorkflowId:o,nodes:r,edges:i,updateNodeData:a,isExecuting:l,setIsExecuting:s,setIsSaving:d,setHasUnsavedChanges:c,setActiveTab:y,setNodes:m,setEdges:b,setSelectedNodeId:g,setSelectedExecutionId:S,userIntegrations:D});return zs(()=>{I&&(x(!1),te())},[I,x,te]),{handleSave:G,handleExecute:te,handleClearWorkflow:()=>{t(Pe,{title:"Clear Workflow",message:"Are you sure you want to clear all nodes and connections? This action cannot be undone.",confirmLabel:"Clear Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:()=>{u()}})},handleDeleteWorkflow:()=>{t(Pe,{title:"Delete Workflow",message:`Are you sure you want to delete "${n}"? This will permanently delete the workflow. This cannot be undone.`,confirmLabel:"Delete Workflow",confirmVariant:"destructive",destructive:!0,onConfirm:async()=>{if(o)try{await j.workflow.delete(o),dt.success("Workflow deleted successfully"),window.location.href="/"}catch(z){console.error("Failed to delete workflow:",z),dt.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){dt.error("Please save the workflow before downloading");return}C(!0),dt.info("Preparing workflow files for download...");try{let z=await j.workflow.download(o);if(!z.success)throw new Error(z.error||"Failed to prepare download");if(!z.files)throw new Error("No files to download");let q=(await import("jszip")).default,A=new q;for(let[_,ne]of Object.entries(z.files))A.file(_,ne);let B=await A.generateAsync({type:"blob"}),k=URL.createObjectURL(B),R=document.createElement("a");R.href=k,R.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(k),dt.success("Workflow downloaded successfully!")}catch(z){dt.error(z instanceof Error?z.message:"Failed to download workflow")}finally{C(!1)}},loadWorkflows:async()=>{try{let z=await j.workflow.getAll();v(z)}catch(z){console.error("Failed to load workflows:",z)}},handleToggleVisibility:async z=>{if(o){if(z==="public"){t(Wd,{onConfirm:async()=>{try{await j.workflow.update(o,{visibility:"public"}),f("public"),dt.success("Workflow is now public")}catch(q){console.error("Failed to update visibility:",q),dt.error("Failed to update visibility. Please try again.")}}});return}try{await j.workflow.update(o,{visibility:z}),f(z),dt.success("Workflow is now private")}catch(q){console.error("Failed to update visibility:",q),dt.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){h(!0);try{w?.user||(await zo.signIn.anonymous(),await new Promise(q=>setTimeout(q,100)));let z=await j.workflow.duplicate(o);dt.success("Workflow duplicated successfully"),p.push(`/workflows/${z.id}`)}catch(z){console.error("Failed to duplicate workflow:",z),dt.error("Failed to duplicate workflow. Please try again.")}finally{h(!1)}}}}}function Hy({workflowId:e,state:t,actions:o}){let{open:n,push:r}=oe(),[i]=Ze(Ce),[a]=Ze(_e),[l]=Ze(re),[s]=Ze(ce),d=qt(so),c=qt(io),{screenToFlowPosition:u}=vy(),f=l.find(m=>m.id===i),v=s.find(m=>m.id===a),C=f||v;if(e&&!t.isOwner||!e)return null;let h=()=>{let b=!!i?"Node":"Connection";r(Pe,{title:`Delete ${b}`,message:`Are you sure you want to delete this ${b.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{i?d(i):a&&c(a)}})},y=()=>{let m=document.querySelector(".react-flow");if(!m)return;let b=m.getBoundingClientRect(),g=b.left+b.width/2,S=b.top+b.height/2,D=u({x:g,y:S}),I=192,x=192;D.x-=I/2,D.y-=x/2;let p=20,w=20,G={...D},te=!0,O=0,W=20;for(;te&&O<W;)te=t.nodes.some(T=>{let H=Math.abs(T.position.x-G.x),X=Math.abs(T.position.y-G.y);return H<w&&X<w}),te&&(G.x+=p,G.y+=p,O+=1);let $={id:Ty(),type:"action",position:G,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode($),t.setSelectedNodeId($.id),t.setActiveTab("properties")};return De(va,{children:[J(Kt,{className:"flex lg:hidden",orientation:"vertical",children:J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:J(ac,{className:"size-4"})})}),De(Kt,{className:"flex lg:hidden",orientation:"vertical",children:[J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(la,{}),size:"icon",title:"Configuration",variant:"secondary",children:J(ky,{className:"size-4"})}),C&&J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:h,size:"icon",title:"Delete",variant:"secondary",children:J(Cy,{className:"size-4"})})]}),J(Kt,{className:"hidden lg:flex",orientation:"horizontal",children:J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:t.isGenerating,onClick:y,size:"icon",title:"Add Step",variant:"secondary",children:J(ac,{className:"size-4"})})}),De(Kt,{className:"flex lg:hidden",orientation:"vertical",children:[J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:J(ic,{className:"size-4"})}),J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:J(sc,{className:"size-4"})})]}),De(Kt,{className:"hidden lg:flex",orientation:"horizontal",children:[J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canUndo||t.isGenerating,onClick:()=>t.undo(),size:"icon",title:"Undo",variant:"secondary",children:J(ic,{className:"size-4"})}),J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!t.canRedo||t.isGenerating,onClick:()=>t.redo(),size:"icon",title:"Redo",variant:"secondary",children:J(sc,{className:"size-4"})})]}),De(Kt,{className:"flex lg:hidden",orientation:"vertical",children:[J(dc,{handleSave:o.handleSave,state:t}),J(cc,{actions:o,state:t})]}),De(Kt,{className:"hidden lg:flex",orientation:"horizontal",children:[J(dc,{handleSave:o.handleSave,state:t}),J(cc,{actions:o,state:t})]}),J(Gy,{actions:o,state:t}),J($y,{actions:o,state:t})]})}function dc({state:e,handleSave:t}){return De(E,{className:"relative border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:!e.currentWorkflowId||e.isGenerating||e.isSaving,onClick:t,size:"icon",title:e.isSaving?"Saving...":"Save workflow",variant:"secondary",children:[e.isSaving?J(ha,{className:"size-4 animate-spin"}):J(Ny,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&J("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function cc({state:e,actions:t}){let{open:o}=oe(),n=()=>{o(Md,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isDownloading||e.nodes.length===0||e.isGenerating||!e.currentWorkflowId,onClick:n,size:"icon",title:e.isDownloading?"Preparing download...":"Export workflow as code",variant:"secondary",children:e.isDownloading?J(ha,{className:"size-4 animate-spin"}):J(wy,{className:"size-4"})})}function Gy({state:e,actions:t}){let o=e.workflowVisibility==="public";return De(Ro,{children:[J(Oo,{asChild:!0,children:J(E,{className:"border hover:bg-black/5 dark:hover:bg-white/5",disabled:!e.currentWorkflowId||e.isGenerating,size:"icon",title:o?"Public workflow":"Private workflow",variant:"secondary",children:o?J(nc,{className:"size-4"}):J(rc,{className:"size-4"})})}),De(Lo,{align:"end",children:[De(xt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[J(rc,{className:"size-4"}),"Private",!o&&J(ya,{className:"ml-auto size-4"})]}),De(xt,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[J(nc,{className:"size-4"}),"Public",o&&J(ya,{className:"ml-auto size-4"})]})]})]})}function $y({state:e,actions:t}){return J(E,{className:"border hover:bg-black/5 disabled:opacity-100 dark:hover:bg-white/5 disabled:[&>svg]:text-muted-foreground",disabled:e.isExecuting||e.nodes.length===0||e.isGenerating,onClick:()=>t.handleExecute(),size:"icon",title:"Run Workflow",variant:"secondary",children:e.isExecuting?J(ha,{className:"size-4 animate-spin"}):J(xy,{className:"size-4"})})}function _y({isDuplicating:e,onDuplicate:t}){return De(E,{className:"h-9 border hover:bg-black/5 dark:hover:bg-white/5",disabled:e,onClick:t,size:"sm",title:"Duplicate to your workflows",variant:"secondary",children:[e?J(ha,{className:"mr-2 size-4 animate-spin"}):J(by,{className:"mr-2 size-4"}),"Duplicate"]})}function Uy({workflowId:e,state:t,actions:o}){return De("div",{className:"flex flex-col gap-1",children:[J("div",{className:"flex h-9 max-w-[160px] items-center overflow-hidden rounded-md border bg-secondary text-secondary-foreground sm:max-w-none",children:De(Ro,{onOpenChange:n=>n&&o.loadWorkflows(),children:[De(Oo,{className:"flex h-full cursor-pointer items-center gap-2 px-3 font-medium text-sm transition-all hover:bg-black/5 dark:hover:bg-white/5",children:[J(Bd,{className:"size-4 shrink-0"}),J("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:De(va,{children:[J("span",{className:"sm:hidden",children:"New"}),J("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),J(hy,{className:"size-3 shrink-0 opacity-50"})]}),De(Lo,{align:"start",className:"w-64",children:[J(xt,{asChild:!0,className:"flex items-center justify-between",children:De("a",{href:"/",children:["New Workflow"," ",!e&&J(ya,{className:"size-4 shrink-0"})]})}),J(Qn,{}),t.allWorkflows.length===0?J(xt,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>De(xt,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[J("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&J(ya,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&J("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var mc=({workflowId:e})=>{let t=By(),o=Vy(t);return De(va,{children:[J(ia,{className:"flex flex-col gap-2 rounded-none border-none bg-transparent p-0 lg:flex-row lg:items-center",position:"top-left",children:De("div",{className:"flex items-center gap-2",children:[J(Uy,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&J("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),J("div",{className:"pointer-events-auto absolute top-4 right-4 z-10",children:De("div",{className:"flex flex-col-reverse items-end gap-2 lg:flex-row lg:items-center",children:[J(Hy,{actions:o,state:t,workflowId:e}),De("div",{className:"flex items-center gap-2",children:[!e&&De(va,{children:[J(Cd,{}),J(vd,{})]}),e&&!t.isOwner&&J(_y,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),J(tc,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as _v,Zap as Uv}from"lucide-react";import{nanoid as qs}from"nanoid";import{BaseEdge as gc,getBezierPath as Ky,getSimpleBezierPath as qy,getSmoothStepPath as jy,Position as Ho,useInternalNode as pc}from"@xyflow/react";import{useAtomValue as Jy}from"jotai";import{jsx as yc}from"react/jsx-runtime";var Yy=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:i,targetPosition:a,selected:l})=>{let[s]=qy({sourceX:t,sourceY:o,sourcePosition:i,targetX:n,targetY:r,targetPosition:a});return yc(gc,{className:"stroke-1",id:e,path:s,style:{stroke:l?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},fc=(e,t,o)=>{let n=t===Ho.Left?"target":"source",r=e.internals.handleBounds?.[n],i=o?r?.find(c=>c.id===o):r?.find(c=>c.position===t);if(!i)return[0,0];let a=i.width/2,l=i.height/2;switch(t){case Ho.Left:a=0;break;case Ho.Right:a=i.width;break;case Ho.Top:l=0;break;case Ho.Bottom:l=i.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let s=e.internals.positionAbsolute.x+i.x+a,d=e.internals.positionAbsolute.y+i.y+l;return[s,d]},Xy=(e,t,o,n)=>{let r=Ho.Right,[i,a]=fc(e,r,o),l=Ho.Left,[s,d]=fc(t,l,n);return{sx:i,sy:a,tx:s,ty:d,sourcePos:r,targetPos:l}},Qy=({id:e,source:t,target:o,sourceHandleId:n,targetHandleId:r,style:i,selected:a})=>{let l=Jy(Yo),s=pc(t),d=pc(o);if(!(s&&d))return null;let{sx:c,sy:u,tx:f,ty:v,sourcePos:C,targetPos:h}=Xy(s,d,n,r),y={sourceX:c,sourceY:u,sourcePosition:C,targetX:f,targetY:v,targetPosition:h},[m]=l.edgeStyle==="bezier"?Ky(y):jy(y);return yc(gc,{id:e,path:m,style:{...i,stroke:a?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},Bs={Temporary:Yy,Animated:Qy};import{useAtomValue as cr}from"jotai";import{AlertTriangle as uv,Check as mv,Code as pv,EyeOff as wc,XCircle as fv,Zap as kc}from"lucide-react";import xc from"next/image";import{memo as gv,useState as yv}from"react";import{useAtomValue as ev}from"jotai";import{Check as hc,Circle as tv,EyeOff as ov,ListOrdered as nv,Loader2 as rv,XCircle as bc}from"lucide-react";import{memo as av,useEffect as sv,useState as iv}from"react";import{Handle as ba,Position as wa}from"@xyflow/react";import{Fragment as Zy,jsx as bo,jsxs as Vs}from"react/jsx-runtime";var vc=({className:e})=>Vs(Zy,{children:[bo("style",{children:`
|
|
212
202
|
@property --angle {
|
|
213
203
|
syntax: "<angle>";
|
|
214
204
|
initial-value: 0deg;
|
|
@@ -233,4 +223,4 @@ export async function POST(request: NextRequest) {
|
|
|
233
223
|
transparent 100%
|
|
234
224
|
);
|
|
235
225
|
}
|
|
236
|
-
`}),bo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Ws("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[bo("defs",{children:Ws("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[bo("stop",{offset:"0%",stopColor:"#60a5fa"}),bo("stop",{offset:"50%",stopColor:"#3b82f6"}),bo("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),bo("rect",{x:"1",y:"1",width:"calc(100% - 2px)",height:"calc(100% - 2px)",rx:"6",fill:"none",stroke:"url(#gradient-glow)",strokeWidth:"2",style:{filter:"drop-shadow(0 0 4px #3b82f6)"}})]})}),bo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as ar,jsxs as Yy}from"react/jsx-runtime";var Bo=({handles:e,className:t,status:o,...n})=>Yy(ua,{className:x("node-container relative gap-0 rounded-md bg-card p-0 transition-all duration-200",o==="success"&&"border-green-500 border-2",o==="error"&&"border-red-500 border-2",t),...n,children:[o==="running"&&ar(fc,{}),e.target&&ar(gc,{position:yc.Left,type:"target"}),e.source&&ar(gc,{position:yc.Right,type:"source"}),n.children]});var Vo=e=>ar(Gd,{...e}),Go=e=>ar(Hd,{...e});import{jsx as tt,jsxs as Xt}from"react/jsx-runtime";function av({status:e}){switch(e){case"pending":return tt(Qy,{className:"size-3 text-muted-foreground"});case"running":return tt(tv,{className:"size-3 animate-spin text-blue-400"});case"success":return tt(vc,{className:"size-3 text-green-400"});case"error":return tt(hc,{className:"size-3 text-red-400"})}}function sv({index:e,name:t,status:o}){return Xt("div",{className:x("flex items-center gap-1.5 rounded px-1.5 py-0.5 text-[10px] leading-tight transition-colors",o==="running"&&"bg-blue-500/10",o==="success"&&"bg-green-500/10",o==="error"&&"bg-red-500/10"),children:[Xt("span",{className:"w-3 shrink-0 text-right text-muted-foreground",children:[e,"."]}),tt(av,{status:o}),tt("span",{className:"min-w-0 flex-1 truncate",children:t})]})}function iv({status:e}){return!e||e==="idle"||e==="running"?null:Xt("div",{className:x("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&tt(vc,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&tt(hc,{className:"size-3.5 text-white",strokeWidth:2.5})]})}var zs=ov(({data:e,selected:t,id:o})=>{let n=Xy(Jo),[r,s]=rv({}),a=e.status,d=e.enabled===!1,i=e.config?.workflowIds||"[]",l=[];try{let y=JSON.parse(i);Array.isArray(y)&&(l=y)}catch{l=i.split(",").map(y=>y.trim()).filter(Boolean)}nv(()=>{if(l.length===0)return;let y=!1;async function p(){try{let v=await fetch("/api/workflow-builder/workflows");if(!v.ok)return;let g=await v.json(),C=g.workflows||g||[],I={};for(let A of C)I[A.id]=A.name;y||s(I)}catch{}}return p(),()=>{y=!0}},[i]);let u=n[o]?.output,f=u?.results,h=new Map;if(f)for(let y of f)h.set(y.workflowId,y.success?"success":"error");function k(y,p){return f&&h.get(y)||"pending"}let b=l.length===0;return Xt(Bo,{className:x("relative flex w-56 flex-col shadow-none transition-all duration-150 ease-out",t&&"border-primary",d&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:a,children:[d&&tt("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:tt(Zy,{className:"size-3.5 text-white"})}),tt(iv,{status:a}),Xt("div",{className:"flex items-center gap-2 border-b px-3 py-2.5",children:[tt(ev,{className:"size-4 shrink-0 text-emerald-300",strokeWidth:1.5}),Xt("div",{className:"min-w-0 flex-1",children:[tt(Vo,{className:"truncate text-xs font-medium",children:e.label||"Run Workflows in Sequence"}),!b&&Xt(Go,{className:"text-[10px]",children:[l.length," workflow",l.length!==1?"s":""]})]})]}),tt("div",{className:"flex flex-col gap-0.5 px-2 py-2",children:b?tt("p",{className:"px-1 py-2 text-center text-[10px] text-muted-foreground",children:"No workflows configured"}):l.map((y,p)=>tt(sv,{index:p+1,name:r[y]||y.slice(0,12)+"...",status:k(y,p)},`${y}-${p}`))}),u&&f&&Xt("div",{className:"border-t px-3 py-1.5 text-[10px] text-muted-foreground",children:[u.succeeded||0," passed",(u.failed||0)>0&&Xt("span",{className:"text-red-400",children:[" / ",u.failed," failed"]})]})]})});zs.displayName="SequenceNode";import{Fragment as Nv,jsx as Te,jsxs as Qt}from"react/jsx-runtime";var fv=e=>({"gpt-5":"GPT-5","openai/gpt-5.1-instant":"GPT-5.1 Instant","openai/gpt-5.1-codex":"GPT-5.1 Codex","openai/gpt-5.1-codex-mini":"GPT-5.1 Codex Mini","openai/gpt-5.1-thinking":"GPT-5.1 Thinking","gpt-4":"GPT-4","gpt-4o":"GPT-4o","gpt-4o-mini":"GPT-4o Mini","claude-3-5-sonnet":"Claude 3.5","claude-3-opus":"Claude 3 Opus","anthropic/claude-opus-4.5":"Claude Opus 4.5","anthropic/claude-sonnet-4.5":"Claude Sonnet 4.5","anthropic/claude-haiku-4.5":"Claude Haiku 4.5","google/gemini-3-pro-preview":"Gemini 3 Pro Preview","google/gemini-2.5-flash-lite":"Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Gemini 2.5 Flash","google/gemini-2.5-pro":"Gemini 2.5 Pro","meta/llama-4-scout":"Llama 4 Scout","meta/llama-3.3-70b":"Llama 3.3 70B","meta/llama-3.1-8b":"Llama 3.1 8B","moonshotai/kimi-k2-0905":"Kimi K2","openai/gpt-oss-120b":"GPT OSS 120B","openai/gpt-oss-safeguard-20b":"GPT OSS Safeguard 20B","openai/gpt-oss-20b":"GPT OSS 20B","o1-preview":"o1 Preview","o1-mini":"o1 Mini","bfl/flux-2-pro":"FLUX.2 Pro","bfl/flux-1-pro":"FLUX.1 Pro","openai/dall-e-3":"DALL-E 3","google/imagen-4.0-generate":"Imagen 4.0"})[e]||e,xc={"HTTP Request":"System","Database Query":"Database",Condition:"Condition","Execute Code":"System",Loop:"Loop",Switch:"Switch",Merge:"Merge","Run Workflow":"System","Run Workflows in Sequence":"System"},gv=e=>{if(xc[e])return xc[e];let t=fe(e);return t?.integration&&Dt(t.integration)?.label||"System"};function yv(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var vv=e=>{if(["Database Query"].includes(e))return!0;let o=fe(e);return o?_o(o.integration):!1},hv=e=>{switch(e){case"HTTP Request":return qo.icon;case"Database Query":return Ko.icon;case"Execute Code":return Te(cv,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return Uo.icon;case"Loop":return _r.icon;case"Merge":return Ur.icon;case"Switch":return jr.icon;case"Run Workflow":return Kr.icon;case"Run Workflows in Sequence":return qr.icon;default:break}let t=fe(e);if(t){let o=Dt(t.integration);if(o?.icon){let n=o.icon;return Te(n,{className:"size-12"})}}return Te(Nc,{className:"size-12 text-amber-300",strokeWidth:1.5})},bv=({status:e})=>!e||e==="idle"||e==="running"?null:Qt("div",{className:x("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&Te(dv,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Te(uv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),wv=({model:e})=>e?Te("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:fv(e)}):null;function xv({base64:e}){let[t,o]=pv(!1);return Qt(Nv,{children:[Te("button",{className:"relative size-12 cursor-zoom-in overflow-hidden rounded-lg transition-transform hover:scale-105",onClick:n=>{n.stopPropagation(),o(!0)},type:"button",children:Te(wc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Te(aa,{onOpenChange:o,open:t,children:Qt(ql,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Te(jl,{className:"sr-only",children:"Generated Image"}),Te("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Te(wc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var Bs=mv(({data:e,selected:t,id:o})=>{let n=sr(no),r=sr(Jo),s=sr(wr),a=sr(ei),d=sr(pr);if(!e)return null;let i=e.config?.actionType||"",l=e.status;if(i==="Run Workflows in Sequence")return Te(zs,{data:e,id:o,selected:t});let c=r[o],u=n&&i==="Generate Image"&&c?.output&&yv(c.output);if(!i){let w=e.enabled===!1;return Qt(Bo,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",w&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:l,children:[w&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Te(bc,{className:"size-3.5 text-white"})}),Qt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Te(Nc,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),Qt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Te(Vo,{className:"text-base",children:e.label||"Action"}),Te(Go,{className:"text-xs",children:"Select an action"})]})]})]})}let f=fe(i),h=e.label||f?.label||i,k=e.description||gv(i),b=vv(i),y=s.has(o),p=e.config?.integrationId,v=p&&a.has(p),g=d&&b&&!v&&!y,I=i==="Generate Text"?e.config?.aiModel||"meta/llama-4-scout":i==="Generate Image"?e.config?.imageModel||"google/imagen-4.0-generate":null,A=e.enabled===!1;return Qt(Bo,{className:x("relative flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",A&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:l,children:[A&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Te(bc,{className:"size-3.5 text-white"})}),!A&&g&&Te("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Te(lv,{className:"size-3.5 text-white"})}),Te(bv,{status:l}),Qt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Te(xv,{base64:c.output.base64}):hv(i),Qt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Te(Vo,{className:"text-base",children:h}),k&&Te(Go,{className:"text-xs",children:k}),I&&Te(wv,{model:I})]})]})]})});Bs.displayName="ActionNode";import{Plus as kv}from"lucide-react";import{jsx as Dn,jsxs as ha}from"react/jsx-runtime";function kc({data:e}){return ha("div",{className:"flex flex-col items-center justify-center gap-8 rounded-lg border border-border border-dashed bg-background/50 p-8 backdrop-blur-sm",children:[ha("div",{className:"text-center",children:[Dn("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),ha("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",Dn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://useworkflow.dev/",rel:"noopener noreferrer",target:"_blank",children:"Workflow"}),","," ",Dn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/",rel:"noopener noreferrer",target:"_blank",children:"AI SDK"}),","," ",Dn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://vercel.com/ai-gateway",rel:"noopener noreferrer",target:"_blank",children:"AI Gateway"})," ","and"," ",Dn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/elements",rel:"noopener noreferrer",target:"_blank",children:"AI Elements"})]})]}),ha(D,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[Dn(kv,{className:"size-4"}),"Add a Step"]})]})}import{Check as Cv,Clock as Tv,Play as Av,Webhook as Sv,XCircle as Iv}from"lucide-react";import{memo as Pv}from"react";import{jsx as ir,jsxs as ba}from"react/jsx-runtime";var Vs=Pv(({data:e,selected:t})=>{if(!e)return null;let o=e.config?.triggerType||"Manual",n=e.label||o,r=e.description||"Trigger",s=e.status,a=Av;return o==="Schedule"?a=Tv:o==="Webhook"&&(a=Sv),ba(Bo,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary"),handles:{target:!1,source:!0},status:s,children:[s&&s!=="idle"&&s!=="running"&&ba("div",{className:x("absolute top-2 right-2 rounded-full p-1",s==="success"&&"bg-green-500/50",s==="error"&&"bg-red-500/50"),children:[s==="success"&&ir(Cv,{className:"size-3.5 text-white",strokeWidth:2.5}),s==="error"&&ir(Iv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),ba("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[ir(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),ba("div",{className:"flex flex-col items-center gap-1 text-center",children:[ir(Vo,{className:"text-base",children:n}),r&&ir(Go,{className:"text-xs",children:r})]})]})]})});Vs.displayName="TriggerNode";import{useAtomValue as Ev,useSetAtom as lr}from"jotai";import{Link2Off as Dv,Plus as Rv,Trash2 as Ov}from"lucide-react";import{nanoid as Lv}from"nanoid";import{useCallback as On,useEffect as Mv,useRef as Fv}from"react";import{jsx as Rn,jsxs as Ac}from"react/jsx-runtime";function Cc({menuState:e,onClose:t}){let o=Ev(ne),n=lr(ao),r=lr(so),s=lr(Yo),a=lr(ke),d=lr(Bt),{open:i}=re(),l=Fv(null),c=On(()=>{if(e?.nodeId){let b=e.nodeId;t(),i(Me,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(b)}})}},[e,n,t,i]),u=On(()=>{if(e?.edgeId){let b=e.edgeId;t(),i(Me,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(b)}})}},[e,r,t,i]),f=On(()=>{if(e?.flowPosition){let y={id:Lv(),type:"action",position:{x:e.flowPosition.x,y:e.flowPosition.y-96},data:{label:"",description:"",type:"action",config:{},status:"idle"},selected:!0};s(y),a(y.id),d("properties")}t()},[e,s,a,d,t]);if(Mv(()=>{if(!e)return;let b=v=>{l.current&&!l.current.contains(v.target)&&t()},y=v=>{v.key==="Escape"&&t()},p=setTimeout(()=>{document.addEventListener("mousedown",b),document.addEventListener("keydown",y)},0);return()=>{clearTimeout(p),document.removeEventListener("mousedown",b),document.removeEventListener("keydown",y)}},[e,t]),!e)return null;let h=!!(e.nodeId&&o.find(b=>b.id===e.nodeId)?.data.type==="trigger"),k=()=>e.nodeId&&o.find(y=>y.id===e.nodeId)?.data.label||"Step";return Ac("div",{className:"fade-in-0 zoom-in-95 fixed z-50 min-w-[8rem] animate-in overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",ref:l,style:{left:e.position.x,top:e.position.y},children:[e.type==="node"&&Rn(Gs,{disabled:h,icon:Rn(Ov,{className:"size-4"}),label:`Delete ${k()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&Rn(Gs,{icon:Rn(Dv,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&Rn(Gs,{icon:Rn(Rv,{className:"size-4"}),label:"Add Step",onClick:f})]})}function Gs({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return Ac("button",{className:x("relative flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",n==="destructive"&&"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive",r&&"pointer-events-none opacity-50"),disabled:r,onClick:o,type:"button",children:[e,t]})}function Tc(e,t){let o=On((s,a)=>{s.preventDefault(),t({type:"node",position:{x:s.clientX,y:s.clientY},nodeId:a.id})},[t]),n=On((s,a)=>{s.preventDefault(),t({type:"edge",position:{x:s.clientX,y:s.clientY},edgeId:a.id})},[t]),r=On(s=>{s.preventDefault();let a=e({x:s.clientX,y:s.clientY});t({type:"pane",position:{x:s.clientX,y:s.clientY},flowPosition:a})},[e,t]);return{onNodeContextMenu:o,onEdgeContextMenu:n,onPaneContextMenu:r}}import{jsx as $o,jsxs as Ic}from"react/jsx-runtime";var $v=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:Gv,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:Hv,defaultConfig:{}}],_v={animated:Fs.Animated,temporary:Fs.Temporary};function Pc(){let[e,t]=dr(ne),[o,n]=dr(ue),[r]=dr(Nt),s=Hs(Ue),[a]=dr(gr),d=Hs(yr),i=Hs(vr),[l,c]=dr(br),u=wo(ai),f=wo(si),h=wo(ke),k=wo(_e),b=wo(Yo),y=wo(nt),p=wo(Wt),v=wo(Bt),{screenToFlowPosition:g,fitView:C,getViewport:I,setViewport:A}=Bv(),w=Ho(null),m=Ho(null),S=Ho(!1),X=Ho(!1),[le,L]=Sc(!1),[W,$]=Sc(null),{onNodeContextMenu:P,onEdgeContextMenu:V,onPaneContextMenu:J}=Tc(g,$),F=xt(()=>{$(null)},[]),K=Ho(void 0),T=e.some(Q=>Q.type!=="add"),z=Ho(!1),N=Ho(!1);wa(()=>{if(l&&!N.current){if(N.current=!0,document.cookie.split("; ").find(Ee=>Ee.startsWith("sidebar-collapsed="))?.split("=")[1]==="true")return;let _=I(),ce=window.innerWidth*.3/2;A({..._,x:_.x-ce},{duration:0})}},[l,I,A]),wa(()=>{if(K.current!==s){if(l&&X.current){K.current=s,L(!0),c(!1);return}setTimeout(()=>{C({maxZoom:1,minZoom:.5,padding:.2,duration:0}),K.current=s,X.current=!0,L(!0),c(!1)},0)}},[s,C,l,c]),wa(()=>{s||(T&&!z.current?(z.current=!0,setTimeout(()=>{C({maxZoom:1,minZoom:.5,padding:.2,duration:0}),X.current=!0,L(!0)},0)):T||(z.current=!1))},[s,T,C]),wa(()=>{let Q=E=>{(E.metaKey||E.ctrlKey)&&E.key==="/"&&(E.preventDefault(),C({padding:.2,duration:300}))};return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[C]);let R=Vv(()=>({trigger:Vs,action:Bs,add:kc}),[]),G=xt((Q,E)=>{let _=e.find(Y=>Y.id===Q);return!_||_.type==="add"?!1:E==="target"?_.type!=="trigger":!0},[e]),oe=xt(Q=>!(!(Q.source&&Q.target)||Q.source===Q.target),[]),de=xt(Q=>{let E={id:$s(),...Q,type:"animated"};n([...o,E]),y(!0),p({immediate:!0})},[o,n,y,p]),B=xt((Q,E)=>{h(E.id)},[h]),Ae=xt((Q,E)=>{w.current=E.nodeId,m.current=E.handleType},[]),Je=xt(Q=>{let E="changedTouches"in Q?Q.changedTouches[0].clientX:Q.clientX,_="changedTouches"in Q?Q.changedTouches[0].clientY:Q.clientY;return{clientX:E,clientY:_}},[]),Ye=xt((Q,E,_)=>{let Y=Q.target.closest(".react-flow")?.getBoundingClientRect(),ce=Y?E-Y.left:E,Ee=Y?_-Y.top:_;return{adjustedX:ce,adjustedY:Ee}},[]),$e=xt(Q=>{let E=Q.getAttribute("data-id"),_=m.current==="source",Y=_?"target":"source",ce=w.current;E&&ce&&E!==ce&&G(E,Y)&&de({source:_?ce:E,target:_?E:ce,sourceHandle:null,targetHandle:null})},[G,de]),Zt=xt((Q,E,_)=>{let Y=w.current;if(!Y)return;let{adjustedX:ce,adjustedY:Ee}=Ye(Q,E,_),Le=$v.find(ka=>ka.type==="action");if(!Le)return;let Ln=g({x:ce,y:Ee}),Na=192;Ln.y-=Na/2;let Mn={id:$s(),type:Le.type,position:Ln,data:{label:Le.label,description:Le.description,type:Le.type,config:Le.defaultConfig,status:"idle"},selected:!0};b(Mn),h(Mn.id),v("properties"),setTimeout(()=>{t(ka=>ka.map(Us=>({...Us,selected:Us.id===Mn.id})))},50);let _s=m.current==="source",Fc={id:$s(),source:_s?Y:Mn.id,target:_s?Mn.id:Y,type:"animated"};n([...o,Fc]),y(!0),p({immediate:!0}),S.current=!0,setTimeout(()=>{S.current=!1},100)},[Ye,g,b,o,n,t,h,v,y,p]),Et=xt(Q=>{if(!w.current)return;let{clientX:E,clientY:_}=Je(Q),Y="changedTouches"in Q?document.elementFromPoint(E,_):Q.target;if(!Y){w.current=null;return}let ce=Y.closest(".react-flow__node"),Ee=Y.closest(".react-flow__handle");if(ce&&!Ee&&m.current){$e(ce),w.current=null,m.current=null;return}ce||Ee||Zt(Q,E,_),w.current=null,m.current=null},[Je,$e,Zt]),ee=xt(()=>{S.current||(h(null),k(null),F())},[h,k,F]),xe=xt(({nodes:Q})=>{S.current&&Q.length===0||(Q.length===0?h(null):Q.length===1&&h(Q[0].id))},[h]);return Ic("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:le?1:0,width:d?`calc(100% - ${d})`:"100%",transition:i?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[$o("div",{className:"pointer-events-auto",children:$o(dc,{workflowId:s??void 0})}),Ic(sd,{className:"bg-background",connectionLineComponent:ld,connectionMode:Wv.Strict,edges:o,edgeTypes:_v,elementsSelectable:!r,isValidConnection:oe,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:R,onConnect:r?void 0:de,onConnectEnd:r?void 0:Et,onConnectStart:r?void 0:Ae,onEdgeContextMenu:r?void 0:V,onEdgesChange:r?void 0:f,onNodeClick:r?void 0:B,onNodeContextMenu:r?void 0:P,onNodesChange:r?void 0:u,onPaneClick:ee,onPaneContextMenu:r?void 0:J,onSelectionChange:r?void 0:xe,children:[$o(sa,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:$o(dd,{})}),a&&$o(zv,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),s&&$o(md,{workflowId:s}),$o(Cc,{menuState:W,onClose:F})]})}import{jsx as Ec}from"react/jsx-runtime";function Dc(){let e=Uv();return e==="/"||e.startsWith("/workflows/")?Ec("div",{className:"fixed inset-0 z-0",children:Ec(Pc,{})}):null}import{AuthUIProvider as Kv}from"@daveyplate/better-auth-ui";import qv from"next/link";import{useRouter as jv}from"next/navigation";import{jsx as Jv}from"react/jsx-runtime";var Rc=e=>{let t=jv(),{children:o,...n}=e;return Jv(Kv,{...n,authClient:Mo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:qv,children:o})};import{ThemeProvider as Yv}from"next-themes";import{jsx as Xv}from"react/jsx-runtime";var Oc=({children:e,...t})=>Xv(Yv,{...t,children:e});import{jsx as xo,jsxs as Lc}from"react/jsx-runtime";function th(e){Bi();let t=eh(jo);return xa.useEffect(()=>{e.canvas&&t(o=>({...o,...e.canvas}))},[e.canvas,t]),Lc(Ki,{children:[xo(xa.Suspense,{children:Lc(Qv,{children:[xo(Dc,{}),e.children]})}),xo(ad,{}),xo(rd,{})]})}var Mc=e=>{let{children:t,canvas:o,...n}=e;return xo(Oc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:xo(Rc,{...n,children:xo(Zv,{children:xo(th,{canvas:o,children:t})})})})};import{jsx as nh}from"react/jsx-runtime";var oh=e=>{let{children:t,canvas:o,...n}=e;return nh(Mc,{canvas:o,...n,children:t})};function rh(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function ah(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{oh as Layout,cs as WorkflowEditor,Tf as WorkflowPage,rh as isAiGatewayManagedKeysEnabled,ah as isAiGatewayManagedKeysEnabledClient};
|
|
226
|
+
`}),bo("div",{className:N("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Vs("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[bo("defs",{children:Vs("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[bo("stop",{offset:"0%",stopColor:"#60a5fa"}),bo("stop",{offset:"50%",stopColor:"#3b82f6"}),bo("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),bo("rect",{x:"1",y:"1",width:"calc(100% - 2px)",height:"calc(100% - 2px)",rx:"6",fill:"none",stroke:"url(#gradient-glow)",strokeWidth:"2",style:{filter:"drop-shadow(0 0 4px #3b82f6)"}})]})}),bo("div",{className:N("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as zt,jsxs as Hs}from"react/jsx-runtime";var Go=({handles:e,className:t,status:o,...n})=>Hs(ma,{className:N("node-container relative gap-0 rounded-md bg-card p-0 transition-all duration-200",o==="success"&&"border-green-500 border-2",o==="error"&&"border-red-500 border-2",t),...n,children:[o==="running"&&zt(vc,{}),e.targetHandles&&e.targetHandles.length>0?zt("div",{className:"absolute top-0 -left-[4px] flex h-full flex-col items-start justify-center gap-1",children:e.targetHandles.map(r=>Hs("div",{className:"relative flex items-center",children:[zt(ba,{id:r.id,position:wa.Left,style:{position:"relative",top:"auto",left:"auto",transform:"none"},type:"target"}),r.label&&zt("span",{className:"ml-1.5 text-muted-foreground text-[9px] leading-none",children:r.label})]},r.id))}):e.target&&zt(ba,{position:wa.Left,type:"target"}),e.sourceHandles&&e.sourceHandles.length>0?zt("div",{className:"absolute top-0 -right-[4px] flex h-full flex-col items-end justify-center gap-1",children:e.sourceHandles.map((r,i)=>Hs("div",{className:"relative flex items-center",children:[r.label&&zt("span",{className:"mr-1.5 text-muted-foreground text-[9px] leading-none",children:r.label}),zt(ba,{id:r.id,position:wa.Right,style:{position:"relative",top:"auto",right:"auto",transform:"none"},type:"source"})]},r.id))}):e.source&&zt(ba,{position:wa.Right,type:"source"}),n.children]});var $o=e=>zt(_d,{...e}),_o=e=>zt(Ud,{...e});import{jsx as et,jsxs as Zt}from"react/jsx-runtime";function lv({status:e}){switch(e){case"pending":return et(tv,{className:"size-3 text-muted-foreground"});case"running":return et(rv,{className:"size-3 animate-spin text-blue-400"});case"success":return et(hc,{className:"size-3 text-green-400"});case"error":return et(bc,{className:"size-3 text-red-400"})}}function dv({index:e,name:t,status:o}){return Zt("div",{className:N("flex items-center gap-1.5 rounded px-1.5 py-0.5 text-[10px] leading-tight transition-colors",o==="running"&&"bg-blue-500/10",o==="success"&&"bg-green-500/10",o==="error"&&"bg-red-500/10"),children:[Zt("span",{className:"w-3 shrink-0 text-right text-muted-foreground",children:[e,"."]}),et(lv,{status:o}),et("span",{className:"min-w-0 flex-1 truncate",children:t})]})}function cv({status:e}){return!e||e==="idle"||e==="running"?null:Zt("div",{className:N("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&et(hc,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&et(bc,{className:"size-3.5 text-white",strokeWidth:2.5})]})}var Gs=av(({data:e,selected:t,id:o})=>{let n=ev(Xo),[r,i]=iv({}),a=e.status,l=e.enabled===!1,s=e.config?.workflowIds||"[]",d=[];try{let y=JSON.parse(s);Array.isArray(y)&&(d=y)}catch{d=s.split(",").map(y=>y.trim()).filter(Boolean)}sv(()=>{if(d.length===0)return;let y=!1;async function m(){try{let b=await fetch("/api/workflow-builder/workflows");if(!b.ok)return;let g=await b.json(),S=g.workflows||g||[],D={};for(let I of S)D[I.id]=I.name;y||i(D)}catch{}}return m(),()=>{y=!0}},[s]);let u=n[o]?.output,f=u?.results,v=new Map;if(f)for(let y of f)v.set(y.workflowId,y.success?"success":"error");function C(y,m){return f&&v.get(y)||"pending"}let h=d.length===0;return Zt(Go,{className:N("relative flex w-56 flex-col shadow-none transition-all duration-150 ease-out",t&&"border-primary",l&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:a,children:[l&&et("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:et(ov,{className:"size-3.5 text-white"})}),et(cv,{status:a}),Zt("div",{className:"flex items-center gap-2 border-b px-3 py-2.5",children:[et(nv,{className:"size-4 shrink-0 text-emerald-300",strokeWidth:1.5}),Zt("div",{className:"min-w-0 flex-1",children:[et($o,{className:"truncate text-xs font-medium",children:e.label||"Run Workflows in Sequence"}),!h&&Zt(_o,{className:"text-[10px]",children:[d.length," workflow",d.length!==1?"s":""]})]})]}),et("div",{className:"flex flex-col gap-0.5 px-2 py-2",children:h?et("p",{className:"px-1 py-2 text-center text-[10px] text-muted-foreground",children:"No workflows configured"}):d.map((y,m)=>et(dv,{index:m+1,name:r[y]||y.slice(0,12)+"...",status:C(y,m)},`${y}-${m}`))}),u&&f&&Zt("div",{className:"border-t px-3 py-1.5 text-[10px] text-muted-foreground",children:[u.succeeded||0," passed",(u.failed||0)>0&&Zt("span",{className:"text-red-400",children:[" / ",u.failed," failed"]})]})]})});Gs.displayName="SequenceNode";import{Fragment as Tv,jsx as Se,jsxs as eo}from"react/jsx-runtime";var vv=e=>({"gpt-5":"GPT-5","openai/gpt-5.1-instant":"GPT-5.1 Instant","openai/gpt-5.1-codex":"GPT-5.1 Codex","openai/gpt-5.1-codex-mini":"GPT-5.1 Codex Mini","openai/gpt-5.1-thinking":"GPT-5.1 Thinking","gpt-4":"GPT-4","gpt-4o":"GPT-4o","gpt-4o-mini":"GPT-4o Mini","claude-3-5-sonnet":"Claude 3.5","claude-3-opus":"Claude 3 Opus","anthropic/claude-opus-4.5":"Claude Opus 4.5","anthropic/claude-sonnet-4.5":"Claude Sonnet 4.5","anthropic/claude-haiku-4.5":"Claude Haiku 4.5","google/gemini-3-pro-preview":"Gemini 3 Pro Preview","google/gemini-2.5-flash-lite":"Gemini 2.5 Flash Lite","google/gemini-2.5-flash":"Gemini 2.5 Flash","google/gemini-2.5-pro":"Gemini 2.5 Pro","meta/llama-4-scout":"Llama 4 Scout","meta/llama-3.3-70b":"Llama 3.3 70B","meta/llama-3.1-8b":"Llama 3.1 8B","moonshotai/kimi-k2-0905":"Kimi K2","openai/gpt-oss-120b":"GPT OSS 120B","openai/gpt-oss-safeguard-20b":"GPT OSS Safeguard 20B","openai/gpt-oss-20b":"GPT OSS 20B","o1-preview":"o1 Preview","o1-mini":"o1 Mini","bfl/flux-2-pro":"FLUX.2 Pro","bfl/flux-1-pro":"FLUX.1 Pro","openai/dall-e-3":"DALL-E 3","google/imagen-4.0-generate":"Imagen 4.0"})[e]||e,Nc={"HTTP Request":"System","Database Query":"Database",Condition:"Condition","Execute Code":"System",Loop:"Loop",Switch:"Switch",Merge:"Merge","Run Workflow":"System","Run Workflows in Sequence":"System"},hv=e=>{if(Nc[e])return Nc[e];let t=ge(e);return t?.integration&&Rt(t.integration)?.label||"System"};function bv(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var wv=e=>{if(["Database Query"].includes(e))return!0;let o=ge(e);return o?Ko(o.integration):!1},xv=e=>{switch(e){case"HTTP Request":return Jo.icon;case"Database Query":return jo.icon;case"Execute Code":return Se(pv,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return qo.icon;case"Loop":return jr.icon;case"Merge":return wn.icon;case"Switch":return xn.icon;case"Run Workflow":return Jr.icon;case"Run Workflows in Sequence":return Yr.icon;default:break}let t=ge(e);if(t){let o=Rt(t.integration);if(o?.icon){let n=o.icon;return Se(n,{className:"size-12"})}}return Se(kc,{className:"size-12 text-amber-300",strokeWidth:1.5})},Nv=({status:e})=>!e||e==="idle"||e==="running"?null:eo("div",{className:N("absolute top-2 right-2 rounded-full p-1",e==="success"&&"bg-green-500/50",e==="error"&&"bg-red-500/50"),children:[e==="success"&&Se(mv,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Se(fv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),kv=({model:e})=>e?Se("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:vv(e)}):null;function Cv({base64:e}){let[t,o]=yv(!1);return eo(Tv,{children:[Se("button",{className:"relative size-12 cursor-zoom-in overflow-hidden rounded-lg transition-transform hover:scale-105",onClick:n=>{n.stopPropagation(),o(!0)},type:"button",children:Se(xc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Se(sa,{onOpenChange:o,open:t,children:eo(Yl,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Se(Xl,{className:"sr-only",children:"Generated Image"}),Se("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Se(xc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var $s=gv(({data:e,selected:t,id:o})=>{let n=cr(ro),r=cr(Xo),i=cr(Tr),a=cr(ni),l=cr(hr);if(!e)return null;let s=e.config?.actionType||"",d=e.status;if(s==="Run Workflows in Sequence")return Se(Gs,{data:e,id:o,selected:t});let c=r[o],u=n&&s==="Generate Image"&&c?.output&&bv(c.output);if(!s){let $=e.enabled===!1;return eo(Go,{className:N("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",$&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:d,children:[$&&Se("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Se(wc,{className:"size-3.5 text-white"})}),eo("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Se(kc,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),eo("div",{className:"flex flex-col items-center gap-1 text-center",children:[Se($o,{className:"text-base",children:e.label||"Action"}),Se(_o,{className:"text-xs",children:"Select an action"})]})]})]})}let f=ge(s),v=e.label||f?.label||s,C=e.description||hv(s),h=wv(s),y=i.has(o),m=e.config?.integrationId,b=m&&a.has(m),g=l&&h&&!b&&!y,D=s==="Generate Text"?e.config?.aiModel||"meta/llama-4-scout":s==="Generate Image"?e.config?.imageModel||"google/imagen-4.0-generate":null,I=e.enabled===!1,x=s==="Switch",p=s==="Condition",w;if(x){let $=Number(e.config?.routeCount)||4;w=[];for(let T=0;T<$;T++){let H=e.config?.[`routeName${T}`]||`Route ${T+1}`;w.push({id:`route-${T}`,label:H})}w.push({id:"route-default",label:"Default"})}else p&&(w=[{id:"condition-true",label:"True"},{id:"condition-false",label:"False"}]);let G=x||p,te=s==="Merge",O;if(te){let $=Number(e.config?.inputCount)||2;O=[];for(let T=0;T<$;T++)O.push({id:`input-${T}`,label:`Input ${T+1}`})}return eo(Go,{className:N("relative flex flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",G||te?"min-h-48 w-48":"h-48 w-48",t&&"border-primary",I&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!te,source:!G,sourceHandles:w,targetHandles:O},status:d,children:[I&&Se("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Se(wc,{className:"size-3.5 text-white"})}),!I&&g&&Se("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Se(uv,{className:"size-3.5 text-white"})}),Se(Nv,{status:d}),eo("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Se(Cv,{base64:c.output.base64}):xv(s),eo("div",{className:"flex flex-col items-center gap-1 text-center",children:[Se($o,{className:"text-base",children:v}),C&&Se(_o,{className:"text-xs",children:C}),D&&Se(kv,{model:D})]})]})]})});$s.displayName="ActionNode";import{Plus as Sv}from"lucide-react";import{jsx as Fn,jsxs as xa}from"react/jsx-runtime";function Cc({data:e}){return xa("div",{className:"flex flex-col items-center justify-center gap-8 rounded-lg border border-border border-dashed bg-background/50 p-8 backdrop-blur-sm",children:[xa("div",{className:"text-center",children:[Fn("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),xa("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",Fn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://useworkflow.dev/",rel:"noopener noreferrer",target:"_blank",children:"Workflow"}),","," ",Fn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/",rel:"noopener noreferrer",target:"_blank",children:"AI SDK"}),","," ",Fn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://vercel.com/ai-gateway",rel:"noopener noreferrer",target:"_blank",children:"AI Gateway"})," ","and"," ",Fn("a",{className:"underline underline-offset-2 transition duration-200 ease-out hover:text-foreground",href:"https://ai-sdk.dev/elements",rel:"noopener noreferrer",target:"_blank",children:"AI Elements"})]})]}),xa(E,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[Fn(Sv,{className:"size-4"}),"Add a Step"]})]})}import{Check as Av,Clock as Iv,Play as Pv,Webhook as Ev,XCircle as Dv}from"lucide-react";import{memo as Rv}from"react";import{jsx as ur,jsxs as Na}from"react/jsx-runtime";var _s=Rv(({data:e,selected:t})=>{if(!e)return null;let o=e.config?.triggerType||"Manual",n=e.label||o,r=e.description||"Trigger",i=e.status,a=Pv;return o==="Schedule"?a=Iv:o==="Webhook"&&(a=Ev),Na(Go,{className:N("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary"),handles:{target:!1,source:!0},status:i,children:[i&&i!=="idle"&&i!=="running"&&Na("div",{className:N("absolute top-2 right-2 rounded-full p-1",i==="success"&&"bg-green-500/50",i==="error"&&"bg-red-500/50"),children:[i==="success"&&ur(Av,{className:"size-3.5 text-white",strokeWidth:2.5}),i==="error"&&ur(Dv,{className:"size-3.5 text-white",strokeWidth:2.5})]}),Na("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[ur(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),Na("div",{className:"flex flex-col items-center gap-1 text-center",children:[ur($o,{className:"text-base",children:n}),r&&ur(_o,{className:"text-xs",children:r})]})]})]})});_s.displayName="TriggerNode";import{useAtomValue as Ov,useSetAtom as mr}from"jotai";import{Link2Off as Lv,Plus as Mv,Trash2 as Wv}from"lucide-react";import{nanoid as Fv}from"nanoid";import{useCallback as Bn,useEffect as zv,useRef as Bv}from"react";import{jsx as zn,jsxs as Ac}from"react/jsx-runtime";function Tc({menuState:e,onClose:t}){let o=Ov(re),n=mr(so),r=mr(io),i=mr(Qo),a=mr(Ce),l=mr(Ht),{open:s}=oe(),d=Bv(null),c=Bn(()=>{if(e?.nodeId){let h=e.nodeId;t(),s(Pe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(h)}})}},[e,n,t,s]),u=Bn(()=>{if(e?.edgeId){let h=e.edgeId;t(),s(Pe,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(h)}})}},[e,r,t,s]),f=Bn(()=>{if(e?.flowPosition){let y={id:Fv(),type:"action",position:{x:e.flowPosition.x,y:e.flowPosition.y-96},data:{label:"",description:"",type:"action",config:{},status:"idle"},selected:!0};i(y),a(y.id),l("properties")}t()},[e,i,a,l,t]);if(zv(()=>{if(!e)return;let h=b=>{d.current&&!d.current.contains(b.target)&&t()},y=b=>{b.key==="Escape"&&t()},m=setTimeout(()=>{document.addEventListener("mousedown",h),document.addEventListener("keydown",y)},0);return()=>{clearTimeout(m),document.removeEventListener("mousedown",h),document.removeEventListener("keydown",y)}},[e,t]),!e)return null;let v=!!(e.nodeId&&o.find(h=>h.id===e.nodeId)?.data.type==="trigger"),C=()=>e.nodeId&&o.find(y=>y.id===e.nodeId)?.data.label||"Step";return Ac("div",{className:"fade-in-0 zoom-in-95 fixed z-50 min-w-[8rem] animate-in overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",ref:d,style:{left:e.position.x,top:e.position.y},children:[e.type==="node"&&zn(Us,{disabled:v,icon:zn(Wv,{className:"size-4"}),label:`Delete ${C()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&zn(Us,{icon:zn(Lv,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&zn(Us,{icon:zn(Mv,{className:"size-4"}),label:"Add Step",onClick:f})]})}function Us({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return Ac("button",{className:N("relative flex w-full cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none","hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground",n==="destructive"&&"text-destructive hover:bg-destructive/10 hover:text-destructive focus:bg-destructive/10 focus:text-destructive",r&&"pointer-events-none opacity-50"),disabled:r,onClick:o,type:"button",children:[e,t]})}function Sc(e,t){let o=Bn((i,a)=>{i.preventDefault(),t({type:"node",position:{x:i.clientX,y:i.clientY},nodeId:a.id})},[t]),n=Bn((i,a)=>{i.preventDefault(),t({type:"edge",position:{x:i.clientX,y:i.clientY},edgeId:a.id})},[t]),r=Bn(i=>{i.preventDefault();let a=e({x:i.clientX,y:i.clientY});t({type:"pane",position:{x:i.clientX,y:i.clientY},flowPosition:a})},[e,t]);return{onNodeContextMenu:o,onEdgeContextMenu:n,onPaneContextMenu:r}}import{jsx as Uo,jsxs as Pc}from"react/jsx-runtime";var Kv=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:_v,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:Uv,defaultConfig:{}}],qv={animated:Bs.Animated,temporary:Bs.Temporary};function Ec(){let[e,t]=pr(re),[o,n]=pr(ce),[r]=pr(kt),i=Ks(Ue),[a]=pr(wr),l=Ks(xr),s=Ks(Nr),[d,c]=pr(Cr),u=wo(li),f=wo(di),v=wo(Ce),C=wo(_e),h=wo(Qo),y=wo(rt),m=wo(Lt),b=wo(Ht),{screenToFlowPosition:g,fitView:S,getViewport:D,setViewport:I}=Gv(),x=xo(null),p=xo(null),w=xo(null),G=xo(!1),te=xo(!1),[O,W]=Ic(!1),[$,T]=Ic(null),{onNodeContextMenu:H,onEdgeContextMenu:X,onPaneContextMenu:z}=Sc(g,T),q=Nt(()=>{T(null)},[]),A=xo(void 0),B=e.some(P=>P.type!=="add"),k=xo(!1),R=xo(!1);ka(()=>{if(d&&!R.current){if(R.current=!0,document.cookie.split("; ").find(Ne=>Ne.startsWith("sidebar-collapsed="))?.split("=")[1]==="true")return;let Y=D(),me=window.innerWidth*.3/2;I({...Y,x:Y.x-me},{duration:0})}},[d,D,I]),ka(()=>{if(A.current!==i){if(d&&te.current){A.current=i,W(!0),c(!1);return}setTimeout(()=>{S({maxZoom:1,minZoom:.5,padding:.2,duration:0}),A.current=i,te.current=!0,W(!0),c(!1)},0)}},[i,S,d,c]),ka(()=>{i||(B&&!k.current?(k.current=!0,setTimeout(()=>{S({maxZoom:1,minZoom:.5,padding:.2,duration:0}),te.current=!0,W(!0)},0)):B||(k.current=!1))},[i,B,S]),ka(()=>{let P=F=>{(F.metaKey||F.ctrlKey)&&F.key==="/"&&(F.preventDefault(),S({padding:.2,duration:300}))};return window.addEventListener("keydown",P),()=>{window.removeEventListener("keydown",P)}},[S]);let _=$v(()=>({trigger:_s,action:$s,add:Cc}),[]),ne=Nt((P,F)=>{let Y=e.find(pe=>pe.id===P);return!Y||Y.type==="add"?!1:F==="target"?Y.type!=="trigger":!0},[e]),le=Nt(P=>!(!(P.source&&P.target)||P.source===P.target),[]),V=Nt(P=>{let F={id:qs(),...P,type:"animated"};n([...o,F]),y(!0),m({immediate:!0})},[o,n,y,m]),Ae=Nt((P,F)=>{v(F.id)},[v]),tt=Nt((P,F)=>{x.current=F.nodeId,p.current=F.handleType,w.current=F.handleId},[]),Ye=Nt(P=>{let F="changedTouches"in P?P.changedTouches[0].clientX:P.clientX,Y="changedTouches"in P?P.changedTouches[0].clientY:P.clientY;return{clientX:F,clientY:Y}},[]),ot=Nt((P,F,Y)=>{let pe=P.target.closest(".react-flow")?.getBoundingClientRect(),me=pe?F-pe.left:F,Ne=pe?Y-pe.top:Y;return{adjustedX:me,adjustedY:Ne}},[]),Bt=Nt(P=>{let F=P.getAttribute("data-id"),Y=p.current==="source",pe=Y?"target":"source",me=x.current;F&&me&&F!==me&&ne(F,pe)&&V({source:Y?me:F,target:Y?F:me,sourceHandle:Y?w.current:null,targetHandle:Y?null:w.current})},[ne,V]),Dt=Nt((P,F,Y)=>{let pe=x.current;if(!pe)return;let{adjustedX:me,adjustedY:Ne}=ot(P,F,Y),ct=Kv.find(Sa=>Sa.type==="action");if(!ct)return;let fr=g({x:me,y:Ne}),Fc=192;fr.y-=Fc/2;let Vn={id:qs(),type:ct.type,position:fr,data:{label:ct.label,description:ct.description,type:ct.type,config:ct.defaultConfig,status:"idle"},selected:!0};h(Vn),v(Vn.id),b("properties"),setTimeout(()=>{t(Sa=>Sa.map(js=>({...js,selected:js.id===Vn.id})))},50);let Ta=p.current==="source",zc={id:qs(),source:Ta?pe:Vn.id,target:Ta?Vn.id:pe,sourceHandle:Ta?w.current:null,type:"animated"};n([...o,zc]),y(!0),m({immediate:!0}),G.current=!0,setTimeout(()=>{G.current=!1},100)},[ot,g,h,o,n,t,v,b,y,m]),ko=Nt(P=>{if(!x.current)return;let{clientX:F,clientY:Y}=Ye(P),pe="changedTouches"in P?document.elementFromPoint(F,Y):P.target;if(!pe){x.current=null;return}let me=pe.closest(".react-flow__node"),Ne=pe.closest(".react-flow__handle");if(me&&!Ne&&p.current){Bt(me),x.current=null,p.current=null;return}me||Ne||Dt(P,F,Y),x.current=null,p.current=null},[Ye,Bt,Dt]),Q=Nt(()=>{G.current||(v(null),C(null),q())},[v,C,q]),we=Nt(({nodes:P})=>{G.current&&P.length===0||(P.length===0?v(null):P.length===1&&v(P[0].id))},[v]);return Pc("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:O?1:0,width:l?`calc(100% - ${l})`:"100%",transition:s?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[Uo("div",{className:"pointer-events-auto",children:Uo(mc,{workflowId:i??void 0})}),Pc(dd,{className:"bg-background",connectionLineComponent:ud,connectionMode:Vv.Strict,edges:o,edgeTypes:qv,elementsSelectable:!r,isValidConnection:le,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:_,onConnect:r?void 0:V,onConnectEnd:r?void 0:ko,onConnectStart:r?void 0:tt,onEdgeContextMenu:r?void 0:X,onEdgesChange:r?void 0:f,onNodeClick:r?void 0:Ae,onNodeContextMenu:r?void 0:H,onNodesChange:r?void 0:u,onPaneClick:Q,onPaneContextMenu:r?void 0:z,onSelectionChange:r?void 0:we,children:[Uo(ia,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:Uo(md,{})}),a&&Uo(Hv,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),i&&Uo(gd,{workflowId:i}),Uo(Tc,{menuState:$,onClose:q})]})}import{jsx as Dc}from"react/jsx-runtime";function Rc(){let e=jv();return e==="/"||e.startsWith("/workflows/")?Dc("div",{className:"fixed inset-0 z-0",children:Dc(Ec,{})}):null}import{AuthUIProvider as Jv}from"@daveyplate/better-auth-ui";import Yv from"next/link";import{useRouter as Xv}from"next/navigation";import{jsx as Qv}from"react/jsx-runtime";var Oc=e=>{let t=Xv(),{children:o,...n}=e;return Qv(Jv,{...n,authClient:zo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:Yv,children:o})};import{ThemeProvider as Zv}from"next-themes";import{jsx as eh}from"react/jsx-runtime";var Lc=({children:e,...t})=>eh(Zv,{...t,children:e});import{jsx as No,jsxs as Mc}from"react/jsx-runtime";function rh(e){Xi();let t=nh(Yo);return Ca.useEffect(()=>{e.canvas&&t(o=>({...o,...e.canvas}))},[e.canvas,t]),Mc(Ci,{children:[No(Ca.Suspense,{children:Mc(th,{children:[No(Rc,{}),e.children]})}),No(ld,{}),No(id,{})]})}var Wc=e=>{let{children:t,canvas:o,...n}=e;return No(Lc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:No(Oc,{...n,children:No(oh,{children:No(rh,{canvas:o,children:t})})})})};import{jsx as sh}from"react/jsx-runtime";var ah=e=>{let{children:t,canvas:o,...n}=e;return sh(Wc,{canvas:o,...n,children:t})};function ih(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function lh(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{ah as Layout,ps as WorkflowEditor,Pf as WorkflowPage,ih as isAiGatewayManagedKeysEnabled,lh as isAiGatewayManagedKeysEnabledClient};
|