next-workflow-builder 0.7.0 → 0.7.1
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 +11 -0
- package/dist/chunk-QMJQ5NK5.js +42 -0
- package/dist/client/index.js +16 -16
- package/dist/handler-YTQRRHEK.js +1 -0
- package/dist/server/api/index.js +10 -10
- package/dist/styles.css +3 -0
- package/package.json +1 -1
- package/dist/chunk-HB2H2PVI.js +0 -42
- package/dist/handler-NWAMWKXW.js +0 -1
package/dist/client/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
"use client";import{a as zo,b as Wo,c as Bo}from"../chunk-NI6U7PHC.js";import{i as
|
|
2
|
-
`);n.buffer=r.pop()||"";for(let s of r)Pc(s,o,n)}var Dc={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(),s=new TextDecoder,a={buffer:"",currentData:o?{nodes:o.nodes||[],edges:o.edges||[],name:o.name}:{nodes:[],edges:[]}};try{for(;;){let{done:l,value:i}=await r.read();if(l)break;Ec(i,s,t,a)}return a.currentData}finally{r.releaseLock()}}},Rc={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)})},Oc={get:()=>ye("/api/user"),update:e=>ye("/api/user",{method:"PATCH",body:JSON.stringify(e)})},nr={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`),download:e=>ye(`/api/workflows/${e}/download`),autoSaveCurrent:(()=>{let e=null,t=2e3;return(o,n)=>{e&&clearTimeout(e),e=setTimeout(()=>{nr.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 nr.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{nr.update(o,n).catch(s=>{console.error("Auto-save failed:",s)})},t)}})()},Lc={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"})},q={ai:Dc,aiGateway:Lc,integration:Rc,user:Oc,workflow:nr};import{atom as An}from"jotai";var mt=An([]),rr=An(!1),hv=An(null),Pt=An(0),_s=An(e=>{let t=e(mt);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as Mc,applyNodeChanges as Fc}from"@xyflow/react";import{atom as ae}from"jotai";var oe=ae([]),ue=ae([]),be=ae(null),_e=ae(null),Ks=ae(!1),$s=ae(!1),wt=ae(!1),$e=ae(null),pt=ae(""),ar=ae("private"),Xt=ae(!0),Ft=ae("properties"),sr=ae(!1),Qt=ae(null),ir=ae(null),lr=ae(!1),dr=ae(!1),js=ae(!1),cr=ae(!1),ur=ae(new Set),Jt=ae(null),mr=ae(!1),pr=ae({}),ya=null,zc=1e3,Lt=ae(null,async(e,t,o)=>{let n=e($e),r=e(oe),s=e(ue);if(!n)return;let a=async()=>{try{await q.workflow.update(n,{nodes:r,edges:s}),t(tt,!1)}catch(l){console.error("Autosave failed:",l)}};o?.immediate?await a():(ya&&clearTimeout(ya),ya=setTimeout(a,zc))}),qs=ae(null,(e,t,o)=>{let n=e(oe),r=o.filter(d=>d.type==="remove"?n.find(u=>u.id===d.id)?.data.type!=="trigger":!0),s=Fc(r,n);t(oe,s);let a=s.find(d=>d.selected);if(a){t(be,a.id),t(_e,null);let d=e(Jt);d&&d!==a.id&&t(Jt,null)}else if(e(be)){let d=e(be);s.find(u=>u.id===d)||t(be,null),t(Jt,null)}if(r.some(d=>d.type==="remove")){t(Lt,{immediate:!0});return}r.some(d=>d.type==="position"&&d.dragging===!1)&&t(Lt)}),Ys=ae(null,(e,t,o)=>{let n=e(ue),r=Mc(o,n);t(ue,r);let s=r.find(l=>l.selected);if(s)t(_e,s.id),t(be,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})}),Vo=ae(null,(e,t,o)=>{let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]),t(Mt,[]);let a=n.map(d=>({...d,selected:!1})),l={...o,selected:!0},i=[...a,l];t(oe,i),t(be,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(Jt,o.id),t(tt,!0),t(Lt,{immediate:!0})}),Zt=ae(null,(e,t,{id:o,data:n})=>{let r=e(oe),a=r.find(c=>c.id===o)?.data.label,l=n.label,i=l!==void 0&&a!==l,d=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(i&&a){let u=Js(c.data.config||{},o,a,l);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(oe,d),n.status||(t(tt,!0),t(Lt))});function Js(e,t,o,n){let r=!1,s={};for(let[a,l]of Object.entries(e))if(typeof l=="string"){let i=new RegExp(`\\{\\{@${Us(t)}:${Us(o)}(\\.[^}]+)?\\}\\}`,"g"),d=l.replace(i,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));s[a]=d}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let i=Js(l,t,o,n);i!==l&&(r=!0),s[a]=i}else s[a]=l;return r?s:e}function Us(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var eo=ae(null,(e,t,o)=>{let n=e(oe);if(n.find(d=>d.id===o)?.data.type==="trigger")return;let s=e(ue),a=e(et);t(et,[...a,{nodes:n,edges:s}]),t(Mt,[]);let l=n.filter(d=>d.id!==o),i=s.filter(d=>d.source!==o&&d.target!==o);t(oe,l),t(ue,i),e(be)===o&&t(be,null),t(tt,!0),t(Lt,{immediate:!0})}),to=ae(null,(e,t,o)=>{let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]),t(Mt,[]);let a=r.filter(l=>l.id!==o);t(ue,a),e(_e)===o&&t(_e,null),t(tt,!0),t(Lt,{immediate:!0})}),Xs=ae(null,(e,t)=>{let o=e(oe),n=e(ue),r=e(et);t(et,[...r,{nodes:o,edges:n}]),t(Mt,[]);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),l=n.filter(i=>!(i.selected||s.includes(i.source)||s.includes(i.target)));t(oe,a),t(ue,l),t(be,null),t(_e,null),t(tt,!0),t(Lt,{immediate:!0})}),fr=ae(null,(e,t)=>{let o=e(oe),n=e(ue),r=e(et);t(et,[...r,{nodes:o,edges:n}]),t(Mt,[]),t(oe,[]),t(ue,[]),t(be,null),t(_e,null),t(tt,!0)}),kv=ae(null,async(e,t)=>{try{t($s,!0);let o=await q.workflow.getCurrent();t(oe,o.nodes),t(ue,o.edges),o.id&&t($e,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t($s,!1)}}),Cv=ae(null,async(e,t,{name:o,description:n})=>{let r=e(oe),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}}),Qs=ae(!1),Zs=ae(!1),gr=ae(!1),tt=ae(!1),ei=ae(!1),et=ae([]),Mt=ae([]),ti=ae(null,(e,t)=>{let o=e(et);if(o.length===0)return;let n=e(oe),r=e(ue),s=e(Mt);t(Mt,[...s,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(et,a),t(oe,l.nodes),t(ue,l.edges),t(tt,!0))}),oi=ae(null,(e,t)=>{let o=e(Mt);if(o.length===0)return;let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(Mt,a),t(oe,l.nodes),t(ue,l.edges),t(tt,!0))}),ni=ae(e=>e(et).length>0),ri=ae(e=>e(Mt).length>0),yr=ae(null,(e,t)=>{let n=e(oe).map(r=>({...r,data:{...r.data,status:"idle"}}));t(oe,n)});import*as vr from"react";var va=768;function zt(){let[e,t]=vr.useState(void 0);return vr.useEffect(()=>{let o=window.matchMedia(`(max-width: ${va-1}px)`),n=()=>{t(window.innerWidth<va)};return o.addEventListener("change",n),t(window.innerWidth<va),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as Wc}from"radix-ui";import{cva as Bc}from"class-variance-authority";import{jsx as Vc}from"react/jsx-runtime";var hr=Bc("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 O({className:e,variant:t,size:o,asChild:n=!1,...r}){let s=n?Wc.Slot:"button";return Vc(s,{"data-slot":"button",className:x(hr({variant:t,size:o,className:e})),...r})}var Gc={"Database Query":"database"};function Hc(e){return pe(e)?.integration||Gc[e]}function ai(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=Hc(n);if(!r)return null;let s=e.data.config?.integrationId;if(s&&o.has(s))return null;let l=t.filter(i=>i.type===r);return l.length===1?{nodeId:e.id,newIntegrationId:l[0].id}:l.length===0&&s?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as io,useAtomValue as Ya,useSetAtom as lo}from"jotai";import{Copy as xl,Eraser as Ja,Eye as Tp,EyeOff as Ap,FileCode as Nl,RefreshCw as kl,Trash2 as jr}from"lucide-react";import{useCallback as Sp,useEffect as Cl,useMemo as Ip,useRef as Tl,useState as Bn}from"react";import{toast as Kr}from"sonner";import{AlertDialog as oo}from"radix-ui";import{jsx as Et,jsxs as Uc}from"react/jsx-runtime";function Go({...e}){return Et(oo.Root,{"data-slot":"alert-dialog",...e})}function _c({...e}){return Et(oo.Portal,{"data-slot":"alert-dialog-portal",...e})}function $c({className:e,...t}){return Et(oo.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 Ho({className:e,...t}){return Uc(_c,{children:[Et($c,{}),Et(oo.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 _o({className:e,...t}){return Et("div",{"data-slot":"alert-dialog-header",className:x("flex flex-col gap-2 text-center sm:text-left",e),...t})}function $o({className:e,...t}){return Et("div",{"data-slot":"alert-dialog-footer",className:x("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Uo({className:e,...t}){return Et(oo.Title,{"data-slot":"alert-dialog-title",className:x("text-lg font-semibold",e),...t})}function Ko({className:e,...t}){return Et(oo.Description,{"data-slot":"alert-dialog-description",className:x("text-muted-foreground text-sm",e),...t})}function jo({className:e,...t}){return Et(oo.Action,{className:x(hr(),e),...t})}function qo({className:e,...t}){return Et(oo.Cancel,{className:x(hr({variant:"outline"}),e),...t})}import Kc from"@monaco-editor/react";import{useTheme as jc}from"next-themes";var si={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 qc}from"react/jsx-runtime";function ft(e){let{resolvedTheme:t}=jc();return qc(Kc,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",si),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as Yc}from"react/jsx-runtime";function se({className:e,type:t,...o}){return Yc("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 Jc}from"radix-ui";import{jsx as Xc}from"react/jsx-runtime";function F({className:e,...t}){return Xc(Jc.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 br}from"radix-ui";import{jsx as wr}from"react/jsx-runtime";function ha({className:e,...t}){return wr(br.Root,{"data-slot":"tabs",className:x("flex flex-col gap-2",e),...t})}function ba({className:e,...t}){return wr(br.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 vo({className:e,...t}){return wr(br.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 ho({className:e,...t}){return wr(br.Content,{"data-slot":"tabs-content",className:x("flex-1 outline-none",e),...t})}import{useAtomValue as Ji,useSetAtom as xm}from"jotai";import{HelpCircle as Nm,Plus as km,Settings as Cm}from"lucide-react";import{useEffect as Tm,useMemo as Lr,useState as Am}from"react";import{Select as ot}from"radix-ui";import{CheckIcon as Qc,ChevronDownIcon as ii,ChevronUpIcon as Zc}from"lucide-react";import{jsx as ze,jsxs as wa}from"react/jsx-runtime";function ke({...e}){return ze(ot.Root,{"data-slot":"select",...e})}function li({...e}){return ze(ot.Group,{"data-slot":"select-group",...e})}function Ce({...e}){return ze(ot.Value,{"data-slot":"select-value",...e})}function Te({className:e,size:t="default",children:o,...n}){return wa(ot.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,ze(ot.Icon,{asChild:!0,children:ze(ii,{className:"size-4 opacity-50"})})]})}function Ae({className:e,children:t,position:o="popper",align:n="center",...r}){return ze(ot.Portal,{children:wa(ot.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:[ze(eu,{}),ze(ot.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}),ze(tu,{})]})})}function di({className:e,...t}){return ze(ot.Label,{"data-slot":"select-label",className:x("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function ie({className:e,children:t,...o}){return wa(ot.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:[ze("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:ze(ot.ItemIndicator,{children:ze(Qc,{className:"size-4"})})}),ze(ot.ItemText,{children:t})]})}function xr({className:e,...t}){return ze(ot.Separator,{"data-slot":"select-separator",className:x("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function eu({className:e,...t}){return ze(ot.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:ze(Zc,{className:"size-4"})})}function tu({className:e,...t}){return ze(ot.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:ze(ii,{className:"size-4"})})}import{useAtom as mi}from"jotai";import{useEffect as xa,useRef as Na,useState as Yo}from"react";import{useAtom as ci}from"jotai";import{Check as ou}from"lucide-react";import{useEffect as Nr,useRef as nu,useState as ui}from"react";import{createPortal as ru}from"react-dom";import{Fragment as lu,jsx as Sn,jsxs as kr}from"react/jsx-runtime";var au=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=pe(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},In=(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(...In(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let l=`${r}[0]`;o.push(...In(n.fields,l))}}return o},su=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,iu=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 In(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(su(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 In(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=pe(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 In(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 Cr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:s=""}){let[a]=ci(oe),[l]=ci(ue),[i,d]=ui(0),c=nu(null),[u,p]=ui(!1);Nr(()=>(p(!0),()=>p(!1)),[]);let T=(()=>{if(!r)return[];let f=new Set,A=[],I=C=>{if(f.has(C))return;f.add(C);let h=l.filter(m=>m.target===C);for(let m of h)A.push(m.source),I(m.source)};return I(r),a.filter(C=>A.includes(C.id))})(),v=[];for(let f of T){let A=au(f),I=iu(f);v.push({type:"node",nodeId:f.id,nodeName:A,template:`{{@${f.id}:${A}}}`});for(let C of I)v.push({type:"field",nodeId:f.id,nodeName:A,field:C.field,description:C.description,template:`{{@${f.id}:${A}.${C.field}}}`})}let y=s?v.filter(f=>f.nodeName.toLowerCase().includes(s.toLowerCase())||f.field&&f.field.toLowerCase().includes(s.toLowerCase())):v;if(Nr(()=>{d(0)},[s]),Nr(()=>{let f=A=>{if(e)switch(A.key){case"ArrowDown":A.preventDefault(),d(I=>I<y.length-1?I+1:I);break;case"ArrowUp":A.preventDefault(),d(I=>I>0?I-1:I);break;case"Enter":A.preventDefault(),y[i]&&o(y[i].template);break;case"Escape":A.preventDefault(),n();break}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,y,i,o,n]),Nr(()=>{if(c.current){let f=c.current.children[i];f&&f.scrollIntoView({block:"nearest"})}},[i]),!e||y.length===0||!u)return null;let w={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},k=Sn("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${w.top}px`,left:`${w.left}px`},children:Sn("div",{className:"max-h-60 overflow-y-auto",children:y.map((f,A)=>kr("div",{className:x("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",A===i?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(f.template),onMouseEnter:()=>d(A),children:[kr("div",{className:"flex-1",children:[Sn("div",{className:"font-medium",children:f.type==="node"?f.nodeName:kr(lu,{children:[kr("span",{className:"text-muted-foreground",children:[f.nodeName,"."]}),f.field]})}),f.description&&Sn("div",{className:"text-muted-foreground text-xs",children:f.description})]}),A===i&&Sn(ou,{className:"h-4 w-4"})]},`${f.nodeId}-${f.field||"root"}`))})});return ru(k,document.body)}import{Fragment as uu,jsx as ka,jsxs as mu}from"react/jsx-runtime";function du(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function cu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(d=>d.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let d=s.data.config?.actionType;d&&(a=pe(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let i=r.substring(l+1);return a?`${a}.${i}`:r}function We({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s}){let[a,l]=Yo(!1),i=Na(null),[d,c]=Yo(e),u=Na(!0),[p]=mi(be),[g]=mi(oe),[T,v]=Yo(!1),[y,w]=Yo({top:0,left:0}),[k,f]=Yo(""),[A,I]=Yo(null),C=Na(null);xa(()=>{e!==d&&!a&&(c(e),u.current=!0)},[e,a,d]),xa(()=>{!a&&d&&(u.current=!0)},[g,a,d]);let h=()=>{if(!i.current)return null;let V=window.getSelection();if(!V||V.rangeCount===0)return null;let X=V.getRangeAt(0),W=X.cloneRange();W.selectNodeContents(i.current),W.setEnd(X.endContainer,X.endOffset);let U=0,N=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),M,b=!1;for(;(M=N.nextNode())&&!b;)if(M.nodeType===Node.TEXT_NODE)if(M===X.endContainer)U+=X.endOffset,b=!0;else{let R=(M.textContent||"").length;U+=R}else if(M.nodeType===Node.ELEMENT_NODE){let R=M,G=R.getAttribute("data-template");G&&(R.contains(X.endContainer)||R===X.endContainer?(U+=G.length,b=!0):U+=G.length)}return{offset:U}},m=V=>{if(!i.current||!V)return;let X=0,W=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),U,N=null,M=0;for(;U=W.nextNode();)if(U.nodeType===Node.TEXT_NODE){let b=(U.textContent||"").length;if(X+b>=V.offset){N=U,M=V.offset-X;break}X+=b}else if(U.nodeType===Node.ELEMENT_NODE){let b=U,R=b.getAttribute("data-template");if(R){if(X+R.length>=V.offset){N=b.nextSibling,M=0,!N&&b.parentNode&&(N=document.createTextNode(""),b.parentNode.appendChild(N));break}X+=R.length}}if(N){let b=document.createRange(),R=window.getSelection();try{let G=Math.min(M,N.textContent?.length||0);b.setStart(N,G),b.collapse(!0),R?.removeAllRanges(),R?.addRange(b),i.current.focus()}catch{i.current.focus()}}},S=()=>{if(!i.current||!u.current)return;let V=i.current,X=d||"",W=a?h():null;if(C.current!==null&&(W={offset:C.current},C.current=null),V.innerHTML="",!X&&!a){V.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let U=/\{\{@([^:]+):([^}]+)\}\}/g,N=0,M;for(;(M=U.exec(X))!==null;){let[b]=M,R=M.index;if(R>N){let de=X.slice(N,R),B=document.createTextNode(de);V.appendChild(B)}let G=document.createElement("span"),te=du(b,g);G.className=te?"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",b),G.textContent=cu(b,g),V.appendChild(G),N=U.lastIndex}if(N<X.length){let b=X.slice(N),R=document.createTextNode(b);V.appendChild(R)}V.innerHTML===""&&a&&(V.innerHTML="<br>"),u.current=!1,W&&requestAnimationFrame(()=>m(W))},J=()=>{if(!i.current)return"";let V="",X=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),W;for(;W=X.nextNode();)if(W.nodeType===Node.TEXT_NODE){let U=W.parentElement,N=!1;for(;U&&U!==i.current;){if(U.getAttribute("data-template")){N=!0;break}U=U.parentElement}N||(V+=W.textContent)}else if(W.nodeType===Node.ELEMENT_NODE){let N=W.getAttribute("data-template");N&&(V+=N)}return V},D=()=>{let V=J();if(V===d)return;let X=(d.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,W=(V.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(W>X){c(V),t?.(V),u.current=!0,v(!1),requestAnimationFrame(()=>S());return}if(W===X&&W>0){c(V),t?.(V);let N=V.lastIndexOf("@");if(N!==-1){let M=V.slice(N+1);if(M.includes(" "))v(!1);else{if(f(M),I(N),i.current){let b=i.current.getBoundingClientRect(),R={top:b.bottom+window.scrollY+4,left:b.left+window.scrollX};w(R)}v(!0)}}else v(!1);return}if(W<X){c(V),t?.(V),u.current=!0,requestAnimationFrame(()=>S());return}c(V),t?.(V);let U=V.lastIndexOf("@");if(U!==-1){let N=V.slice(U+1);if(N.includes(" "))v(!1);else{if(f(N),I(U),i.current){let M=i.current.getBoundingClientRect(),b={top:M.bottom+window.scrollY+4,left:M.left+window.scrollX};w(b)}v(!0)}}else v(!1)},j=V=>{if(!i.current||A===null)return;let X=J(),W=X.slice(0,A),U=X.slice(A+1+k.length),N=W+V+U,M=W.length+V.length;c(N),t?.(N),u.current=!0,v(!1),I(null),C.current=M,i.current.focus()},z=()=>{l(!0),u.current=!0},re=()=>{setTimeout(()=>{document.activeElement!==i.current&&(l(!1),u.current=!0,v(!1))},200)},P=V=>{V.preventDefault();let X=V.clipboardData.getData("text/plain");document.execCommand("insertText",!1,X)};return xa(()=>{u.current&&S()},[d,a]),mu(uu,{children:[ka("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:ka("div",{className:"w-full outline-none",contentEditable:!n,id:s,onBlur:re,onFocus:z,onInput:D,onPaste:P,ref:i,role:"textbox",suppressContentEditableWarning:!0})}),ka(Cr,{currentNodeId:p||void 0,filter:k,isOpen:T,onClose:()=>v(!1),onSelect:j,position:y})]})}import{jsx as nt,jsxs as bo}from"react/jsx-runtime";function pi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.dataType||"string",r=e?.operator||or[n][0].value,s=or[n],l=s.find(d=>d.value===r)?.unary??!1;function i(d){t("dataType",d);let c=or[d];c?.[0]&&t("operator",c[0].value)}return bo("div",{className:"space-y-4",children:[bo("div",{className:"space-y-2",children:[nt(F,{htmlFor:"leftValue",children:"Value to Test"}),nt(We,{disabled:o,id:"leftValue",onChange:d=>t("leftValue",d),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),nt("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),bo("div",{className:"space-y-2",children:[nt(F,{htmlFor:"dataType",children:"Data Type"}),bo(ke,{disabled:o,onValueChange:i,value:n,children:[nt(Te,{id:"dataType",children:nt(Ce,{placeholder:"Select data type"})}),nt(Ae,{children:Hs.map(d=>nt(ie,{value:d.value,children:d.label},d.value))})]})]}),bo("div",{className:"space-y-2",children:[nt(F,{htmlFor:"operator",children:"Operator"}),bo(ke,{disabled:o,onValueChange:d=>t("operator",d),value:r,children:[nt(Te,{id:"operator",children:nt(Ce,{placeholder:"Select operator"})}),nt(Ae,{children:s.map(d=>nt(ie,{value:d.value,children:d.label},d.value))})]})]}),!l&&bo("div",{className:"space-y-2",children:[nt(F,{htmlFor:"rightValue",children:"Compare Value"}),nt(We,{disabled:o,id:"rightValue",onChange:d=>t("rightValue",d),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as pu,Trash2 as fu}from"lucide-react";import{nanoid as gu}from"nanoid";import{jsx as we,jsxs as lt}from"react/jsx-runtime";function no({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:gu(),name:"",type:"string"}])},s=(c,u)=>{let p={...c};return u!=="array"&&(p.itemType=void 0),u!=="object"&&(p.fields=void 0),u==="array"&&!p.itemType&&(p.itemType="string"),u==="object"&&!p.fields&&(p.fields=[]),p},a=(c,u)=>{let p=[...e];p[c]={...p[c],...u},u.type&&(p[c]=s(p[c],u.type)),t(p)},l=c=>{t(e.filter((u,p)=>p!==c))},i=(c,u)=>{let p=[...e];p[c].fields=u,t(p)},d=n>0?"ml-4 border-l-2 border-muted pl-4":"";return lt("div",{className:`space-y-3 ${d}`,children:[e.map((c,u)=>{let p=c.id||`field-${n}-${u}`;return lt("div",{className:"space-y-2 rounded-md border p-3",children:[lt("div",{className:"flex gap-2",children:[lt("div",{className:"flex-1 space-y-2",children:[we(F,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),we(se,{disabled:o,id:`field-name-${n}-${u}`,onChange:g=>a(u,{name:g.target.value}),placeholder:"propertyName",value:c.name})]}),lt("div",{className:"flex-1 space-y-2",children:[we(F,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),lt(ke,{disabled:o,onValueChange:g=>a(u,{type:g}),value:c.type,children:[we(Te,{className:"w-full",id:`field-type-${n}-${u}`,children:we(Ce,{})}),lt(Ae,{children:[we(ie,{value:"string",children:"String"}),we(ie,{value:"number",children:"Number"}),we(ie,{value:"boolean",children:"Boolean"}),we(ie,{value:"array",children:"Array"}),we(ie,{value:"object",children:"Object"})]})]})]}),we("div",{className:"flex items-end",children:we(O,{disabled:o,onClick:()=>l(u),size:"icon",variant:"ghost",children:we(fu,{className:"h-4 w-4"})})})]}),c.type==="array"&<("div",{className:"space-y-2",children:[we(F,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),lt(ke,{disabled:o,onValueChange:g=>a(u,{itemType:g}),value:c.itemType||"string",children:[we(Te,{className:"w-full",id:`field-item-type-${n}-${u}`,children:we(Ce,{})}),lt(Ae,{children:[we(ie,{value:"string",children:"String"}),we(ie,{value:"number",children:"Number"}),we(ie,{value:"boolean",children:"Boolean"}),we(ie,{value:"object",children:"Object"})]})]})]}),c.type==="object"&<("div",{className:"mt-2",children:[we(F,{className:"mb-2 block",children:"Object Properties"}),we(no,{disabled:o,level:n+1,onChange:g=>i(u,g),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&<("div",{className:"mt-2",children:[we(F,{className:"mb-2 block",children:"Array Item Properties"}),we(no,{disabled:o,level:n+1,onChange:g=>i(u,g),schema:c.fields||[]})]}),lt("div",{className:"space-y-2",children:[we(F,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),we(se,{disabled:o,id:`field-desc-${n}-${u}`,onChange:g=>a(u,{description:g.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},p)}),lt(O,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[we(pu,{className:"size-4"}),"Add Property"]})]})}import{Fragment as yu,jsx as Jo,jsxs as Ca}from"react/jsx-runtime";function fi({config:e,onUpdateConfig:t,disabled:o}){return Ca(yu,{children:[Ca("div",{className:"space-y-2",children:[Jo(F,{htmlFor:"dbQuery",children:"SQL Query"}),Jo("div",{className:"overflow-hidden rounded-md border",children:Jo(ft,{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||""})}),Jo("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),Ca("div",{className:"space-y-2",children:[Jo(F,{children:"Schema (Optional)"}),Jo(no,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as vu,jsx as Ue,jsxs as wo}from"react/jsx-runtime";function gi({config:e,onUpdateConfig:t,disabled:o}){return wo(vu,{children:[wo("div",{className:"space-y-2",children:[Ue(F,{htmlFor:"httpMethod",children:"HTTP Method"}),wo(ke,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[Ue(Te,{className:"w-full",id:"httpMethod",children:Ue(Ce,{placeholder:"Select method"})}),wo(Ae,{children:[Ue(ie,{value:"GET",children:"GET"}),Ue(ie,{value:"POST",children:"POST"}),Ue(ie,{value:"PUT",children:"PUT"}),Ue(ie,{value:"PATCH",children:"PATCH"}),Ue(ie,{value:"DELETE",children:"DELETE"})]})]})]}),wo("div",{className:"space-y-2",children:[Ue(F,{htmlFor:"endpoint",children:"URL"}),Ue(We,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),wo("div",{className:"space-y-2",children:[Ue(F,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),Ue("div",{className:"overflow-hidden rounded-md border",children:Ue(ft,{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||"{}"})})]}),wo("div",{className:"space-y-2",children:[Ue(F,{htmlFor:"httpBody",children:"Body (JSON)"}),Ue("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:Ue(ft,{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"&&Ue("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as Xo,jsxs as Ta}from"react/jsx-runtime";function yi({config:e,onUpdateConfig:t,disabled:o}){return Ta("div",{className:"space-y-4",children:[Ta("div",{className:"space-y-2",children:[Xo(F,{htmlFor:"items",children:"Items to Iterate"}),Xo(We,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),Xo("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),Ta("div",{className:"space-y-2",children:[Xo(F,{htmlFor:"batchSize",children:"Batch Size (optional)"}),Xo(We,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),Xo("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 hu,jsx as ge,jsxs as Je}from"react/jsx-runtime";function vi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append";return Je("div",{className:"space-y-4",children:[Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"mode",children:"Mode"}),Je(ke,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[ge(Te,{id:"mode",children:ge(Ce,{placeholder:"Select mode"})}),Je(Ae,{children:[ge(ie,{value:"append",children:"Append"}),ge(ie,{value:"combineByPosition",children:"Combine by Position"}),ge(ie,{value:"combineByFields",children:"Combine by Fields"})]})]}),Je("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."]})]}),Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"input1",children:"Input 1"}),ge(We,{disabled:o,id:"input1",onChange:r=>t("input1",r),placeholder:"e.g., {{PreviousNode.rows}}",value:e?.input1||""}),ge("p",{className:"text-muted-foreground text-xs",children:"First array to merge. Use @ to reference outputs from previous nodes."})]}),Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"input2",children:"Input 2"}),ge(We,{disabled:o,id:"input2",onChange:r=>t("input2",r),placeholder:"e.g., {{AnotherNode.results}}",value:e?.input2||""}),ge("p",{className:"text-muted-foreground text-xs",children:"Second array to merge. Use @ to reference outputs from previous nodes."})]}),n==="combineByPosition"&&Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),Je(ke,{disabled:o,onValueChange:r=>t("unmatchedHandling",r),value:e?.unmatchedHandling||"useNull",children:[ge(Te,{id:"unmatchedHandling",children:ge(Ce,{})}),Je(Ae,{children:[ge(ie,{value:"useNull",children:"Fill with null"}),ge(ie,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&Je(hu,{children:[Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"matchField1",children:"Match Field (Input 1)"}),ge(We,{disabled:o,id:"matchField1",onChange:r=>t("matchField1",r),placeholder:"e.g., id",value:e?.matchField1||""}),ge("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 1 to match on."})]}),Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"matchField2",children:"Match Field (Input 2)"}),ge(We,{disabled:o,id:"matchField2",onChange:r=>t("matchField2",r),placeholder:"e.g., id",value:e?.matchField2||""}),ge("p",{className:"text-muted-foreground text-xs",children:"Field name in Input 2 to match on."})]}),Je("div",{className:"space-y-2",children:[ge(F,{htmlFor:"joinType",children:"Join Type"}),Je(ke,{disabled:o,onValueChange:r=>t("joinType",r),value:e?.joinType||"inner",children:[ge(Te,{id:"joinType",children:ge(Ce,{})}),Je(Ae,{children:[ge(ie,{value:"inner",children:"Inner Join"}),ge(ie,{value:"leftOuter",children:"Left Outer Join"}),ge(ie,{value:"rightOuter",children:"Right Outer Join"}),ge(ie,{value:"fullOuter",children:"Full Outer Join"})]})]}),ge("p",{className:"text-muted-foreground text-xs",children:"Inner keeps only matches. Left/Right keeps all items from that input. Full keeps everything."})]})]})]})}import{jsx as rt,jsxs as Dt}from"react/jsx-runtime";function hi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules";return Dt("div",{className:"space-y-4",children:[Dt("div",{className:"space-y-2",children:[rt(F,{htmlFor:"mode",children:"Mode"}),Dt(ke,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[rt(Te,{id:"mode",children:rt(Ce,{placeholder:"Select mode"})}),Dt(Ae,{children:[rt(ie,{value:"rules",children:"Rules"}),rt(ie,{value:"expression",children:"Expression"})]})]}),Dt("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"&&Dt("div",{className:"space-y-2",children:[rt(F,{htmlFor:"switchValue",children:"Value to Switch On"}),rt(We,{disabled:o,id:"switchValue",onChange:r=>t("switchValue",r),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),rt("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=>Dt("div",{className:"space-y-3 rounded-md border p-3",children:[Dt("p",{className:"font-medium text-sm",children:["Route ",r+1]}),Dt("div",{className:"space-y-2",children:[rt(F,{htmlFor:`routeName${r}`,children:"Name (optional)"}),rt(se,{disabled:o,id:`routeName${r}`,onChange:s=>t(`routeName${r}`,s.target.value),placeholder:`Route ${r+1}`,value:e?.[`routeName${r}`]||""})]}),n==="rules"&&Dt("div",{className:"space-y-2",children:[rt(F,{htmlFor:`routeCondition${r}`,children:"Condition"}),rt(We,{disabled:o,id:`routeCondition${r}`,onChange:s=>t(`routeCondition${r}`,s),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${r}`]||""})]}),n==="expression"&&Dt("div",{className:"space-y-2",children:[rt(F,{htmlFor:`routeCaseValue${r}`,children:"Case Value"}),rt(We,{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)),rt("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 Tr}from"jotai";var Ar=Tr(null),bi=Tr([]),wi=Tr(!1),mb=Tr(!1);import{useAtomValue as Li,useSetAtom as Ea}from"jotai";import{Search as Lu}from"lucide-react";import{useCallback as Mu,useMemo as Fu,useState as tn}from"react";import{toast as ko}from"sonner";import{atom as Pn,useSetAtom as bu}from"jotai";import*as Ni from"react";var xi=null;var xo=Pn(null),Sr=Pn([]),Ir=Pn(!1),ki=Pn(!1),Ht=Pn(null);function Ci(){let e=bu(Ht);Ni.useEffect(()=>{xi&&e(xi)},[e])}import{Database as wu,HelpCircle as xu}from"lucide-react";import{jsx as En}from"react/jsx-runtime";function Nu({className:e}){return En("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:En("path",{d:"m577.3 0 577.4 1000H0z"})})}var ku={database:wu,vercel:Nu};function Rt({integration:e,className:t="h-3 w-3"}){let o=ku[e];if(o)return En(o,{className:x("text-foreground",t)});let n=It(e);if(n?.icon){let r=n.icon;return En(r,{className:x("text-foreground",t)})}return En(xu,{className:x("text-foreground",t)})}import{AlertTriangleIcon as Ru}from"lucide-react";import{Loader2 as Cu}from"lucide-react";import{jsx as Qo,jsxs as Sa}from"react/jsx-runtime";function Aa({action:e}){return Sa(O,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&Qo(Cu,{className:"mr-2 size-4 animate-spin"}),e.label]})}function Ti({actions:e,className:t,children:o}){if(o)return Qo("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,l=r.length>0||s.length>0;return Sa("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&l?"sm:justify-between":"sm:justify-end",t),children:[a&&Qo("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(i=>Qo(Aa,{action:i},i.label))}),l&&Sa("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(i=>Qo(Aa,{action:i},i.label)),s.map(i=>Qo(Aa,{action:i},i.label))]})]})}import{ChevronLeftIcon as Iu,XIcon as Pu}from"lucide-react";import{createContext as Si,useCallback as Zo,useContext as Ii,useMemo as Tu,useRef as Au,useState as Su}from"react";import{jsx as Ai}from"react/jsx-runtime";var Pi=Si(null),Ei=Si([]);function Ia(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Di({children:e}){let[t,o]=Su([]),n=Au([]);t.length>0&&(n.current=t);let r=Zo((u,p,g)=>{let T=Ia();return o([{id:T,component:u,props:p??{},options:g??{}}]),T},[]),s=Zo((u,p,g)=>{let T=Ia(),v={id:T,component:u,props:p??{},options:g??{}};return o(y=>[...y,v]),T},[]),a=Zo(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),l=Zo((u,p,g)=>{let T=Ia(),v={id:T,component:u,props:p??{},options:g??{}};return o(y=>y.length===0?[v]:(y[y.length-1]?.options.onClose?.(),[...y.slice(0,-1),v])),T},[]),i=Zo(()=>{o(u=>{for(let p of u)p.options.onClose?.();return[]})},[]),d=Zo(u=>{o(p=>{let g=p.findIndex(T=>T.id===u);if(g===-1)return p;for(let T=g;T<p.length;T++)p[T].options.onClose?.();return p.slice(0,g)})},[]),c=Tu(()=>({stack:t,open:r,push:s,pop:a,replace:l,closeAll:i,close:d,hasOverlays:t.length>0,depth:t.length}),[t,r,s,a,l,i,d]);return Ai(Pi.Provider,{value:c,children:Ai(Ei.Provider,{value:n.current,children:e})})}function ne(){let e=Ii(Pi);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function Ri(e){let{stack:t}=ne(),o=Ii(Ei),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 No,jsxs as Oi}from"react/jsx-runtime";function Eu({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:s,className:a}){let{pop:l,closeAll:i}=ne(),d=o??!1,c=()=>{r?r():l()},u=()=>{s?s():i()};return Oi("div",{className:x("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[Oi("div",{className:"flex min-h-8 items-center gap-2",children:[d&&No(O,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:No(Iu,{className:"size-5"})}),e&&No("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&No(O,{"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:No(Pu,{className:"size-4"})})]}),t&&No("p",{className:"text-muted-foreground text-sm",children:t})]})}function en({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=Ri(e);return No(Eu,{...o,showBackButton:t??n})}import{jsx as Pa,jsxs as Du}from"react/jsx-runtime";function De({overlayId:e,title:t,description:o,actions:n,children:r,className:s}){return Du("div",{className:x("flex flex-col",s),children:[(t||o)&&Pa(en,{description:o,overlayId:e,title:t}),r&&Pa("div",{className:"flex-1 overflow-y-auto p-6",children:r}),Pa(Ti,{actions:n})]})}import{jsx as Pr,jsxs as Ou}from"react/jsx-runtime";function Oe({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:s="default",destructive:a=!1,onConfirm:l,onCancel:i}){let{pop:d}=ne();return Pr(De,{actions:[{label:r,variant:"outline",onClick:()=>{i?.(),d()}},{label:n,variant:a?"destructive":s,onClick:async()=>{await l(),d()}}],overlayId:e,title:t,children:Ou("div",{className:"flex gap-4",children:[a&&Pr("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Pr(Ru,{className:"size-5 text-destructive"})}),Pr("p",{className:x("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{jsx as Ve,jsxs as gt}from"react/jsx-runtime";var zu=["database"],Wu={database:"Database"},Bu={database:"Connect to PostgreSQL databases"},Vu=()=>[...Vs(),...zu],Da=e=>Yt()[e]||Wu[e]||e,Gu=e=>Bs()[e]||Bu[e]||"";function Fi({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=ne(),[r,s]=tn(""),a=zt(),l=Li(Ht),i=Li(xo),d=Ea(xo),c=Ea(Sr),u=Ea(Ir),p=Vu(),g=Fu(()=>{if(!r.trim())return p;let y=r.toLowerCase();return p.filter(w=>Da(w).toLowerCase().includes(y))},[p,r]),T=Mu(()=>{l&&o(l.ConsentOverlay,{onConsent:y=>{t?.(y),n()}})},[l,o,n,t]),v=y=>{let w=l?.integrationType===y;if(w&&i?.enabled&&i?.isVercelUser){T();return}if(w&&i===null){l.api.getStatus().then(f=>{d(f),f?.enabled&&f?.isVercelUser?(u(!0),l.api.getTeams().then(A=>{c(A.teams)}).finally(()=>{u(!1),T()})):o(ro,{type:y,onSuccess:t})});return}o(ro,{type:y,onSuccess:t})};return gt(De,{overlayId:e,title:"Add Connection",children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),gt("div",{className:"space-y-3",children:[gt("div",{className:"relative",children:[Ve(Lu,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ve(se,{autoFocus:!a,className:"pl-9",onChange:y=>s(y.target.value),placeholder:"Search services...",value:r})]}),Ve("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:g.length===0?Ve("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):g.map(y=>{let w=Gu(y);return gt("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:()=>v(y),type:"button",children:[Ve(Rt,{className:"size-5 shrink-0",integration:y==="ai-gateway"?"vercel":y}),gt("span",{className:"min-w-0 flex-1 truncate",children:[Ve("span",{className:"font-medium",children:Da(y)}),w&>("span",{className:"text-muted-foreground text-xs",children:[" ","- ",w]})]})]},y)})})]})]})}function Mi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:l}){return gt("div",{className:"space-y-2",children:[Ve(F,{htmlFor:e,children:t}),Ve(se,{className:"flex-1",id:e,onChange:i=>l(o,i.target.value),placeholder:n,type:"password",value:a}),(r||s)&>("p",{className:"text-muted-foreground text-xs",children:[r,s&&Ve("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]})}function ro({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=ne(),[s,a]=tn(!1),[l,i]=tn(!1),[d,c]=tn(null),[u,p]=tn(""),[g,T]=tn({}),v=(C,h)=>{T(m=>({...m,[C]:h}))},y=async()=>{try{a(!0);let C=await q.integration.create({name:u.trim(),type:t,config:g});ko.success("Connection created"),o?.(C.id),r()}catch(C){console.error("Failed to save integration:",C),ko.error("Failed to save connection")}finally{a(!1)}},w=async()=>{if(!Object.values(g).some(h=>h&&h.length>0)){ko.error("Please enter credentials");return}try{a(!0),c(null);let h=await q.integration.testCredentials({type:t,config:g});if(h.status==="error"){n(Oe,{title:"Connection Test Failed",message:`The test failed: ${h.message}
|
|
1
|
+
"use client";import{a as zo,b as Wo,c as Bo}from"../chunk-NI6U7PHC.js";import{i as or,k as Hs,l as nr}from"../chunk-DMHGXYVW.js";import{a as x}from"../chunk-6UXAINJQ.js";import{d as Ms,h as It,i as Fs,k as zs,l as Ws,m as pe,n as Yt,o as Bs,p as Vs,v as Gs,w as fa,y as Fo}from"../chunk-QRG4O4PE.js";import{AuthView as qp}from"@daveyplate/better-auth-ui";import{useParams as Yp}from"next/navigation";import{useAtom as Bt,useAtomValue as Lp,useSetAtom as kt}from"jotai";import{ChevronLeft as Mp,ChevronRight as Fp}from"lucide-react";import zp from"next/link";import{useSearchParams as Wp}from"next/navigation";import{useCallback as uo,useEffect as Ct,useRef as Po,useState as Qa}from"react";import{toast as Za}from"sonner";var ga=class extends Error{status;constructor(t,o){super(o),this.status=t,this.name="ApiError"}};async function ge(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 ga(o.status,n.error||"Request failed")}return o.json()}function xc(e,t){e?.name&&(t.currentData.name=e.name)}function Nc(e,t){e?.description&&(t.currentData.description=e.description)}function kc(e,t){e?.node&&(t.currentData.nodes=[...t.currentData.nodes,e.node])}function Cc(e,t){e?.edge&&(t.currentData.edges=[...t.currentData.edges,e.edge])}function Tc(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 Ac(e,t){e?.edgeId&&(t.currentData.edges=t.currentData.edges.filter(o=>o.id!==e.edgeId))}function Sc(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 Ic={setName:xc,setDescription:Nc,addNode:kc,addEdge:Cc,removeNode:Tc,removeEdge:Ac,updateNode:Sc};function Pc(e,t){if(!e?.op)return;let o=Ic[e.op];o&&o(e,t)}function Ec(e,t,o){if(e.trim())try{let n=JSON.parse(e);if(n.type==="operation"&&n.operation)Pc(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 Dc(e,t,o,n){n.buffer+=t.decode(e,{stream:!0});let r=n.buffer.split(`
|
|
2
|
+
`);n.buffer=r.pop()||"";for(let s of r)Ec(s,o,n)}var Rc={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:l,value:i}=await r.read();if(l)break;Dc(i,s,t,a)}return a.currentData}finally{r.releaseLock()}}},Oc={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)})},Lc={get:()=>ge("/api/user"),update:e=>ge("/api/user",{method:"PATCH",body:JSON.stringify(e)})},rr={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(()=>{rr.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 rr.update(o,n);e&&clearTimeout(e),e=setTimeout(()=>{rr.update(o,n).catch(s=>{console.error("Auto-save failed:",s)})},t)}})()},Mc={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"})},j={ai:Rc,aiGateway:Mc,integration:Oc,user:Lc,workflow:rr};import{atom as An}from"jotai";var mt=An([]),ar=An(!1),bv=An(null),Pt=An(0),_s=An(e=>{let t=e(mt);return new Set(t.map(o=>o.id))});import{applyEdgeChanges as Fc,applyNodeChanges as zc}from"@xyflow/react";import{atom as re}from"jotai";var oe=re([]),ue=re([]),be=re(null),_e=re(null),Ks=re(!1),$s=re(!1),wt=re(!1),$e=re(null),pt=re(""),sr=re("private"),Xt=re(!0),Ft=re("properties"),ir=re(!1),Qt=re(null),lr=re(null),dr=re(!1),cr=re(!1),js=re(!1),ur=re(!1),mr=re(new Set),Jt=re(null),pr=re(!1),fr=re({}),ya=null,Wc=1e3,Lt=re(null,async(e,t,o)=>{let n=e($e),r=e(oe),s=e(ue);if(!n)return;let a=async()=>{try{await j.workflow.update(n,{nodes:r,edges:s}),t(tt,!1)}catch(l){console.error("Autosave failed:",l)}};o?.immediate?await a():(ya&&clearTimeout(ya),ya=setTimeout(a,Wc))}),qs=re(null,(e,t,o)=>{let n=e(oe),r=o.filter(d=>d.type==="remove"?n.find(u=>u.id===d.id)?.data.type!=="trigger":!0),s=zc(r,n);t(oe,s);let a=s.find(d=>d.selected);if(a){t(be,a.id),t(_e,null);let d=e(Jt);d&&d!==a.id&&t(Jt,null)}else if(e(be)){let d=e(be);s.find(u=>u.id===d)||t(be,null),t(Jt,null)}if(r.some(d=>d.type==="remove")){t(Lt,{immediate:!0});return}r.some(d=>d.type==="position"&&d.dragging===!1)&&t(Lt)}),Ys=re(null,(e,t,o)=>{let n=e(ue),r=Fc(o,n);t(ue,r);let s=r.find(l=>l.selected);if(s)t(_e,s.id),t(be,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})}),Vo=re(null,(e,t,o)=>{let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]),t(Mt,[]);let a=n.map(d=>({...d,selected:!1})),l={...o,selected:!0},i=[...a,l];t(oe,i),t(be,o.id),o.data.type==="action"&&!o.data.config?.actionType&&t(Jt,o.id),t(tt,!0),t(Lt,{immediate:!0})}),Zt=re(null,(e,t,{id:o,data:n})=>{let r=e(oe),a=r.find(c=>c.id===o)?.data.label,l=n.label,i=l!==void 0&&a!==l,d=r.map(c=>{if(c.id===o)return{...c,data:{...c.data,...n}};if(i&&a){let u=Js(c.data.config||{},o,a,l);if(u!==c.data.config)return{...c,data:{...c.data,config:u}}}return c});t(oe,d),n.status||(t(tt,!0),t(Lt))});function Js(e,t,o,n){let r=!1,s={};for(let[a,l]of Object.entries(e))if(typeof l=="string"){let i=new RegExp(`\\{\\{@${Us(t)}:${Us(o)}(\\.[^}]+)?\\}\\}`,"g"),d=l.replace(i,(c,u)=>(r=!0,`{{@${t}:${n}${u||""}}}`));s[a]=d}else if(typeof l=="object"&&l!==null&&!Array.isArray(l)){let i=Js(l,t,o,n);i!==l&&(r=!0),s[a]=i}else s[a]=l;return r?s:e}function Us(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var eo=re(null,(e,t,o)=>{let n=e(oe);if(n.find(d=>d.id===o)?.data.type==="trigger")return;let s=e(ue),a=e(et);t(et,[...a,{nodes:n,edges:s}]),t(Mt,[]);let l=n.filter(d=>d.id!==o),i=s.filter(d=>d.source!==o&&d.target!==o);t(oe,l),t(ue,i),e(be)===o&&t(be,null),t(tt,!0),t(Lt,{immediate:!0})}),to=re(null,(e,t,o)=>{let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]),t(Mt,[]);let a=r.filter(l=>l.id!==o);t(ue,a),e(_e)===o&&t(_e,null),t(tt,!0),t(Lt,{immediate:!0})}),Xs=re(null,(e,t)=>{let o=e(oe),n=e(ue),r=e(et);t(et,[...r,{nodes:o,edges:n}]),t(Mt,[]);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),l=n.filter(i=>!(i.selected||s.includes(i.source)||s.includes(i.target)));t(oe,a),t(ue,l),t(be,null),t(_e,null),t(tt,!0),t(Lt,{immediate:!0})}),gr=re(null,(e,t)=>{let o=e(oe),n=e(ue),r=e(et);t(et,[...r,{nodes:o,edges:n}]),t(Mt,[]),t(oe,[]),t(ue,[]),t(be,null),t(_e,null),t(tt,!0)}),Cv=re(null,async(e,t)=>{try{t($s,!0);let o=await j.workflow.getCurrent();t(oe,o.nodes),t(ue,o.edges),o.id&&t($e,o.id)}catch(o){console.error("Failed to load workflow:",o)}finally{t($s,!1)}}),Tv=re(null,async(e,t,{name:o,description:n})=>{let r=e(oe),s=e(ue);try{return await j.workflow.create({name:o,description:n,nodes:r,edges:s})}catch(a){throw console.error("Failed to save workflow:",a),a}}),Qs=re(!1),Zs=re(!1),yr=re(!1),tt=re(!1),ei=re(!1),et=re([]),Mt=re([]),ti=re(null,(e,t)=>{let o=e(et);if(o.length===0)return;let n=e(oe),r=e(ue),s=e(Mt);t(Mt,[...s,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(et,a),t(oe,l.nodes),t(ue,l.edges),t(tt,!0))}),oi=re(null,(e,t)=>{let o=e(Mt);if(o.length===0)return;let n=e(oe),r=e(ue),s=e(et);t(et,[...s,{nodes:n,edges:r}]);let a=[...o],l=a.pop();l&&(t(Mt,a),t(oe,l.nodes),t(ue,l.edges),t(tt,!0))}),ni=re(e=>e(et).length>0),ri=re(e=>e(Mt).length>0),vr=re(null,(e,t)=>{let n=e(oe).map(r=>({...r,data:{...r.data,status:"idle"}}));t(oe,n)});import*as hr from"react";var va=768;function zt(){let[e,t]=hr.useState(void 0);return hr.useEffect(()=>{let o=window.matchMedia(`(max-width: ${va-1}px)`),n=()=>{t(window.innerWidth<va)};return o.addEventListener("change",n),t(window.innerWidth<va),()=>o.removeEventListener("change",n)},[]),!!e}import{Slot as Bc}from"radix-ui";import{cva as Vc}from"class-variance-authority";import{jsx as Gc}from"react/jsx-runtime";var br=Vc("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 R({className:e,variant:t,size:o,asChild:n=!1,...r}){let s=n?Bc.Slot:"button";return Gc(s,{"data-slot":"button",className:x(br({variant:t,size:o,className:e})),...r})}var Hc={"Database Query":"database"};function _c(e){return pe(e)?.integration||Hc[e]}function ai(e,t,o){let n=e.data.config?.actionType;if(!n)return null;let r=_c(n);if(!r)return null;let s=e.data.config?.integrationId;if(s&&o.has(s))return null;let l=t.filter(i=>i.type===r);return l.length===1?{nodeId:e.id,newIntegrationId:l[0].id}:l.length===0&&s?{nodeId:e.id,newIntegrationId:void 0}:null}import{useAtom as io,useAtomValue as Ya,useSetAtom as lo}from"jotai";import{Copy as Nl,Eraser as Ja,Eye as Ap,EyeOff as Sp,FileCode as kl,RefreshCw as Cl,Trash2 as jr}from"lucide-react";import{useCallback as Ip,useEffect as Tl,useMemo as Pp,useRef as Al,useState as Vn}from"react";import{toast as Kr}from"sonner";import{AlertDialog as oo}from"radix-ui";import{jsx as Et,jsxs as Kc}from"react/jsx-runtime";function Go({...e}){return Et(oo.Root,{"data-slot":"alert-dialog",...e})}function $c({...e}){return Et(oo.Portal,{"data-slot":"alert-dialog-portal",...e})}function Uc({className:e,...t}){return Et(oo.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 Ho({className:e,...t}){return Kc($c,{children:[Et(Uc,{}),Et(oo.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 _o({className:e,...t}){return Et("div",{"data-slot":"alert-dialog-header",className:x("flex flex-col gap-2 text-center sm:text-left",e),...t})}function $o({className:e,...t}){return Et("div",{"data-slot":"alert-dialog-footer",className:x("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",e),...t})}function Uo({className:e,...t}){return Et(oo.Title,{"data-slot":"alert-dialog-title",className:x("text-lg font-semibold",e),...t})}function Ko({className:e,...t}){return Et(oo.Description,{"data-slot":"alert-dialog-description",className:x("text-muted-foreground text-sm",e),...t})}function jo({className:e,...t}){return Et(oo.Action,{className:x(br(),e),...t})}function qo({className:e,...t}){return Et(oo.Cancel,{className:x(br({variant:"outline"}),e),...t})}import jc from"@monaco-editor/react";import{useTheme as qc}from"next-themes";var si={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 Yc}from"react/jsx-runtime";function ft(e){let{resolvedTheme:t}=qc();return Yc(jc,{...e,onMount:(n,r)=>{r.editor.defineTheme("vercel-dark",si),r.editor.setTheme(t==="dark"?"vercel-dark":"light"),e.onMount&&e.onMount(n,r)},theme:t==="dark"?"vercel-dark":"light"})}import{jsx as Jc}from"react/jsx-runtime";function ae({className:e,type:t,...o}){return Jc("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 Xc}from"radix-ui";import{jsx as Qc}from"react/jsx-runtime";function W({className:e,...t}){return Qc(Xc.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 wr}from"radix-ui";import{jsx as xr}from"react/jsx-runtime";function ha({className:e,...t}){return xr(wr.Root,{"data-slot":"tabs",className:x("flex flex-col gap-2",e),...t})}function ba({className:e,...t}){return xr(wr.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 vo({className:e,...t}){return xr(wr.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 ho({className:e,...t}){return xr(wr.Content,{"data-slot":"tabs-content",className:x("flex-1 outline-none",e),...t})}import{useAtomValue as Ji,useSetAtom as Nm}from"jotai";import{HelpCircle as km,Plus as Cm,Settings as Tm}from"lucide-react";import{useEffect as Am,useMemo as Mr,useState as Sm}from"react";import{Select as ot}from"radix-ui";import{CheckIcon as Zc,ChevronDownIcon as ii,ChevronUpIcon as eu}from"lucide-react";import{jsx as ze,jsxs as wa}from"react/jsx-runtime";function ke({...e}){return ze(ot.Root,{"data-slot":"select",...e})}function li({...e}){return ze(ot.Group,{"data-slot":"select-group",...e})}function Ce({...e}){return ze(ot.Value,{"data-slot":"select-value",...e})}function Te({className:e,size:t="default",children:o,...n}){return wa(ot.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,ze(ot.Icon,{asChild:!0,children:ze(ii,{className:"size-4 opacity-50"})})]})}function Ae({className:e,children:t,position:o="popper",align:n="center",...r}){return ze(ot.Portal,{children:wa(ot.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:[ze(tu,{}),ze(ot.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}),ze(ou,{})]})})}function di({className:e,...t}){return ze(ot.Label,{"data-slot":"select-label",className:x("text-muted-foreground px-2 py-1.5 text-xs",e),...t})}function se({className:e,children:t,...o}){return wa(ot.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:[ze("span",{className:"absolute right-2 flex size-3.5 items-center justify-center",children:ze(ot.ItemIndicator,{children:ze(Zc,{className:"size-4"})})}),ze(ot.ItemText,{children:t})]})}function Nr({className:e,...t}){return ze(ot.Separator,{"data-slot":"select-separator",className:x("bg-border pointer-events-none -mx-1 my-1 h-px",e),...t})}function tu({className:e,...t}){return ze(ot.ScrollUpButton,{"data-slot":"select-scroll-up-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:ze(eu,{className:"size-4"})})}function ou({className:e,...t}){return ze(ot.ScrollDownButton,{"data-slot":"select-scroll-down-button",className:x("flex cursor-default items-center justify-center py-1",e),...t,children:ze(ii,{className:"size-4"})})}import{useAtom as mi}from"jotai";import{useEffect as xa,useRef as Na,useState as Yo}from"react";import{useAtom as ci}from"jotai";import{Check as nu}from"lucide-react";import{useEffect as kr,useRef as ru,useState as ui}from"react";import{createPortal as au}from"react-dom";import{Fragment as du,jsx as Sn,jsxs as Cr}from"react/jsx-runtime";var su=e=>{if(e.data.label)return e.data.label;if(e.data.type==="action"){let t=e.data.config?.actionType;if(t){let o=pe(t);if(o?.label)return o.label}return t||"HTTP Request"}return e.data.type==="trigger"?e.data.config?.triggerType||"Manual":"Node"},In=(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(...In(n.fields,r)),n.type==="array"&&n.itemType==="object"&&n.fields&&n.fields.length>0){let l=`${r}[0]`;o.push(...In(n.fields,l))}}return o},iu=(e,...t)=>e?t.some(o=>e===o||e.endsWith(`/${o.toLowerCase().replace(/\s+/g,"-")}`)):!1,lu=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 In(n)}catch{}return[{field:"rows",description:"Query result rows"},{field:"count",description:"Number of rows"}]}if(iu(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 In(r,"object")}catch{}return[{field:"text",description:"Generated text"}]}if(t){let o=pe(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 In(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 Tr({isOpen:e,position:t,onSelect:o,onClose:n,currentNodeId:r,filter:s=""}){let[a]=ci(oe),[l]=ci(ue),[i,d]=ui(0),c=ru(null),[u,p]=ui(!1);kr(()=>(p(!0),()=>p(!1)),[]);let C=(()=>{if(!r)return[];let f=new Set,T=[],I=A=>{if(f.has(A))return;f.add(A);let h=l.filter(m=>m.target===A);for(let m of h)T.push(m.source),I(m.source)};return I(r),a.filter(A=>T.includes(A.id))})(),v=[];for(let f of C){let T=su(f),I=lu(f);v.push({type:"node",nodeId:f.id,nodeName:T,template:`{{@${f.id}:${T}}}`});for(let A of I)v.push({type:"field",nodeId:f.id,nodeName:T,field:A.field,description:A.description,template:`{{@${f.id}:${T}.${A.field}}}`})}let y=s?v.filter(f=>f.nodeName.toLowerCase().includes(s.toLowerCase())||f.field&&f.field.toLowerCase().includes(s.toLowerCase())):v;if(kr(()=>{d(0)},[s]),kr(()=>{let f=T=>{if(e)switch(T.key){case"ArrowDown":T.preventDefault(),d(I=>I<y.length-1?I+1:I);break;case"ArrowUp":T.preventDefault(),d(I=>I>0?I-1:I);break;case"Enter":T.preventDefault(),y[i]&&o(y[i].template);break;case"Escape":T.preventDefault(),n();break}};return window.addEventListener("keydown",f),()=>window.removeEventListener("keydown",f)},[e,y,i,o,n]),kr(()=>{if(c.current){let f=c.current.children[i];f&&f.scrollIntoView({block:"nearest"})}},[i]),!e||y.length===0||!u)return null;let w={top:Math.min(t.top,window.innerHeight-300),left:Math.min(t.left,window.innerWidth-320)},k=Sn("div",{className:"fixed z-[9999] w-80 rounded-lg border bg-popover p-1 text-popover-foreground shadow-md",ref:c,style:{top:`${w.top}px`,left:`${w.left}px`},children:Sn("div",{className:"max-h-60 overflow-y-auto",children:y.map((f,T)=>Cr("div",{className:x("flex cursor-pointer items-center justify-between rounded px-2 py-1.5 text-sm transition-colors",T===i?"bg-accent text-accent-foreground":"hover:bg-accent/50"),onClick:()=>o(f.template),onMouseEnter:()=>d(T),children:[Cr("div",{className:"flex-1",children:[Sn("div",{className:"font-medium",children:f.type==="node"?f.nodeName:Cr(du,{children:[Cr("span",{className:"text-muted-foreground",children:[f.nodeName,"."]}),f.field]})}),f.description&&Sn("div",{className:"text-muted-foreground text-xs",children:f.description})]}),T===i&&Sn(nu,{className:"h-4 w-4"})]},`${f.nodeId}-${f.field||"root"}`))})});return au(k,document.body)}import{Fragment as mu,jsx as ka,jsxs as pu}from"react/jsx-runtime";function cu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function uu(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(d=>d.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let d=s.data.config?.actionType;d&&(a=pe(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let i=r.substring(l+1);return a?`${a}.${i}`:r}function We({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s}){let[a,l]=Yo(!1),i=Na(null),[d,c]=Yo(e),u=Na(!0),[p]=mi(be),[g]=mi(oe),[C,v]=Yo(!1),[y,w]=Yo({top:0,left:0}),[k,f]=Yo(""),[T,I]=Yo(null),A=Na(null);xa(()=>{e!==d&&!a&&(c(e),u.current=!0)},[e,a,d]),xa(()=>{!a&&d&&(u.current=!0)},[g,a,d]);let h=()=>{if(!i.current)return null;let V=window.getSelection();if(!V||V.rangeCount===0)return null;let Y=V.getRangeAt(0),M=Y.cloneRange();M.selectNodeContents(i.current),M.setEnd(Y.endContainer,Y.endOffset);let K=0,N=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),z,b=!1;for(;(z=N.nextNode())&&!b;)if(z.nodeType===Node.TEXT_NODE)if(z===Y.endContainer)K+=Y.endOffset,b=!0;else{let D=(z.textContent||"").length;K+=D}else if(z.nodeType===Node.ELEMENT_NODE){let D=z,G=D.getAttribute("data-template");G&&(D.contains(Y.endContainer)||D===Y.endContainer?(K+=G.length,b=!0):K+=G.length)}return{offset:K}},m=V=>{if(!i.current||!V)return;let Y=0,M=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),K,N=null,z=0;for(;K=M.nextNode();)if(K.nodeType===Node.TEXT_NODE){let b=(K.textContent||"").length;if(Y+b>=V.offset){N=K,z=V.offset-Y;break}Y+=b}else if(K.nodeType===Node.ELEMENT_NODE){let b=K,D=b.getAttribute("data-template");if(D){if(Y+D.length>=V.offset){N=b.nextSibling,z=0,!N&&b.parentNode&&(N=document.createTextNode(""),b.parentNode.appendChild(N));break}Y+=D.length}}if(N){let b=document.createRange(),D=window.getSelection();try{let G=Math.min(z,N.textContent?.length||0);b.setStart(N,G),b.collapse(!0),D?.removeAllRanges(),D?.addRange(b),i.current.focus()}catch{i.current.focus()}}},S=()=>{if(!i.current||!u.current)return;let V=i.current,Y=d||"",M=a?h():null;if(A.current!==null&&(M={offset:A.current},A.current=null),V.innerHTML="",!Y&&!a){V.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let K=/\{\{@([^:]+):([^}]+)\}\}/g,N=0,z;for(;(z=K.exec(Y))!==null;){let[b]=z,D=z.index;if(D>N){let de=Y.slice(N,D),B=document.createTextNode(de);V.appendChild(B)}let G=document.createElement("span"),te=cu(b,g);G.className=te?"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",b),G.textContent=uu(b,g),V.appendChild(G),N=K.lastIndex}if(N<Y.length){let b=Y.slice(N),D=document.createTextNode(b);V.appendChild(D)}V.innerHTML===""&&a&&(V.innerHTML="<br>"),u.current=!1,M&&requestAnimationFrame(()=>m(M))},X=()=>{if(!i.current)return"";let V="",Y=document.createTreeWalker(i.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),M;for(;M=Y.nextNode();)if(M.nodeType===Node.TEXT_NODE){let K=M.parentElement,N=!1;for(;K&&K!==i.current;){if(K.getAttribute("data-template")){N=!0;break}K=K.parentElement}N||(V+=M.textContent)}else if(M.nodeType===Node.ELEMENT_NODE){let N=M.getAttribute("data-template");N&&(V+=N)}return V},le=()=>{let V=X();if(V===d)return;let Y=(d.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,M=(V.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(M>Y){c(V),t?.(V),u.current=!0,v(!1),requestAnimationFrame(()=>S());return}if(M===Y&&M>0){c(V),t?.(V);let N=V.lastIndexOf("@");if(N!==-1){let z=V.slice(N+1);if(z.includes(" "))v(!1);else{if(f(z),I(N),i.current){let b=i.current.getBoundingClientRect(),D={top:b.bottom+window.scrollY+4,left:b.left+window.scrollX};w(D)}v(!0)}}else v(!1);return}if(M<Y){c(V),t?.(V),u.current=!0,requestAnimationFrame(()=>S());return}c(V),t?.(V);let K=V.lastIndexOf("@");if(K!==-1){let N=V.slice(K+1);if(N.includes(" "))v(!1);else{if(f(N),I(K),i.current){let z=i.current.getBoundingClientRect(),b={top:z.bottom+window.scrollY+4,left:z.left+window.scrollX};w(b)}v(!0)}}else v(!1)},L=V=>{if(!i.current||T===null)return;let Y=X(),M=Y.slice(0,T),K=Y.slice(T+1+k.length),N=M+V+K,z=M.length+V.length;c(N),t?.(N),u.current=!0,v(!1),I(null),A.current=z,i.current.focus()},F=()=>{l(!0),u.current=!0},_=()=>{setTimeout(()=>{document.activeElement!==i.current&&(l(!1),u.current=!0,v(!1))},200)},P=V=>{V.preventDefault();let Y=V.clipboardData.getData("text/plain");document.execCommand("insertText",!1,Y)};return xa(()=>{u.current&&S()},[d,a]),pu(mu,{children:[ka("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:ka("div",{className:"w-full outline-none",contentEditable:!n,id:s,onBlur:_,onFocus:F,onInput:le,onPaste:P,ref:i,role:"textbox",suppressContentEditableWarning:!0})}),ka(Tr,{currentNodeId:p||void 0,filter:k,isOpen:C,onClose:()=>v(!1),onSelect:L,position:y})]})}import{jsx as nt,jsxs as bo}from"react/jsx-runtime";function pi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.dataType||"string",r=e?.operator||nr[n][0].value,s=nr[n],l=s.find(d=>d.value===r)?.unary??!1;function i(d){t("dataType",d);let c=nr[d];c?.[0]&&t("operator",c[0].value)}return bo("div",{className:"space-y-4",children:[bo("div",{className:"space-y-2",children:[nt(W,{htmlFor:"leftValue",children:"Value to Test"}),nt(We,{disabled:o,id:"leftValue",onChange:d=>t("leftValue",d),placeholder:"e.g., {{PreviousNode.status}}",value:e?.leftValue||""}),nt("p",{className:"text-muted-foreground text-xs",children:"Use @ to reference previous node outputs."})]}),bo("div",{className:"space-y-2",children:[nt(W,{htmlFor:"dataType",children:"Data Type"}),bo(ke,{disabled:o,onValueChange:i,value:n,children:[nt(Te,{id:"dataType",children:nt(Ce,{placeholder:"Select data type"})}),nt(Ae,{children:Hs.map(d=>nt(se,{value:d.value,children:d.label},d.value))})]})]}),bo("div",{className:"space-y-2",children:[nt(W,{htmlFor:"operator",children:"Operator"}),bo(ke,{disabled:o,onValueChange:d=>t("operator",d),value:r,children:[nt(Te,{id:"operator",children:nt(Ce,{placeholder:"Select operator"})}),nt(Ae,{children:s.map(d=>nt(se,{value:d.value,children:d.label},d.value))})]})]}),!l&&bo("div",{className:"space-y-2",children:[nt(W,{htmlFor:"rightValue",children:"Compare Value"}),nt(We,{disabled:o,id:"rightValue",onChange:d=>t("rightValue",d),placeholder:"e.g., 200 or {{OtherNode.field}}",value:e?.rightValue||""})]})]})}import{Plus as fu,Trash2 as gu}from"lucide-react";import{nanoid as yu}from"nanoid";import{jsx as we,jsxs as lt}from"react/jsx-runtime";function no({schema:e,onChange:t,disabled:o,level:n=0}){let r=()=>{t([...e,{id:yu(),name:"",type:"string"}])},s=(c,u)=>{let p={...c};return u!=="array"&&(p.itemType=void 0),u!=="object"&&(p.fields=void 0),u==="array"&&!p.itemType&&(p.itemType="string"),u==="object"&&!p.fields&&(p.fields=[]),p},a=(c,u)=>{let p=[...e];p[c]={...p[c],...u},u.type&&(p[c]=s(p[c],u.type)),t(p)},l=c=>{t(e.filter((u,p)=>p!==c))},i=(c,u)=>{let p=[...e];p[c].fields=u,t(p)},d=n>0?"ml-4 border-l-2 border-muted pl-4":"";return lt("div",{className:`space-y-3 ${d}`,children:[e.map((c,u)=>{let p=c.id||`field-${n}-${u}`;return lt("div",{className:"space-y-2 rounded-md border p-3",children:[lt("div",{className:"flex gap-2",children:[lt("div",{className:"flex-1 space-y-2",children:[we(W,{className:"ml-1",htmlFor:`field-name-${n}-${u}`,children:"Property Name"}),we(ae,{disabled:o,id:`field-name-${n}-${u}`,onChange:g=>a(u,{name:g.target.value}),placeholder:"propertyName",value:c.name})]}),lt("div",{className:"flex-1 space-y-2",children:[we(W,{className:"ml-1",htmlFor:`field-type-${n}-${u}`,children:"Type"}),lt(ke,{disabled:o,onValueChange:g=>a(u,{type:g}),value:c.type,children:[we(Te,{className:"w-full",id:`field-type-${n}-${u}`,children:we(Ce,{})}),lt(Ae,{children:[we(se,{value:"string",children:"String"}),we(se,{value:"number",children:"Number"}),we(se,{value:"boolean",children:"Boolean"}),we(se,{value:"array",children:"Array"}),we(se,{value:"object",children:"Object"})]})]})]}),we("div",{className:"flex items-end",children:we(R,{disabled:o,onClick:()=>l(u),size:"icon",variant:"ghost",children:we(gu,{className:"h-4 w-4"})})})]}),c.type==="array"&<("div",{className:"space-y-2",children:[we(W,{className:"ml-1",htmlFor:`field-item-type-${n}-${u}`,children:"Array Item Type"}),lt(ke,{disabled:o,onValueChange:g=>a(u,{itemType:g}),value:c.itemType||"string",children:[we(Te,{className:"w-full",id:`field-item-type-${n}-${u}`,children:we(Ce,{})}),lt(Ae,{children:[we(se,{value:"string",children:"String"}),we(se,{value:"number",children:"Number"}),we(se,{value:"boolean",children:"Boolean"}),we(se,{value:"object",children:"Object"})]})]})]}),c.type==="object"&<("div",{className:"mt-2",children:[we(W,{className:"mb-2 block",children:"Object Properties"}),we(no,{disabled:o,level:n+1,onChange:g=>i(u,g),schema:c.fields||[]})]}),c.type==="array"&&c.itemType==="object"&<("div",{className:"mt-2",children:[we(W,{className:"mb-2 block",children:"Array Item Properties"}),we(no,{disabled:o,level:n+1,onChange:g=>i(u,g),schema:c.fields||[]})]}),lt("div",{className:"space-y-2",children:[we(W,{className:"ml-1",htmlFor:`field-desc-${n}-${u}`,children:"Description (optional)"}),we(ae,{disabled:o,id:`field-desc-${n}-${u}`,onChange:g=>a(u,{description:g.target.value}),placeholder:"Description for the AI",value:c.description||""})]})]},p)}),lt(R,{className:"w-full",disabled:o,onClick:r,type:"button",variant:"outline",children:[we(fu,{className:"size-4"}),"Add Property"]})]})}import{Fragment as vu,jsx as Jo,jsxs as Ca}from"react/jsx-runtime";function fi({config:e,onUpdateConfig:t,disabled:o}){return Ca(vu,{children:[Ca("div",{className:"space-y-2",children:[Jo(W,{htmlFor:"dbQuery",children:"SQL Query"}),Jo("div",{className:"overflow-hidden rounded-md border",children:Jo(ft,{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||""})}),Jo("p",{className:"text-muted-foreground text-xs",children:"The DATABASE_URL from your project integrations will be used to execute this query."})]}),Ca("div",{className:"space-y-2",children:[Jo(W,{children:"Schema (Optional)"}),Jo(no,{disabled:o,onChange:n=>t("dbSchema",JSON.stringify(n)),schema:e?.dbSchema?JSON.parse(e.dbSchema):[]})]})]})}import{Fragment as hu,jsx as Ue,jsxs as wo}from"react/jsx-runtime";function gi({config:e,onUpdateConfig:t,disabled:o}){return wo(hu,{children:[wo("div",{className:"space-y-2",children:[Ue(W,{htmlFor:"httpMethod",children:"HTTP Method"}),wo(ke,{disabled:o,onValueChange:n=>t("httpMethod",n),value:e?.httpMethod||"POST",children:[Ue(Te,{className:"w-full",id:"httpMethod",children:Ue(Ce,{placeholder:"Select method"})}),wo(Ae,{children:[Ue(se,{value:"GET",children:"GET"}),Ue(se,{value:"POST",children:"POST"}),Ue(se,{value:"PUT",children:"PUT"}),Ue(se,{value:"PATCH",children:"PATCH"}),Ue(se,{value:"DELETE",children:"DELETE"})]})]})]}),wo("div",{className:"space-y-2",children:[Ue(W,{htmlFor:"endpoint",children:"URL"}),Ue(We,{disabled:o,id:"endpoint",onChange:n=>t("endpoint",n),placeholder:"https://api.example.com/endpoint or {{NodeName.url}}",value:e?.endpoint||""})]}),wo("div",{className:"space-y-2",children:[Ue(W,{htmlFor:"httpHeaders",children:"Headers (JSON)"}),Ue("div",{className:"overflow-hidden rounded-md border",children:Ue(ft,{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||"{}"})})]}),wo("div",{className:"space-y-2",children:[Ue(W,{htmlFor:"httpBody",children:"Body (JSON)"}),Ue("div",{className:`overflow-hidden rounded-md border ${e?.httpMethod==="GET"?"opacity-50":""}`,children:Ue(ft,{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"&&Ue("p",{className:"text-muted-foreground text-xs",children:"Body is disabled for GET requests"})]})]})}import{jsx as Xo,jsxs as Ta}from"react/jsx-runtime";function yi({config:e,onUpdateConfig:t,disabled:o}){return Ta("div",{className:"space-y-4",children:[Ta("div",{className:"space-y-2",children:[Xo(W,{htmlFor:"items",children:"Items to Iterate"}),Xo(We,{disabled:o,id:"items",onChange:n=>t("items",n),placeholder:"e.g., {{PreviousNode.rows}}, {{DatabaseQuery.results}}",value:e?.items||""}),Xo("p",{className:"text-muted-foreground text-xs",children:"Reference an array from a previous node. Use @ to reference outputs."})]}),Ta("div",{className:"space-y-2",children:[Xo(W,{htmlFor:"batchSize",children:"Batch Size (optional)"}),Xo(We,{disabled:o,id:"batchSize",onChange:n=>t("batchSize",n),placeholder:"1",value:e?.batchSize||""}),Xo("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 bu,jsx as ye,jsxs as Je}from"react/jsx-runtime";function vi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"append";return Je("div",{className:"space-y-4",children:[Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"mode",children:"Mode"}),Je(ke,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[ye(Te,{id:"mode",children:ye(Ce,{placeholder:"Select mode"})}),Je(Ae,{children:[ye(se,{value:"append",children:"Append"}),ye(se,{value:"combineByPosition",children:"Combine by Position"}),ye(se,{value:"combineByFields",children:"Combine by Fields"})]})]}),Je("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."]})]}),Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"input1",children:"Input 1"}),ye(We,{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."})]}),Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"input2",children:"Input 2"}),ye(We,{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"&&Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"unmatchedHandling",children:"When arrays have different lengths"}),Je(ke,{disabled:o,onValueChange:r=>t("unmatchedHandling",r),value:e?.unmatchedHandling||"useNull",children:[ye(Te,{id:"unmatchedHandling",children:ye(Ce,{})}),Je(Ae,{children:[ye(se,{value:"useNull",children:"Fill with null"}),ye(se,{value:"discard",children:"Discard extra items"})]})]})]}),n==="combineByFields"&&Je(bu,{children:[Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"matchField1",children:"Match Field (Input 1)"}),ye(We,{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."})]}),Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"matchField2",children:"Match Field (Input 2)"}),ye(We,{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."})]}),Je("div",{className:"space-y-2",children:[ye(W,{htmlFor:"joinType",children:"Join Type"}),Je(ke,{disabled:o,onValueChange:r=>t("joinType",r),value:e?.joinType||"inner",children:[ye(Te,{id:"joinType",children:ye(Ce,{})}),Je(Ae,{children:[ye(se,{value:"inner",children:"Inner Join"}),ye(se,{value:"leftOuter",children:"Left Outer Join"}),ye(se,{value:"rightOuter",children:"Right Outer Join"}),ye(se,{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{jsx as rt,jsxs as Dt}from"react/jsx-runtime";function hi({config:e,onUpdateConfig:t,disabled:o}){let n=e?.mode||"rules";return Dt("div",{className:"space-y-4",children:[Dt("div",{className:"space-y-2",children:[rt(W,{htmlFor:"mode",children:"Mode"}),Dt(ke,{disabled:o,onValueChange:r=>t("mode",r),value:n,children:[rt(Te,{id:"mode",children:rt(Ce,{placeholder:"Select mode"})}),Dt(Ae,{children:[rt(se,{value:"rules",children:"Rules"}),rt(se,{value:"expression",children:"Expression"})]})]}),Dt("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"&&Dt("div",{className:"space-y-2",children:[rt(W,{htmlFor:"switchValue",children:"Value to Switch On"}),rt(We,{disabled:o,id:"switchValue",onChange:r=>t("switchValue",r),placeholder:"e.g., {{PreviousNode.statusCode}}",value:e?.switchValue||""}),rt("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=>Dt("div",{className:"space-y-3 rounded-md border p-3",children:[Dt("p",{className:"font-medium text-sm",children:["Route ",r+1]}),Dt("div",{className:"space-y-2",children:[rt(W,{htmlFor:`routeName${r}`,children:"Name (optional)"}),rt(ae,{disabled:o,id:`routeName${r}`,onChange:s=>t(`routeName${r}`,s.target.value),placeholder:`Route ${r+1}`,value:e?.[`routeName${r}`]||""})]}),n==="rules"&&Dt("div",{className:"space-y-2",children:[rt(W,{htmlFor:`routeCondition${r}`,children:"Condition"}),rt(We,{disabled:o,id:`routeCondition${r}`,onChange:s=>t(`routeCondition${r}`,s),placeholder:"e.g., {{PreviousNode.status}} === 200",value:e?.[`routeCondition${r}`]||""})]}),n==="expression"&&Dt("div",{className:"space-y-2",children:[rt(W,{htmlFor:`routeCaseValue${r}`,children:"Case Value"}),rt(We,{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)),rt("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 Ar}from"jotai";var Sr=Ar(null),bi=Ar([]),wi=Ar(!1),pb=Ar(!1);import{useAtomValue as Li,useSetAtom as Ea}from"jotai";import{Search as Mu}from"lucide-react";import{useCallback as Fu,useMemo as zu,useState as tn}from"react";import{toast as ko}from"sonner";import{atom as Pn,useSetAtom as wu}from"jotai";import*as Ni from"react";var xi=null;var xo=Pn(null),Ir=Pn([]),Pr=Pn(!1),ki=Pn(!1),Ht=Pn(null);function Ci(){let e=wu(Ht);Ni.useEffect(()=>{xi&&e(xi)},[e])}import{Database as xu,HelpCircle as Nu}from"lucide-react";import{jsx as En}from"react/jsx-runtime";function ku({className:e}){return En("svg",{className:e,fill:"currentColor",height:"12",viewBox:"0 0 1155 1000",width:"12",xmlns:"http://www.w3.org/2000/svg",children:En("path",{d:"m577.3 0 577.4 1000H0z"})})}var Cu={database:xu,vercel:ku};function Rt({integration:e,className:t="h-3 w-3"}){let o=Cu[e];if(o)return En(o,{className:x("text-foreground",t)});let n=It(e);if(n?.icon){let r=n.icon;return En(r,{className:x("text-foreground",t)})}return En(Nu,{className:x("text-foreground",t)})}import{AlertTriangleIcon as Ou}from"lucide-react";import{Loader2 as Tu}from"lucide-react";import{jsx as Qo,jsxs as Sa}from"react/jsx-runtime";function Aa({action:e}){return Sa(R,{disabled:e.disabled||e.loading,onClick:e.onClick,variant:e.variant??"default",children:[e.loading&&Qo(Tu,{className:"mr-2 size-4 animate-spin"}),e.label]})}function Ti({actions:e,className:t,children:o}){if(o)return Qo("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,l=r.length>0||s.length>0;return Sa("div",{className:x("flex flex-col-reverse gap-2 p-6 pt-4 sm:flex-row",a&&l?"sm:justify-between":"sm:justify-end",t),children:[a&&Qo("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:n.map(i=>Qo(Aa,{action:i},i.label))}),l&&Sa("div",{className:"flex flex-col-reverse gap-2 sm:flex-row",children:[r.map(i=>Qo(Aa,{action:i},i.label)),s.map(i=>Qo(Aa,{action:i},i.label))]})]})}import{ChevronLeftIcon as Pu,XIcon as Eu}from"lucide-react";import{createContext as Si,useCallback as Zo,useContext as Ii,useMemo as Au,useRef as Su,useState as Iu}from"react";import{jsx as Ai}from"react/jsx-runtime";var Pi=Si(null),Ei=Si([]);function Ia(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}function Di({children:e}){let[t,o]=Iu([]),n=Su([]);t.length>0&&(n.current=t);let r=Zo((u,p,g)=>{let C=Ia();return o([{id:C,component:u,props:p??{},options:g??{}}]),C},[]),s=Zo((u,p,g)=>{let C=Ia(),v={id:C,component:u,props:p??{},options:g??{}};return o(y=>[...y,v]),C},[]),a=Zo(()=>{o(u=>u.length<=1?(u[0]?.options.onClose?.(),[]):(u[u.length-1]?.options.onClose?.(),u.slice(0,-1)))},[]),l=Zo((u,p,g)=>{let C=Ia(),v={id:C,component:u,props:p??{},options:g??{}};return o(y=>y.length===0?[v]:(y[y.length-1]?.options.onClose?.(),[...y.slice(0,-1),v])),C},[]),i=Zo(()=>{o(u=>{for(let p of u)p.options.onClose?.();return[]})},[]),d=Zo(u=>{o(p=>{let g=p.findIndex(C=>C.id===u);if(g===-1)return p;for(let C=g;C<p.length;C++)p[C].options.onClose?.();return p.slice(0,g)})},[]),c=Au(()=>({stack:t,open:r,push:s,pop:a,replace:l,closeAll:i,close:d,hasOverlays:t.length>0,depth:t.length}),[t,r,s,a,l,i,d]);return Ai(Pi.Provider,{value:c,children:Ai(Ei.Provider,{value:n.current,children:e})})}function ne(){let e=Ii(Pi);if(!e)throw new Error("useOverlay must be used within an OverlayProvider");return e}function Ri(e){let{stack:t}=ne(),o=Ii(Ei),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 No,jsxs as Oi}from"react/jsx-runtime";function Du({title:e,description:t,showBackButton:o,showCloseButton:n=!0,onBack:r,onClose:s,className:a}){let{pop:l,closeAll:i}=ne(),d=o??!1,c=()=>{r?r():l()},u=()=>{s?s():i()};return Oi("div",{className:x("relative flex flex-col gap-1.5 p-6 pb-0",a),children:[Oi("div",{className:"flex min-h-8 items-center gap-2",children:[d&&No(R,{"aria-label":"Go back",className:"ml-[-8px] size-8 shrink-0",onClick:c,size:"icon",variant:"ghost",children:No(Pu,{className:"size-5"})}),e&&No("h2",{className:"flex-1 font-semibold text-lg leading-none tracking-tight",children:e}),n&&No(R,{"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:No(Eu,{className:"size-4"})})]}),t&&No("p",{className:"text-muted-foreground text-sm",children:t})]})}function en({overlayId:e,showBackButton:t,...o}){let{showBackButton:n}=Ri(e);return No(Du,{...o,showBackButton:t??n})}import{jsx as Pa,jsxs as Ru}from"react/jsx-runtime";function De({overlayId:e,title:t,description:o,actions:n,children:r,className:s}){return Ru("div",{className:x("flex flex-col",s),children:[(t||o)&&Pa(en,{description:o,overlayId:e,title:t}),r&&Pa("div",{className:"flex-1 overflow-y-auto p-6",children:r}),Pa(Ti,{actions:n})]})}import{jsx as Er,jsxs as Lu}from"react/jsx-runtime";function Oe({overlayId:e,title:t="Confirm",message:o,confirmLabel:n="Confirm",cancelLabel:r="Cancel",confirmVariant:s="default",destructive:a=!1,onConfirm:l,onCancel:i}){let{pop:d}=ne();return Er(De,{actions:[{label:r,variant:"outline",onClick:()=>{i?.(),d()}},{label:n,variant:a?"destructive":s,onClick:async()=>{await l(),d()}}],overlayId:e,title:t,children:Lu("div",{className:"flex gap-4",children:[a&&Er("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-destructive/10",children:Er(Ou,{className:"size-5 text-destructive"})}),Er("p",{className:x("text-muted-foreground text-sm",a&&"pt-2"),children:o})]})})}import{jsx as Ve,jsxs as gt}from"react/jsx-runtime";var Wu=["database"],Bu={database:"Database"},Vu={database:"Connect to PostgreSQL databases"},Gu=()=>[...Vs(),...Wu],Da=e=>Yt()[e]||Bu[e]||e,Hu=e=>Bs()[e]||Vu[e]||"";function Fi({overlayId:e,onSuccess:t}){let{push:o,closeAll:n}=ne(),[r,s]=tn(""),a=zt(),l=Li(Ht),i=Li(xo),d=Ea(xo),c=Ea(Ir),u=Ea(Pr),p=Gu(),g=zu(()=>{if(!r.trim())return p;let y=r.toLowerCase();return p.filter(w=>Da(w).toLowerCase().includes(y))},[p,r]),C=Fu(()=>{l&&o(l.ConsentOverlay,{onConsent:y=>{t?.(y),n()}})},[l,o,n,t]),v=y=>{let w=l?.integrationType===y;if(w&&i?.enabled&&i?.isVercelUser){C();return}if(w&&i===null){l.api.getStatus().then(f=>{d(f),f?.enabled&&f?.isVercelUser?(u(!0),l.api.getTeams().then(T=>{c(T.teams)}).finally(()=>{u(!1),C()})):o(ro,{type:y,onSuccess:t})});return}o(ro,{type:y,onSuccess:t})};return gt(De,{overlayId:e,title:"Add Connection",children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Select a service to connect"}),gt("div",{className:"space-y-3",children:[gt("div",{className:"relative",children:[Ve(Mu,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ve(ae,{autoFocus:!a,className:"pl-9",onChange:y=>s(y.target.value),placeholder:"Search services...",value:r})]}),Ve("div",{className:"max-h-[300px] space-y-1 overflow-y-auto",children:g.length===0?Ve("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No services found"}):g.map(y=>{let w=Hu(y);return gt("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:()=>v(y),type:"button",children:[Ve(Rt,{className:"size-5 shrink-0",integration:y==="ai-gateway"?"vercel":y}),gt("span",{className:"min-w-0 flex-1 truncate",children:[Ve("span",{className:"font-medium",children:Da(y)}),w&>("span",{className:"text-muted-foreground text-xs",children:[" ","- ",w]})]})]},y)})})]})]})}function Mi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:l}){return gt("div",{className:"space-y-2",children:[Ve(W,{htmlFor:e,children:t}),Ve(ae,{className:"flex-1",id:e,onChange:i=>l(o,i.target.value),placeholder:n,type:"password",value:a}),(r||s)&>("p",{className:"text-muted-foreground text-xs",children:[r,s&&Ve("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]})}function ro({overlayId:e,type:t,onSuccess:o}){let{push:n,closeAll:r}=ne(),[s,a]=tn(!1),[l,i]=tn(!1),[d,c]=tn(null),[u,p]=tn(""),[g,C]=tn({}),v=(A,h)=>{C(m=>({...m,[A]:h}))},y=async()=>{try{a(!0);let A=await j.integration.create({name:u.trim(),type:t,config:g});ko.success("Connection created"),o?.(A.id),r()}catch(A){console.error("Failed to save integration:",A),ko.error("Failed to save connection")}finally{a(!1)}},w=async()=>{if(!Object.values(g).some(h=>h&&h.length>0)){ko.error("Please enter credentials");return}try{a(!0),c(null);let h=await j.integration.testCredentials({type:t,config:g});if(h.status==="error"){n(Oe,{title:"Connection Test Failed",message:`The test failed: ${h.message}
|
|
3
3
|
|
|
4
4
|
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1);return}await y()}catch(h){let m=h instanceof Error?h.message:"Failed to test connection";n(Oe,{title:"Connection Test Failed",message:`${m}
|
|
5
5
|
|
|
6
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1)}},k=async()=>{if(!Object.values(g).some(h=>h&&h.length>0)){ko.error("Please enter credentials first");return}try{i(!0),c(null);let h=await
|
|
6
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await y()}}),a(!1)}},k=async()=>{if(!Object.values(g).some(h=>h&&h.length>0)){ko.error("Please enter credentials first");return}try{i(!0),c(null);let h=await j.integration.testCredentials({type:t,config:g});c(h),h.status==="success"?ko.success(h.message||"Connection successful"):ko.error(h.message||"Connection failed")}catch(h){let m=h instanceof Error?h.message:"Connection test failed";c({status:"error",message:m}),ko.error(m)}finally{i(!1)}},T=It(t)?.formFields,I=()=>t==="database"?Ve(Mi,{configKey:"url",fieldId:"url",helpText:"Connection string in the format: postgresql://user:password@host:port/database",label:"Database URL",onChange:v,placeholder:"postgresql://user:password@host:port/database",value:g.url||""}):T?T.map(A=>A.type==="password"?Ve(Mi,{configKey:A.configKey,fieldId:A.id,helpLink:A.helpLink,helpText:A.helpText,label:A.label,onChange:v,placeholder:A.placeholder,value:g[A.configKey]||""},A.id):gt("div",{className:"space-y-2",children:[Ve(W,{htmlFor:A.id,children:A.label}),Ve(ae,{id:A.id,onChange:h=>v(A.configKey,h.target.value),placeholder:A.placeholder,type:A.type,value:g[A.configKey]||""}),(A.helpText||A.helpLink)&>("p",{className:"text-muted-foreground text-xs",children:[A.helpText,A.helpLink&&Ve("a",{className:"underline hover:text-foreground",href:A.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:A.helpLink.text})]})]},A.id)):null;return gt(De,{actions:[{label:"Test",variant:"outline",onClick:k,loading:l,disabled:s},{label:"Create",onClick:w,loading:s}],overlayId:e,title:`Add ${Da(t)}`,children:[Ve("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Enter your credentials"}),gt("div",{className:"space-y-4",children:[I(),gt("div",{className:"space-y-2",children:[Ve(W,{htmlFor:"name",children:"Label (Optional)"}),Ve(ae,{id:"name",onChange:A=>p(A.target.value),placeholder:"e.g. Production, Personal, Work",value:u})]})]})]})}import{useAtomValue as zi,useSetAtom as _u}from"jotai";import{Loader2 as $u,Sparkles as Uu,X as Ku}from"lucide-react";import{useCallback as Dr,useEffect as ju,useState as Ra}from"react";import{jsx as Ke,jsxs as ao}from"react/jsx-runtime";function Wi({overlayId:e,onConsent:t,onManualEntry:o,onDecline:n}){let{pop:r}=ne(),s=_u(Sr),[a,l]=Ra(!1),[i,d]=Ra(null),[c,u]=Ra(""),p=zi(bi),g=zi(wi);ju(()=>{p.length>0&&!c&&u(p[0].id)},[p,c]);let C=Dr(f=>{l(!1),t?.(f),r()},[t,r]),v=Dr(async()=>{if(!c){d("Please select a team");return}let T=p.find(I=>I.id===c)?.name||"AI Gateway";l(!0),d(null);try{let I=await j.aiGateway.consent(c,T);if(!I.success)throw new Error(I.error||"Failed to set up AI Gateway");let A=I.managedIntegrationId||"";s(h=>h?{...h,hasManagedKey:I.hasManagedKey,managedIntegrationId:A}:null),C(A)}catch(I){d(I instanceof Error?I.message:"An error occurred"),l(!1)}},[c,p,s,C]),y=Dr(()=>{n?.(),r()},[n,r]),w=Dr(()=>{o?.()},[o]),k=[...o?[{label:"Enter manually",variant:"ghost",onClick:w,disabled:a}]:[],{label:"Cancel",variant:"outline",onClick:y,disabled:a},{label:a?"Setting up...":"Agree & Connect",variant:"default",onClick:v,disabled:a||g&&p.length===0||!c,loading:a}];return Ke(De,{actions:k,description:"Connect your Vercel account to use your own AI Gateway balance",overlayId:e,title:"Use Your AI Gateway Credits",children:ao("div",{className:"space-y-4",children:[ao("div",{className:"flex items-start gap-3",children:[Ke("div",{className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-primary/10",children:Ke(Uu,{className:"size-5 text-primary"})}),Ke("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."})]}),ao("div",{className:"space-y-2",children:[Ke(W,{htmlFor:"team-select",children:"Vercel Team"}),g&&p.length===0?ao("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3 text-muted-foreground text-sm",children:[Ke($u,{className:"size-4 animate-spin"}),"Loading teams..."]}):ao(ke,{disabled:a,onValueChange:u,value:c,children:[Ke(Te,{id:"team-select",children:Ke(Ce,{placeholder:"Select a team"})}),Ke(Ae,{children:p.map((f,T)=>ao("div",{children:[Ke(se,{value:f.id,children:ao("div",{className:"flex items-center gap-2",children:[f.avatar?Ke("img",{alt:"",className:"size-4 rounded-full bg-white",src:f.avatar}):Ke("div",{className:"size-4 rounded-full bg-white"}),Ke("span",{children:f.name}),f.isPersonal&&Ke("span",{className:"text-muted-foreground text-xs",children:"(Personal)"})]})}),f.isPersonal&&T<p.length-1&&Ke(Nr,{})]},f.id))})]})]}),i&&ao("div",{className:"flex items-start gap-3 rounded-md border border-red-500/30 bg-red-500/10 p-3",children:[Ke(Ku,{className:"mt-0.5 size-4 shrink-0 text-red-500"}),Ke("p",{className:"text-red-700 text-sm dark:text-red-400",children:i})]})]})})}import{useAtom as Lr,useAtomValue as Gi,useSetAtom as Hi}from"jotai";import{AlertTriangle as tm,Check as Ma,Circle as _i,Pencil as Fa,Plus as om,Settings as nm}from"lucide-react";import{useCallback as Dn,useEffect as on,useMemo as rm,useRef as am,useState as $i}from"react";import{useAtomValue as Yu}from"jotai";import{Check as Ju,Pencil as Xu,X as Qu}from"lucide-react";import{useState as so}from"react";import{toast as Co}from"sonner";import*as Rr from"@radix-ui/react-checkbox";import{CheckIcon as qu}from"lucide-react";import{jsx as Oa}from"react/jsx-runtime";function Bi({className:e,...t}){return Oa(Rr.Root,{"data-slot":"checkbox",className:x("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:Oa(Rr.Indicator,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:Oa(qu,{className:"size-3.5"})})})}import{jsx as Me,jsxs as dt}from"react/jsx-runtime";var Zu={database:"Database"},em=e=>Yt()[e]||Zu[e]||e;function Vi({fieldId:e,label:t,configKey:o,placeholder:n,helpText:r,helpLink:s,value:a,onChange:l}){let[i,d]=so(!1),c=zt(),u=a.length>0;return i||u?dt("div",{className:"space-y-2",children:[Me(W,{htmlFor:e,children:t}),dt("div",{className:"flex items-center gap-2",children:[Me(ae,{autoFocus:i&&!c,className:"flex-1",id:e,onChange:p=>l(o,p.target.value),placeholder:n,type:"password",value:a}),(i||u)&&Me(R,{onClick:()=>{l(o,""),d(!1)},size:"icon",type:"button",variant:"ghost",children:Me(Qu,{className:"size-4"})})]}),(r||s)&&dt("p",{className:"text-muted-foreground text-xs",children:[r,s&&Me("a",{className:"underline hover:text-foreground",href:s.url,rel:"noopener noreferrer",target:"_blank",children:s.text})]})]}):dt("div",{className:"space-y-2",children:[Me(W,{htmlFor:e,children:t}),dt("div",{className:"flex items-center gap-2",children:[dt("div",{className:"flex h-9 flex-1 items-center gap-2 rounded-md border bg-muted/30 px-3",children:[Me(Ju,{className:"size-4 text-green-600"}),Me("span",{className:"text-muted-foreground text-sm",children:"Configured"})]}),dt(R,{onClick:()=>d(!0),type:"button",variant:"outline",children:[Me(Xu,{className:"mr-1.5 size-3"}),"Change"]})]})]})}function Or({overlayId:e,integration:t,onSuccess:o,onDelete:n}){let{push:r,closeAll:s}=ne(),[a,l]=so(!1),[i,d]=so(!1),[c,u]=so(null),[p,g]=so(t.name),[C,v]=so({}),y=(m,S)=>{v(X=>({...X,[m]:S}))},w=async()=>{try{l(!0);let m=Object.values(C).some(S=>S&&S.length>0);await j.integration.update(t.id,{name:p.trim(),...m?{config:C}:{}}),Co.success("Connection updated"),o?.(),s()}catch(m){console.error("Failed to update integration:",m),Co.error("Failed to update connection")}finally{l(!1)}},k=async()=>{if(!Object.values(C).some(S=>S&&S.length>0)){await w();return}try{l(!0),u(null);let S=await j.integration.testCredentials({type:t.type,config:C});if(S.status==="error"){r(Oe,{title:"Connection Test Failed",message:`The test failed: ${S.message}
|
|
7
7
|
|
|
8
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await w()}}),l(!1);return}await w()}catch(S){let
|
|
8
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await w()}}),l(!1);return}await w()}catch(S){let X=S instanceof Error?S.message:"Failed to test connection";r(Oe,{title:"Connection Test Failed",message:`${X}
|
|
9
9
|
|
|
10
|
-
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await w()}}),l(!1)}},f=async()=>{let m=Object.values(T).some(S=>S&&S.length>0);try{d(!0),u(null);let S;m?S=await q.integration.testCredentials({type:t.type,config:T}):S=await q.integration.testConnection(t.id),u(S),S.status==="success"?Co.success(S.message||"Connection successful"):Co.error(S.message||"Connection failed")}catch(S){let J=S instanceof Error?S.message:"Connection test failed";u({status:"error",message:J}),Co.error(J)}finally{d(!1)}},A=()=>{r(La,{integration:t,onSuccess:()=>{n?.(),s()}})},C=It(t.type)?.formFields,h=()=>t.type==="database"?Me(Vi,{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:T.url||""}):C?C.map(m=>m.type==="password"?Me(Vi,{configKey:m.configKey,fieldId:m.id,helpLink:m.helpLink,helpText:m.helpText,label:m.label,onChange:y,placeholder:m.placeholder,value:T[m.configKey]||""},m.id):dt("div",{className:"space-y-2",children:[Me(F,{htmlFor:m.id,children:m.label}),Me(se,{id:m.id,onChange:S=>y(m.configKey,S.target.value),placeholder:m.placeholder,type:m.type,value:T[m.configKey]||""}),(m.helpText||m.helpLink)&&dt("p",{className:"text-muted-foreground text-xs",children:[m.helpText,m.helpLink&&Me("a",{className:"underline hover:text-foreground",href:m.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:m.helpLink.text})]})]},m.id)):null;return dt(De,{actions:[{label:"Delete",variant:"ghost",onClick:A,disabled:a||i},{label:"Test",variant:"outline",onClick:f,loading:i,disabled:a},{label:"Update",onClick:k,loading:a}],overlayId:e,title:`Edit ${Zu(t.type)}`,children:[Me("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),dt("div",{className:"space-y-4",children:[h(),dt("div",{className:"space-y-2",children:[Me(F,{htmlFor:"name",children:"Label (Optional)"}),Me(se,{id:"name",onChange:m=>g(m.target.value),placeholder:"e.g. Production, Personal, Work",value:p})]})]})]})}function La({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=ne(),r=qu(Ht),[s,a]=so(!1),[l,i]=so(!0);return dt(De,{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 q.integration.delete(t.id),Co.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Co.error("Failed to delete connection"),a(!1)}},loading:s}],overlayId:e,title:"Delete Connection",children:[Me("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&&dt("div",{className:"mt-4 flex items-center gap-2",children:[Me(Bi,{checked:l,id:"revoke-key",onCheckedChange:c=>i(c)}),Me(F,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as za,jsx as Se,jsxs as Wt}from"react/jsx-runtime";function Ui({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:s}){let{push:a}=ne(),[l,i]=Or(mt),d=Gi(Pt),c=Hi(Pt),u=rm(d),[p,g]=$i(!1),T=Gi(Ht),[v,y]=Or(xo),[w,k]=$i(!1),[f,A]=Or(Sr),[I,C]=Or(ki),h=Hi(Ir),m=nm(()=>l.filter(b=>b.type===e),[l,e]),S=l.length>0,J=Dn(async()=>{try{let b=await q.integration.getAll();i(b),g(!0)}catch(b){console.error("Failed to load integrations:",b)}},[i]);on(()=>{T?.integrationType===e&&!w&&T.api.getStatus().then(b=>{y(b),k(!0)}).catch(()=>{k(!0)})},[e,w,T,y]),on(()=>{T?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!I&&(h(!0),T.api.getTeams().then(b=>{A(b.teams),b.teams.length>0&&C(!0)}).catch(()=>{}).finally(()=>{h(!1)}))},[e,T,v,I,A,C,h]),on(()=>{T?.integrationType===e&&v?.enabled&&v?.isVercelUser&&T.api.getTeams().then(b=>{b.teams.length>0&&(A(b.teams),C(!0))}).catch(()=>{})},[e,T,v?.enabled,v?.isVercelUser]),on(()=>{J()},[J,e]),on(()=>{d!==u.current&&(u.current=d,J())},[d,J]),on(()=>{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 D=async b=>{await J(),o(b),c(R=>R+1)},j=async()=>{if(await J(),c(b=>b+1),T?.integrationType===e){let b=await T.api.getStatus();y(b)}},z=Dn(()=>{a(ro,{type:e,onSuccess:D})},[e,a,D]),re=Dn(b=>{a(Rr,{integration:b,onSuccess:j,onDelete:j})},[a,j]),P=T?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!v?.hasManagedKey,V=Dn(async b=>{if(await J(),o(b),c(R=>R+1),T){let R=await T.api.getStatus();y(R)}},[J,o,c,T,y]),X=Dn(()=>{s?s():P&&T?a(T.ConsentOverlay,{onConsent:V,onManualEntry:z}):z()},[s,P,T,a,V,z]);if(!S&&!p)return Se("div",{className:"flex flex-col gap-1",children:Wt("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 U=It(e)?.label||e,N=m.filter(b=>b.isManaged),M=m.filter(b=>!b.isManaged);if(m.length===0)return Se(za,{children:Wt(O,{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:[Se(em,{className:"size-4"}),Wt("span",{className:"flex-1 text-left",children:["Add ",U," connection"]}),Se(tm,{className:"size-4"})]})});if(m.length===1){let b=m[0],R=b.name||`${U} API Key`;return Se(za,{children:Wt("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(Ma,{className:"size-4 shrink-0 text-green-600"}),Se("span",{className:"flex-1 truncate",children:R}),Se(O,{className:"size-6 shrink-0",disabled:r,onClick:()=>re(b),size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]})})}return Se(za,{children:Wt("div",{className:"flex flex-col gap-1",children:[N.map(b=>{let R=t===b.id,G=b.name||`${U} API Key`;return Wt("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:[Wt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(b.id),type:"button",children:[R?Se(Ma,{className:"size-4 shrink-0"}):Se(_i,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(O,{className:"size-6 shrink-0",disabled:r,onClick:te=>{te.stopPropagation(),re(b)},size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]},b.id)}),M.map(b=>{let R=t===b.id,G=b.name||`${U} API Key`;return Wt("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:[Wt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(b.id),type:"button",children:[R?Se(Ma,{className:"size-4 shrink-0"}):Se(_i,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(O,{className:"size-6 shrink-0",disabled:r,onClick:te=>{te.stopPropagation(),re(b)},size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]},b.id)}),n&&Wt("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(om,{className:"size-4 shrink-0"}),Se("span",{children:"Manage all connections"})]})]})})}import*as xt from"@radix-ui/react-tooltip";import{jsx as nn,jsxs as am}from"react/jsx-runtime";function rn({delayDuration:e=0,...t}){return nn(xt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Rn({...e}){return nn(rn,{children:nn(xt.Root,{"data-slot":"tooltip",...e})})}function On({...e}){return nn(xt.Trigger,{"data-slot":"tooltip-trigger",...e})}function Ln({className:e,sideOffset:t=0,children:o,...n}){return nn(xt.Portal,{children:am(xt.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,nn(xt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as cm}from"lucide-react";import{useState as um}from"react";import{useAtom as Ki}from"jotai";import{useEffect as Wa,useRef as Ba,useState as an}from"react";import{Fragment as lm,jsx as Va,jsxs as dm}from"react/jsx-runtime";function sm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function im(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(d=>d.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let d=s.data.config?.actionType;d&&(a=pe(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let i=r.substring(l+1);return a?`${a}.${i}`:r}function ji({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s,rows:a=3}){let[l,i]=an(!1),d=Ba(null),[c,u]=an(e),p=Ba(!0),[g]=Ki(be),[T]=Ki(oe),[v,y]=an(!1),[w,k]=an({top:0,left:0}),[f,A]=an(""),[I,C]=an(null),h=Ba(null);Wa(()=>{e!==c&&!l&&(u(e),p.current=!0)},[e,l,c]),Wa(()=>{!l&&c&&(p.current=!0)},[T,l,c]);let m=()=>{if(!d.current)return null;let N=window.getSelection();if(!N||N.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let M=N.getRangeAt(0),b=M.cloneRange();b.selectNodeContents(d.current),b.setEnd(M.endContainer,M.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",M.endContainer,"endOffset",M.endOffset);let R=0,G=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),te,de=!1;for(;(te=G.nextNode())&&!de;)if(te.nodeType===Node.TEXT_NODE)if(te===M.endContainer)R+=M.endOffset,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",R);else{let B=(te.textContent||"").length;R+=B,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",B)}else if(te.nodeType===Node.ELEMENT_NODE){let B=te,xe=B.getAttribute("data-template");xe?B.contains(M.endContainer)||B===M.endContainer?(R+=xe.length,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",R)):(R+=xe.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",xe.length)):B.tagName==="BR"&&(B===M.endContainer||B.contains(M.endContainer)?de=!0:(R+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",R),{offset:R}},S=N=>{if(!d.current||!N)return;let M=0,b=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),R,G=null,te=0;for(;R=b.nextNode();)if(R.nodeType===Node.TEXT_NODE){let de=(R.textContent||"").length;if(M+de>=N.offset){G=R,te=N.offset-M;break}M+=de}else if(R.nodeType===Node.ELEMENT_NODE){let de=R,B=de.getAttribute("data-template");if(B){if(M+B.length>=N.offset){G=de.nextSibling,te=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}M+=B.length}else if(de.tagName==="BR"){if(M+1>=N.offset){G=de.nextSibling,te=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}M+=1}}if(G){let de=document.createRange(),B=window.getSelection();try{de.setStart(G,Math.min(te,G.textContent?.length||0)),de.collapse(!0),B?.removeAllRanges(),B?.addRange(de),d.current.focus()}catch{d.current.focus()}}},J=()=>{if(!d.current||!p.current)return;let N=d.current,M=c||"",b=l?m():null;if(h.current!==null&&(b={offset:h.current},h.current=null),N.innerHTML="",!M&&!l){N.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let R=/\{\{@([^:]+):([^}]+)\}\}/g,G=0,te;for(;(te=R.exec(M))!==null;){let[de,,B]=te,xe=te.index;if(xe>G){let He=M.slice(G,xe);D(N,He)}let qe=document.createElement("span"),Ye=sm(de,T);qe.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",qe.contentEditable="false",qe.setAttribute("data-template",de),qe.textContent=im(de,T),N.appendChild(qe),G=R.lastIndex}if(G<M.length){let de=M.slice(G);D(N,de)}N.innerHTML===""&&l&&(N.innerHTML="<br>"),p.current=!1,b&&requestAnimationFrame(()=>S(b))},D=(N,M)=>{let b=M.split(`
|
|
11
|
-
`);b.forEach((
|
|
12
|
-
`,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",N),N},
|
|
13
|
-
`)){if(
|
|
14
|
-
`)){if(
|
|
10
|
+
Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{await w()}}),l(!1)}},f=async()=>{let m=Object.values(C).some(S=>S&&S.length>0);try{d(!0),u(null);let S;m?S=await j.integration.testCredentials({type:t.type,config:C}):S=await j.integration.testConnection(t.id),u(S),S.status==="success"?Co.success(S.message||"Connection successful"):Co.error(S.message||"Connection failed")}catch(S){let X=S instanceof Error?S.message:"Connection test failed";u({status:"error",message:X}),Co.error(X)}finally{d(!1)}},T=()=>{r(La,{integration:t,onSuccess:()=>{n?.(),s()}})},A=It(t.type)?.formFields,h=()=>t.type==="database"?Me(Vi,{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||""}):A?A.map(m=>m.type==="password"?Me(Vi,{configKey:m.configKey,fieldId:m.id,helpLink:m.helpLink,helpText:m.helpText,label:m.label,onChange:y,placeholder:m.placeholder,value:C[m.configKey]||""},m.id):dt("div",{className:"space-y-2",children:[Me(W,{htmlFor:m.id,children:m.label}),Me(ae,{id:m.id,onChange:S=>y(m.configKey,S.target.value),placeholder:m.placeholder,type:m.type,value:C[m.configKey]||""}),(m.helpText||m.helpLink)&&dt("p",{className:"text-muted-foreground text-xs",children:[m.helpText,m.helpLink&&Me("a",{className:"underline hover:text-foreground",href:m.helpLink.url,rel:"noopener noreferrer",target:"_blank",children:m.helpLink.text})]})]},m.id)):null;return dt(De,{actions:[{label:"Delete",variant:"ghost",onClick:T,disabled:a||i},{label:"Test",variant:"outline",onClick:f,loading:i,disabled:a},{label:"Update",onClick:k,loading:a}],overlayId:e,title:`Edit ${em(t.type)}`,children:[Me("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your connection credentials"}),dt("div",{className:"space-y-4",children:[h(),dt("div",{className:"space-y-2",children:[Me(W,{htmlFor:"name",children:"Label (Optional)"}),Me(ae,{id:"name",onChange:m=>g(m.target.value),placeholder:"e.g. Production, Personal, Work",value:p})]})]})]})}function La({overlayId:e,integration:t,onSuccess:o}){let{pop:n}=ne(),r=Yu(Ht),[s,a]=so(!1),[l,i]=so(!0);return dt(De,{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),Co.success("Connection deleted"),o?.()}catch(c){console.error("Failed to delete integration:",c),Co.error("Failed to delete connection"),a(!1)}},loading:s}],overlayId:e,title:"Delete Connection",children:[Me("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&&dt("div",{className:"mt-4 flex items-center gap-2",children:[Me(Bi,{checked:l,id:"revoke-key",onCheckedChange:c=>i(c)}),Me(W,{className:"cursor-pointer font-normal",htmlFor:"revoke-key",children:"Revoke API key from Vercel"})]})]})}import{Fragment as za,jsx as Se,jsxs as Wt}from"react/jsx-runtime";function Ui({integrationType:e,value:t,onChange:o,onOpenSettings:n,disabled:r,onAddConnection:s}){let{push:a}=ne(),[l,i]=Lr(mt),d=Gi(Pt),c=Hi(Pt),u=am(d),[p,g]=$i(!1),C=Gi(Ht),[v,y]=Lr(xo),[w,k]=$i(!1),[f,T]=Lr(Ir),[I,A]=Lr(ki),h=Hi(Pr),m=rm(()=>l.filter(b=>b.type===e),[l,e]),S=l.length>0,X=Dn(async()=>{try{let b=await j.integration.getAll();i(b),g(!0)}catch(b){console.error("Failed to load integrations:",b)}},[i]);on(()=>{C?.integrationType===e&&!w&&C.api.getStatus().then(b=>{y(b),k(!0)}).catch(()=>{k(!0)})},[e,w,C,y]),on(()=>{C?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!I&&(h(!0),C.api.getTeams().then(b=>{T(b.teams),b.teams.length>0&&A(!0)}).catch(()=>{}).finally(()=>{h(!1)}))},[e,C,v,I,T,A,h]),on(()=>{C?.integrationType===e&&v?.enabled&&v?.isVercelUser&&C.api.getTeams().then(b=>{b.teams.length>0&&(T(b.teams),A(!0))}).catch(()=>{})},[e,C,v?.enabled,v?.isVercelUser]),on(()=>{X()},[X,e]),on(()=>{d!==u.current&&(u.current=d,X())},[d,X]),on(()=>{if(m.length>0&&!r&&!(t&&m.some(D=>D.id===t))){let D=m.find(G=>G.isManaged);o(D?.id||m[0].id)}},[m,t,r,o]);let le=async b=>{await X(),o(b),c(D=>D+1)},L=async()=>{if(await X(),c(b=>b+1),C?.integrationType===e){let b=await C.api.getStatus();y(b)}},F=Dn(()=>{a(ro,{type:e,onSuccess:le})},[e,a,le]),_=Dn(b=>{a(Or,{integration:b,onSuccess:L,onDelete:L})},[a,L]),P=C?.integrationType===e&&v?.enabled&&v?.isVercelUser&&!v?.hasManagedKey,V=Dn(async b=>{if(await X(),o(b),c(D=>D+1),C){let D=await C.api.getStatus();y(D)}},[X,o,c,C,y]),Y=Dn(()=>{s?s():P&&C?a(C.ConsentOverlay,{onConsent:V,onManualEntry:F}):F()},[s,P,C,a,V,F]);if(!S&&!p)return Se("div",{className:"flex flex-col gap-1",children:Wt("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=It(e)?.label||e,N=m.filter(b=>b.isManaged),z=m.filter(b=>!b.isManaged);if(m.length===0)return Se(za,{children:Wt(R,{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:Y,variant:"outline",children:[Se(tm,{className:"size-4"}),Wt("span",{className:"flex-1 text-left",children:["Add ",K," connection"]}),Se(om,{className:"size-4"})]})});if(m.length===1){let b=m[0],D=b.name||`${K} API Key`;return Se(za,{children:Wt("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(Ma,{className:"size-4 shrink-0 text-green-600"}),Se("span",{className:"flex-1 truncate",children:D}),Se(R,{className:"size-6 shrink-0",disabled:r,onClick:()=>_(b),size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]})})}return Se(za,{children:Wt("div",{className:"flex flex-col gap-1",children:[N.map(b=>{let D=t===b.id,G=b.name||`${K} API Key`;return Wt("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",D?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Wt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(b.id),type:"button",children:[D?Se(Ma,{className:"size-4 shrink-0"}):Se(_i,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(R,{className:"size-6 shrink-0",disabled:r,onClick:te=>{te.stopPropagation(),_(b)},size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]},b.id)}),z.map(b=>{let D=t===b.id,G=b.name||`${K} API Key`;return Wt("div",{className:x("flex w-full items-center gap-2 rounded-md px-[13px] py-1.5 text-sm transition-colors",D?"bg-primary/10 text-primary":"hover:bg-muted/50",r&&"cursor-not-allowed opacity-50"),children:[Wt("button",{className:"flex flex-1 items-center gap-2 text-left",disabled:r,onClick:()=>o(b.id),type:"button",children:[D?Se(Ma,{className:"size-4 shrink-0"}):Se(_i,{className:"size-4 shrink-0 text-muted-foreground"}),Se("span",{className:"truncate",children:G})]}),Se(R,{className:"size-6 shrink-0",disabled:r,onClick:te=>{te.stopPropagation(),_(b)},size:"icon",variant:"ghost",children:Se(Fa,{className:"size-3"})})]},b.id)}),n&&Wt("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(nm,{className:"size-4 shrink-0"}),Se("span",{children:"Manage all connections"})]})]})})}import*as xt from"@radix-ui/react-tooltip";import{jsx as nn,jsxs as sm}from"react/jsx-runtime";function rn({delayDuration:e=0,...t}){return nn(xt.Provider,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function Rn({...e}){return nn(rn,{children:nn(xt.Root,{"data-slot":"tooltip",...e})})}function On({...e}){return nn(xt.Trigger,{"data-slot":"tooltip-trigger",...e})}function Ln({className:e,sideOffset:t=0,children:o,...n}){return nn(xt.Portal,{children:sm(xt.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,nn(xt.Arrow,{className:"bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]"})]})})}import{ChevronDown as um}from"lucide-react";import{useState as mm}from"react";import{useAtom as Ki}from"jotai";import{useEffect as Wa,useRef as Ba,useState as an}from"react";import{Fragment as dm,jsx as Va,jsxs as cm}from"react/jsx-runtime";function im(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return!1;let n=o[1];return t.some(r=>r.id===n)}function lm(e,t){let o=e.match(/\{\{@([^:]+):([^}]+)\}\}/);if(!o)return e;let n=o[1],r=o[2],s=t.find(d=>d.id===n);if(!s)return r;let a=s.data.label;if(!a&&s.data.type==="action"){let d=s.data.config?.actionType;d&&(a=pe(d)?.label)}let l=r.indexOf(".");if(l===-1)return a??r;let i=r.substring(l+1);return a?`${a}.${i}`:r}function ji({value:e="",onChange:t,placeholder:o,disabled:n,className:r,id:s,rows:a=3}){let[l,i]=an(!1),d=Ba(null),[c,u]=an(e),p=Ba(!0),[g]=Ki(be),[C]=Ki(oe),[v,y]=an(!1),[w,k]=an({top:0,left:0}),[f,T]=an(""),[I,A]=an(null),h=Ba(null);Wa(()=>{e!==c&&!l&&(u(e),p.current=!0)},[e,l,c]),Wa(()=>{!l&&c&&(p.current=!0)},[C,l,c]);let m=()=>{if(!d.current)return null;let N=window.getSelection();if(!N||N.rangeCount===0)return console.log("[Textarea] saveCursorPosition: No selection"),null;let z=N.getRangeAt(0),b=z.cloneRange();b.selectNodeContents(d.current),b.setEnd(z.endContainer,z.endOffset),console.log("[Textarea] saveCursorPosition: range.endContainer",z.endContainer,"endOffset",z.endOffset);let D=0,G=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),te,de=!1;for(;(te=G.nextNode())&&!de;)if(te.nodeType===Node.TEXT_NODE)if(te===z.endContainer)D+=z.endOffset,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in text node, offset:",D);else{let B=(te.textContent||"").length;D+=B,console.log("[Textarea] saveCursorPosition: Text node before cursor, length:",B)}else if(te.nodeType===Node.ELEMENT_NODE){let B=te,xe=B.getAttribute("data-template");xe?B.contains(z.endContainer)||B===z.endContainer?(D+=xe.length,de=!0,console.log("[Textarea] saveCursorPosition: Found cursor in badge, offset:",D)):(D+=xe.length,console.log("[Textarea] saveCursorPosition: Badge before cursor, length:",xe.length)):B.tagName==="BR"&&(B===z.endContainer||B.contains(z.endContainer)?de=!0:(D+=1,console.log("[Textarea] saveCursorPosition: BR before cursor")))}return console.log("[Textarea] saveCursorPosition: Final offset:",D),{offset:D}},S=N=>{if(!d.current||!N)return;let z=0,b=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),D,G=null,te=0;for(;D=b.nextNode();)if(D.nodeType===Node.TEXT_NODE){let de=(D.textContent||"").length;if(z+de>=N.offset){G=D,te=N.offset-z;break}z+=de}else if(D.nodeType===Node.ELEMENT_NODE){let de=D,B=de.getAttribute("data-template");if(B){if(z+B.length>=N.offset){G=de.nextSibling,te=0,!G&&de.parentNode&&(G=document.createTextNode(""),de.parentNode.appendChild(G));break}z+=B.length}else if(de.tagName==="BR"){if(z+1>=N.offset){G=de.nextSibling,te=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(te,G.textContent?.length||0)),de.collapse(!0),B?.removeAllRanges(),B?.addRange(de),d.current.focus()}catch{d.current.focus()}}},X=()=>{if(!d.current||!p.current)return;let N=d.current,z=c||"",b=l?m():null;if(h.current!==null&&(b={offset:h.current},h.current=null),N.innerHTML="",!z&&!l){N.innerHTML=`<span class="text-muted-foreground pointer-events-none">${o||""}</span>`;return}let D=/\{\{@([^:]+):([^}]+)\}\}/g,G=0,te;for(;(te=D.exec(z))!==null;){let[de,,B]=te,xe=te.index;if(xe>G){let He=z.slice(G,xe);le(N,He)}let qe=document.createElement("span"),Ye=im(de,C);qe.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",qe.contentEditable="false",qe.setAttribute("data-template",de),qe.textContent=lm(de,C),N.appendChild(qe),G=D.lastIndex}if(G<z.length){let de=z.slice(G);le(N,de)}N.innerHTML===""&&l&&(N.innerHTML="<br>"),p.current=!1,b&&requestAnimationFrame(()=>S(b))},le=(N,z)=>{let b=z.split(`
|
|
11
|
+
`);b.forEach((D,G)=>{D&&N.appendChild(document.createTextNode(D)),G<b.length-1&&N.appendChild(document.createElement("br"))})},L=()=>{if(!d.current)return"";let N="",z=document.createTreeWalker(d.current,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,null),b;for(;b=z.nextNode();)if(b.nodeType===Node.TEXT_NODE){let D=b.parentElement,G=!1;for(;D&&D!==d.current;){if(D.getAttribute("data-template")){G=!0;break}D=D.parentElement}G?console.log("[Textarea] extractValue: Skipping text inside badge:",b.textContent):(N+=b.textContent,console.log("[Textarea] extractValue: Adding text node:",b.textContent))}else if(b.nodeType===Node.ELEMENT_NODE){let D=b,G=D.getAttribute("data-template");G?(N+=G,console.log("[Textarea] extractValue: Adding template:",G)):D.tagName==="BR"&&(N+=`
|
|
12
|
+
`,console.log("[Textarea] extractValue: Adding line break"))}return console.log("[Textarea] extractValue: Final result:",N),N},F=()=>{let N=L();if(console.log("[Textarea] handleInput: newValue:",N),console.log("[Textarea] handleInput: internalValue:",c),console.log("[Textarea] handleInput: DOM innerHTML:",d.current?.innerHTML),N===c){console.log("[Textarea] handleInput: No change detected, ignoring");return}let z=(c.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length,b=(N.match(/\{\{@([^:]+):([^}]+)\}\}/g)||[]).length;if(console.log("[Textarea] handleInput: oldTemplates:",z,"newTemplates:",b),b>z){console.log("[Textarea] handleInput: New template added, rendering badge"),u(N),t?.(N),p.current=!0,y(!1),requestAnimationFrame(()=>X());return}if(b===z&&b>0){console.log("[Textarea] handleInput: Typing around existing badges, NOT updating display"),u(N),t?.(N);let G=N.lastIndexOf("@");if(G!==-1){let te=N.slice(G+1);if(!te.includes(" ")&&!te.includes(`
|
|
13
|
+
`)){if(T(te),A(G),d.current){let de=d.current.getBoundingClientRect(),B={top:de.bottom+window.scrollY+4,left:de.left+window.scrollX};k(B)}y(!0)}else y(!1)}else y(!1);return}if(b<z){console.log("[Textarea] handleInput: Template removed, updating display"),u(N),t?.(N),p.current=!0,requestAnimationFrame(()=>X());return}console.log("[Textarea] handleInput: Normal typing, no badges"),u(N),t?.(N);let D=N.lastIndexOf("@");if(D!==-1){let G=N.slice(D+1);if(!G.includes(" ")&&!G.includes(`
|
|
14
|
+
`)){if(T(G),A(D),d.current){let te=d.current.getBoundingClientRect(),de={top:te.bottom+window.scrollY+4,left:te.left+window.scrollX};k(de)}y(!0)}else y(!1)}else y(!1)},_=N=>{if(!d.current||I===null)return;let z=L(),b=z.slice(0,I),D=z.slice(I+1+f.length),G=b+N+D,te=b.length+N.length;console.log("[Textarea] Autocomplete select:",{currentText:z,atSignPosition:I,filter:f,template:N,beforeAt:b,afterFilter:D,newText:G,targetCursorPosition:te}),u(G),t?.(G),p.current=!0,y(!1),A(null),h.current=te,d.current.focus()},P=()=>{i(!0),p.current=!0},V=()=>{setTimeout(()=>{document.activeElement!==d.current&&(i(!1),p.current=!0,y(!1))},200)},Y=N=>{N.preventDefault();let z=N.clipboardData.getData("text/plain");document.execCommand("insertText",!1,z)},M=N=>{N.key==="Enter"&&(N.preventDefault(),document.execCommand("insertLineBreak"))};Wa(()=>{p.current&&X()},[c,l]);let K=`${a*1.5}rem`;return cm(dm,{children:[Va("div",{className:x("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:K},children:Va("div",{className:"w-full outline-none whitespace-pre-wrap break-words",contentEditable:!n,id:s,onBlur:V,onFocus:P,onInput:F,onKeyDown:M,onPaste:Y,ref:d,role:"textbox",suppressContentEditableWarning:!0})}),Va(Tr,{currentNodeId:g||void 0,filter:f,isOpen:v,onClose:()=>y(!1),onSelect:_,position:w})]})}import{Fragment as xm,jsx as Xe,jsxs as Mn}from"react/jsx-runtime";function pm({field:e,value:t,onChange:o,disabled:n}){return Xe(We,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,value:t})}function fm({field:e,value:t,onChange:o,disabled:n}){return Xe(ji,{disabled:n,id:e.key,onChange:o,placeholder:e.placeholder,rows:e.rows||4,value:t})}function gm({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 ym({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 vm({field:e,value:t,onChange:o,disabled:n}){return e.options?Mn(ke,{disabled:n,onValueChange:o,value:t,children:[Xe(Te,{className:"w-full",id:e.key,children:Xe(Ce,{placeholder:e.placeholder})}),Xe(Ae,{children:e.options.map(r=>Xe(se,{value:r.value,children:r.label},r.value))})]}):null}function hm(e){return Xe(no,{disabled:e.disabled,onChange:t=>e.onChange(JSON.stringify(t)),schema:e.value?JSON.parse(e.value):[]})}var bm={"template-input":pm,"template-textarea":fm,text:gm,number:ym,select:vm,"schema-builder":hm};function qi(e,t,o,n){if(e.showWhen&&t[e.showWhen.field]!==e.showWhen.equals)return null;let r=t[e.key]||e.defaultValue||"",s=bm[e.type];return Mn("div",{className:"space-y-2",children:[Mn(W,{className:"ml-1",htmlFor:e.key,children:[e.label,e.required&&Xe("span",{className:"text-red-500",children:"*"})]}),Xe(s,{disabled:n,field:e,onChange:a=>o(e.key,a),value:r})]},e.key)}function wm({label:e,fields:t,config:o,onUpdateConfig:n,disabled:r,defaultExpanded:s=!1}){let[a,l]=mm(s);return Mn("div",{className:"space-y-2",children:[Mn("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(um,{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(i=>qi(i,o,n,r))})]})}function Yi({fields:e,config:t,onUpdateConfig:o,disabled:n}){return Xe(xm,{children:e.map(r=>Gs(r)?Xe(wm,{config:t,defaultExpanded:r.defaultExpanded,disabled:n,fields:r.fields,label:r.label,onUpdateConfig:o},`group-${r.label}`):qi(r,t,o,n))})}import{Fragment as Dm,jsx as fe,jsxs as yt}from"react/jsx-runtime";function Im({actionType:e,config:t,onUpdateConfig:o,disabled:n}){switch(e){case"HTTP Request":return fe(gi,{config:t,disabled:n,onUpdateConfig:o});case"Database Query":return fe(fi,{config:t,disabled:n,onUpdateConfig:o});case"Condition":return fe(pi,{config:t,disabled:n,onUpdateConfig:o});case"Loop":return fe(yi,{config:t,disabled:n,onUpdateConfig:o});case"Merge":return fe(vi,{config:t,disabled:n,onUpdateConfig:o});case"Switch":return fe(hi,{config:t,disabled:n,onUpdateConfig:o});default:return null}}var Zi=[{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"}],Ga=Zi.map(e=>e.id),Xi={"Database Query":"database"};function Pm(){return Mr(()=>{let e=Ws(),t={System:Zi};for(let[o,n]of Object.entries(e))t[o]=n.map(r=>({id:r.id,label:r.label}));return t},[])}function Qi(e){if(Ga.includes(e))return"System";let t=pe(e);return t?.category?t.category:null}function Em(e){if(Ga.includes(e))return e;let t=pe(e);return t?t.id:e}function Fr({config:e,onUpdateConfig:t,disabled:o,isOwner:n=!0}){let r=e?.actionType||"",s=Pm(),a=Mr(()=>Fs(),[]),l=r?Qi(r):null,[i,d]=Sm(l||""),c=Nm(Pt),u=Ji(mt),{push:p}=ne(),g=Ji(Sr);Am(()=>{let m=r?Qi(r):null;d(m||"")},[r]);let C=m=>{d(m);let S=s[m]?.[0];S&&t("actionType",S.id)},v=m=>{t("actionType",m)},y=(m,S)=>{t(m,String(S))},w=r?pe(r):null,k=Mr(()=>{if(!r)return;if(Xi[r])return Xi[r];let S=pe(r)?.integration;if(!(S&&!Fo(S)))return S},[r]),f=k==="ai-gateway"&&g?.enabled&&g?.isVercelUser,T=Mr(()=>k?u.some(m=>m.type===k):!1,[k,u]),I=m=>{t("integrationId",m),c(S=>S+1)},A=()=>{k&&p(ro,{type:k,onSuccess:m=>{c(S=>S+1),t("integrationId",m)}})},h=()=>{f?p(Wi,{onConsent:I,onManualEntry:A}):A()};return yt(Dm,{children:[yt("div",{className:"grid grid-cols-2 gap-2",children:[yt("div",{className:"space-y-2",children:[fe(W,{className:"ml-1",htmlFor:"actionCategory",children:"Service"}),yt(ke,{disabled:o,onValueChange:C,value:i||void 0,children:[fe(Te,{className:"w-full",id:"actionCategory",children:fe(Ce,{placeholder:"Select category"})}),yt(Ae,{children:[fe(se,{value:"System",children:yt("div",{className:"flex items-center gap-2",children:[fe(Tm,{className:"size-4"}),fe("span",{children:"System"})]})}),fe(Nr,{}),a.map(m=>fe(se,{value:m.label,children:yt("div",{className:"flex items-center gap-2",children:[fe(Rt,{className:"size-4",integration:m.type}),fe("span",{children:m.label})]})},m.type))]})]})]}),yt("div",{className:"space-y-2",children:[fe(W,{className:"ml-1",htmlFor:"actionType",children:"Action"}),yt(ke,{disabled:o||!i,onValueChange:v,value:Em(r)||void 0,children:[fe(Te,{className:"w-full",id:"actionType",children:fe(Ce,{placeholder:"Select action"})}),fe(Ae,{children:i&&s[i]?.map(m=>fe(se,{value:m.id,children:m.label},m.id))})]})]})]}),k&&n&&yt("div",{className:"space-y-2",children:[yt("div",{className:"ml-1 flex items-center justify-between",children:[yt("div",{className:"flex items-center gap-1",children:[fe(W,{children:"Connection"}),fe(rn,{children:yt(Rn,{children:[fe(On,{asChild:!0,children:fe(km,{className:"size-3.5 text-muted-foreground"})}),fe(Ln,{children:fe("p",{children:"API key or OAuth credentials for this service"})})]})})]}),T&&fe(R,{className:"size-6",disabled:o,onClick:h,size:"icon",variant:"ghost",children:fe(Cm,{className:"size-4"})})]}),fe(Ui,{disabled:o,integrationType:k,onChange:m=>t("integrationId",m),value:e?.integrationId||""})]}),fe(Im,{actionType:e?.actionType||"",config:e,disabled:o,onUpdateConfig:t}),w&&!Ga.includes(r)&&fe(Yi,{config:e,disabled:o,fields:w.configFields,onUpdateConfig:y})]})}import{ChevronRight as Hm,Eye as il,EyeOff as ll,Grid3X3 as _m,List as $m,MoreHorizontal as Um,Search as Km,Settings as cl,Zap as ul}from"lucide-react";import{useEffect as jm,useMemo as Ha,useRef as qm,useState as zn}from"react";import{Repeat as Rm}from"lucide-react";import{jsx as Om}from"react/jsx-runtime";var zr={id:"Loop",label:"Loop",description:"Loop through a list of items",category:"System",icon:Om(Rm,{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,7 +39,7 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
39
39
|
items,
|
|
40
40
|
batchSize,
|
|
41
41
|
};
|
|
42
|
-
}`};import{Merge as
|
|
42
|
+
}`};import{Merge as Lm}from"lucide-react";import{jsx as Mm}from"react/jsx-runtime";var Wr={id:"Merge",label:"Merge",description:"Combine data from two inputs",category:"System",icon:Mm(Lm,{className:"size-12 text-orange-300",strokeWidth:1.5}),codeGenerator:`export async function mergeStep(input: {
|
|
43
43
|
input1: unknown[];
|
|
44
44
|
input2: unknown[];
|
|
45
45
|
mode: "append" | "combineByPosition" | "combineByFields";
|
|
@@ -121,7 +121,7 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
121
121
|
}
|
|
122
122
|
|
|
123
123
|
return { merged: [...items1, ...items2], totalItems: items1.length + items2.length };
|
|
124
|
-
}`};import{ArrowLeftRight as
|
|
124
|
+
}`};import{ArrowLeftRight as Fm}from"lucide-react";import{jsx as zm}from"react/jsx-runtime";var Br={id:"Switch",label:"Switch",description:"Route based on rules or values",category:"System",icon:zm(Fm,{className:"size-12 text-violet-300",strokeWidth:1.5}),codeGenerator:`export async function switchStep(input: {
|
|
125
125
|
mode: "rules" | "expression";
|
|
126
126
|
switchValue?: string;
|
|
127
127
|
routeName0?: string;
|
|
@@ -164,16 +164,16 @@ Do you want to save anyway?`,confirmLabel:"Save Anyway",onConfirm:async()=>{awai
|
|
|
164
164
|
}
|
|
165
165
|
|
|
166
166
|
return { matchedRouteIndex: -1, matchedRouteName: "Default", isDefault: true };
|
|
167
|
-
}`};import{useEffect as zm,useState as Wm}from"react";function el(){let[e,t]=Wm(void 0);return zm(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as vt}from"radix-ui";import{CheckIcon as aN,ChevronRightIcon as Bm,CircleIcon as Vm}from"lucide-react";import{jsx as ct,jsxs as sl}from"react/jsx-runtime";function To({...e}){return ct(vt.Root,{"data-slot":"dropdown-menu",...e})}function Ao({...e}){return ct(vt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function So({className:e,sideOffset:t=4,...o}){return ct(vt.Portal,{children:ct(vt.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 ht({className:e,inset:t,variant:o="default",...n}){return ct(vt.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 tl({...e}){return ct(vt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Br({className:e,children:t,...o}){return sl(vt.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:[ct("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:ct(vt.ItemIndicator,{children:ct(Vm,{className:"size-2 fill-current"})})}),t]})}function ol({className:e,inset:t,...o}){return ct(vt.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 Fn({className:e,...t}){return ct(vt.Separator,{"data-slot":"dropdown-menu-separator",className:x("bg-border -mx-1 my-1 h-px",e),...t})}function nl({...e}){return ct(vt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function rl({className:e,inset:t,children:o,...n}){return sl(vt.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,ct(Bm,{className:"ml-auto size-4"})]})}function al({className:e,...t}){return ct(vt.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 dl,jsx as me,jsxs as at}from"react/jsx-runtime";var qm=[Bo,zo,Wo,Fr,zr,Wr];function Ym(){return Ha(()=>{let t=zs().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...qm,...t]},[])}function Jm({group:e}){let t=e.actions[0];return t?.integration?me(Rt,{className:"size-4",integration:t.integration}):e.category==="System"?me(cl,{className:"size-4"}):me(ul,{className:"size-4"})}function Xm({action:e,className:t}){return e.integration?me(Rt,{className:t,integration:e.integration}):e.category==="System"?me(cl,{className:x(t,"text-muted-foreground")}):me(ul,{className:x(t,"text-muted-foreground")})}var ml="workflow-action-grid-hidden-groups",pl="workflow-action-grid-view-mode";function Qm(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(ml);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function Zm(){if(typeof window>"u")return"list";try{return localStorage.getItem(pl)==="grid"?"grid":"list"}catch{return"list"}}function Vr({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=zn(""),[s,a]=zn(new Set),[l,i]=zn(Qm),[d,c]=zn(!1),[u,p]=zn(Zm),g=Ym(),T=jm(null),v=el(),y=()=>{let h=u==="list"?"grid":"list";p(h),localStorage.setItem(pl,h)},w=h=>{a(m=>{let S=new Set(m);return S.has(h)?S.delete(h):S.add(h),S})},k=h=>{i(m=>{let S=new Set(m);return S.has(h)?S.delete(h):S.add(h),localStorage.setItem(ml,JSON.stringify([...S])),S})};Km(()=>{o&&v===!1&&T.current&&T.current.focus()},[o,v]);let f=g.filter(h=>{let m=n.toLowerCase();return h.label.toLowerCase().includes(m)||h.description.toLowerCase().includes(m)||h.category.toLowerCase().includes(m)}),A=Ha(()=>{let h={};for(let S of f){let J=S.category;h[J]||(h[J]=[]),h[J].push(S)}return Object.keys(h).sort((S,J)=>S==="System"?-1:J==="System"?1:S.localeCompare(J)).map(S=>({category:S,actions:h[S]}))},[f]),I=Ha(()=>d?A:A.filter(h=>!l.has(h.category)),[A,l,d]),C=l.size;return at("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[at("div",{className:"flex shrink-0 gap-2",children:[at("div",{className:"relative flex-1",children:[me(Um,{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:h=>r(h.target.value),placeholder:"Search actions...",ref:T,value:n})]}),me(rn,{children:at(Rn,{children:[me(On,{asChild:!0,children:me(O,{className:"shrink-0",onClick:y,size:"icon",variant:"ghost",children:u==="list"?me(Hm,{className:"size-4"}):me(_m,{className:"size-4"})})}),me(Ln,{children:u==="list"?"Grid view":"List view"})]})}),C>0&&me(rn,{children:at(Rn,{children:[me(On,{asChild:!0,children:me(O,{className:x("shrink-0",d&&"bg-muted"),onClick:()=>c(!d),size:"icon",variant:"ghost",children:d?me(il,{className:"size-4"}):me(ll,{className:"size-4"})})}),me(Ln,{children:d?"Hide hidden groups":`Show ${C} hidden group${C>1?"s":""}`})]})})]}),at("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[f.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),f.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:f.filter(h=>d||!l.has(h.category)).map(h=>at("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-${h.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(h.id),type:"button",children:[me(Xm,{action:h,className:"size-6"}),me("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:h.label})]},h.id))}),u==="list"&&I.length>0&&I.map((h,m)=>{let S=s.has(h.category),J=l.has(h.category);return at("div",{children:[m>0&&me("div",{className:"my-2 h-px bg-border"}),at("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",J&&"opacity-50"),children:[at("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>w(h.category),type:"button",children:[me(Gm,{className:x("size-3.5 transition-transform",!S&&"rotate-90")}),me(Jm,{group:h}),h.category]}),at(To,{children:[me(Ao,{asChild:!0,children:me("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:me($m,{className:"size-4"})})}),me(So,{align:"end",children:me(ht,{onClick:()=>k(h.category),children:J?at(dl,{children:[me(il,{className:"mr-2 size-4"}),"Show group"]}):at(dl,{children:[me(ll,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!S&&h.actions.map(D=>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-${D.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(D.id),type:"button",children:at("span",{className:"min-w-0 flex-1 truncate",children:[me("span",{className:"font-medium",children:D.label}),D.description&&at("span",{className:"text-muted-foreground text-xs",children:[" ","- ",D.description]})]})},D.id))]},h.category)})]})]})}import{Clock as tp,Copy as op,Play as np,Webhook as rp}from"lucide-react";import{toast as ap}from"sonner";import{jsx as Wn,jsxs as fl}from"react/jsx-runtime";var ep=[{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 gl({value:e,onValueChange:t,disabled:o,id:n}){return fl(ke,{value:e,onValueChange:t,disabled:o,children:[Wn(Te,{id:n,children:Wn(Ce,{placeholder:"Select timezone"})}),Wn(Ae,{children:ep.map(r=>fl(li,{children:[Wn(di,{children:r.label}),r.zones.map(s=>Wn(ie,{value:s.value,children:s.label},s.value))]},r.label))})]})}import{Fragment as _a,jsx as Ie,jsxs as st}from"react/jsx-runtime";function Gr({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),ap.success("Webhook URL copied to clipboard"))};return st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(F,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),st(ke,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[Ie(Te,{className:"w-full",id:"triggerType",children:Ie(Ce,{placeholder:"Select trigger type"})}),st(Ae,{children:[Ie(ie,{value:"Manual",children:st("div",{className:"flex items-center gap-2",children:[Ie(np,{className:"h-4 w-4"}),"Manual"]})}),Ie(ie,{value:"Schedule",children:st("div",{className:"flex items-center gap-2",children:[Ie(tp,{className:"h-4 w-4"}),"Schedule"]})}),Ie(ie,{value:"Webhook",children:st("div",{className:"flex items-center gap-2",children:[Ie(rp,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&&st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(F,{className:"ml-1",children:"Webhook URL"}),st("div",{className:"flex gap-2",children:[Ie(se,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),Ie(O,{disabled:!r,onClick:s,size:"icon",variant:"outline",children:Ie(op,{className:"h-4 w-4"})})]})]}),st("div",{className:"space-y-2",children:[Ie(F,{children:"Request Schema (Optional)"}),Ie(no,{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."})]}),st("div",{className:"space-y-2",children:[Ie(F,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),Ie("div",{className:"overflow-hidden rounded-md border",children:Ie(ft,{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"&&st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(F,{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||""})]}),st("div",{className:"space-y-2",children:[Ie(F,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),Ie(gl,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var yl={"Database Query":Wo.codeGenerator,"HTTP Request":Bo.codeGenerator,Condition:zo.codeGenerator},$a=`async function actionStep(input: Record<string, unknown>) {
|
|
167
|
+
}`};import{useEffect as Wm,useState as Bm}from"react";function el(){let[e,t]=Bm(void 0);return Wm(()=>{let o="ontouchstart"in window||navigator.maxTouchPoints>0||navigator.msMaxTouchPoints>0;t(o)},[]),e}import{DropdownMenu as vt}from"radix-ui";import{CheckIcon as sN,ChevronRightIcon as Vm,CircleIcon as Gm}from"lucide-react";import{jsx as ct,jsxs as sl}from"react/jsx-runtime";function To({...e}){return ct(vt.Root,{"data-slot":"dropdown-menu",...e})}function Ao({...e}){return ct(vt.Trigger,{"data-slot":"dropdown-menu-trigger",...e})}function So({className:e,sideOffset:t=4,...o}){return ct(vt.Portal,{children:ct(vt.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 ht({className:e,inset:t,variant:o="default",...n}){return ct(vt.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 tl({...e}){return ct(vt.RadioGroup,{"data-slot":"dropdown-menu-radio-group",...e})}function Vr({className:e,children:t,...o}){return sl(vt.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:[ct("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:ct(vt.ItemIndicator,{children:ct(Gm,{className:"size-2 fill-current"})})}),t]})}function ol({className:e,inset:t,...o}){return ct(vt.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 Fn({className:e,...t}){return ct(vt.Separator,{"data-slot":"dropdown-menu-separator",className:x("bg-border -mx-1 my-1 h-px",e),...t})}function nl({...e}){return ct(vt.Sub,{"data-slot":"dropdown-menu-sub",...e})}function rl({className:e,inset:t,children:o,...n}){return sl(vt.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,ct(Vm,{className:"ml-auto size-4"})]})}function al({className:e,...t}){return ct(vt.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 dl,jsx as me,jsxs as at}from"react/jsx-runtime";var Ym=[Bo,zo,Wo,zr,Wr,Br];function Jm(){return Ha(()=>{let t=zs().map(o=>({id:o.id,label:o.label,description:o.description,category:o.category,integration:o.integration}));return[...Ym,...t]},[])}function Xm({group:e}){let t=e.actions[0];return t?.integration?me(Rt,{className:"size-4",integration:t.integration}):e.category==="System"?me(cl,{className:"size-4"}):me(ul,{className:"size-4"})}function Qm({action:e,className:t}){return e.integration?me(Rt,{className:t,integration:e.integration}):e.category==="System"?me(cl,{className:x(t,"text-muted-foreground")}):me(ul,{className:x(t,"text-muted-foreground")})}var ml="workflow-action-grid-hidden-groups",pl="workflow-action-grid-view-mode";function Zm(){if(typeof window>"u")return new Set;try{let e=localStorage.getItem(ml);return e?new Set(JSON.parse(e)):new Set}catch{return new Set}}function ep(){if(typeof window>"u")return"list";try{return localStorage.getItem(pl)==="grid"?"grid":"list"}catch{return"list"}}function Gr({onSelectAction:e,disabled:t,isNewlyCreated:o}){let[n,r]=zn(""),[s,a]=zn(new Set),[l,i]=zn(Zm),[d,c]=zn(!1),[u,p]=zn(ep),g=Jm(),C=qm(null),v=el(),y=()=>{let h=u==="list"?"grid":"list";p(h),localStorage.setItem(pl,h)},w=h=>{a(m=>{let S=new Set(m);return S.has(h)?S.delete(h):S.add(h),S})},k=h=>{i(m=>{let S=new Set(m);return S.has(h)?S.delete(h):S.add(h),localStorage.setItem(ml,JSON.stringify([...S])),S})};jm(()=>{o&&v===!1&&C.current&&C.current.focus()},[o,v]);let f=g.filter(h=>{let m=n.toLowerCase();return h.label.toLowerCase().includes(m)||h.description.toLowerCase().includes(m)||h.category.toLowerCase().includes(m)}),T=Ha(()=>{let h={};for(let S of f){let X=S.category;h[X]||(h[X]=[]),h[X].push(S)}return Object.keys(h).sort((S,X)=>S==="System"?-1:X==="System"?1:S.localeCompare(X)).map(S=>({category:S,actions:h[S]}))},[f]),I=Ha(()=>d?T:T.filter(h=>!l.has(h.category)),[T,l,d]),A=l.size;return at("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[at("div",{className:"flex shrink-0 gap-2",children:[at("div",{className:"relative flex-1",children:[me(Km,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),me(ae,{className:"pl-9","data-testid":"action-search-input",disabled:t,id:"action-filter",onChange:h=>r(h.target.value),placeholder:"Search actions...",ref:C,value:n})]}),me(rn,{children:at(Rn,{children:[me(On,{asChild:!0,children:me(R,{className:"shrink-0",onClick:y,size:"icon",variant:"ghost",children:u==="list"?me(_m,{className:"size-4"}):me($m,{className:"size-4"})})}),me(Ln,{children:u==="list"?"Grid view":"List view"})]})}),A>0&&me(rn,{children:at(Rn,{children:[me(On,{asChild:!0,children:me(R,{className:x("shrink-0",d&&"bg-muted"),onClick:()=>c(!d),size:"icon",variant:"ghost",children:d?me(il,{className:"size-4"}):me(ll,{className:"size-4"})})}),me(Ln,{children:d?"Hide hidden groups":`Show ${A} hidden group${A>1?"s":""}`})]})})]}),at("div",{className:"min-h-0 flex-1 overflow-y-auto pb-4","data-testid":"action-grid",children:[f.length===0&&me("p",{className:"py-4 text-center text-muted-foreground text-sm",children:"No actions found"}),f.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:f.filter(h=>d||!l.has(h.category)).map(h=>at("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-${h.id.toLowerCase().replace(/\s+/g,"-")}`,disabled:t,onClick:()=>e(h.id),type:"button",children:[me(Qm,{action:h,className:"size-6"}),me("span",{className:"line-clamp-2 font-medium text-xs leading-tight",children:h.label})]},h.id))}),u==="list"&&I.length>0&&I.map((h,m)=>{let S=s.has(h.category),X=l.has(h.category);return at("div",{children:[m>0&&me("div",{className:"my-2 h-px bg-border"}),at("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:[at("button",{className:"flex flex-1 items-center gap-2 text-left hover:text-foreground",onClick:()=>w(h.category),type:"button",children:[me(Hm,{className:x("size-3.5 transition-transform",!S&&"rotate-90")}),me(Xm,{group:h}),h.category]}),at(To,{children:[me(Ao,{asChild:!0,children:me("button",{className:"rounded p-0.5 hover:bg-muted hover:text-foreground",type:"button",children:me(Um,{className:"size-4"})})}),me(So,{align:"end",children:me(ht,{onClick:()=>k(h.category),children:X?at(dl,{children:[me(il,{className:"mr-2 size-4"}),"Show group"]}):at(dl,{children:[me(ll,{className:"mr-2 size-4"}),"Hide group"]})})})]})]}),!S&&h.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:at("span",{className:"min-w-0 flex-1 truncate",children:[me("span",{className:"font-medium",children:le.label}),le.description&&at("span",{className:"text-muted-foreground text-xs",children:[" ","- ",le.description]})]})},le.id))]},h.category)})]})]})}import{Clock as op,Copy as np,Play as rp,Webhook as ap}from"lucide-react";import{toast as sp}from"sonner";import{jsx as Wn,jsxs as fl}from"react/jsx-runtime";var tp=[{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 gl({value:e,onValueChange:t,disabled:o,id:n}){return fl(ke,{value:e,onValueChange:t,disabled:o,children:[Wn(Te,{id:n,children:Wn(Ce,{placeholder:"Select timezone"})}),Wn(Ae,{children:tp.map(r=>fl(li,{children:[Wn(di,{children:r.label}),r.zones.map(s=>Wn(se,{value:s.value,children:s.label},s.value))]},r.label))})]})}import{Fragment as _a,jsx as Ie,jsxs as st}from"react/jsx-runtime";function Hr({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),sp.success("Webhook URL copied to clipboard"))};return st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(W,{className:"ml-1",htmlFor:"triggerType",children:"Trigger Type"}),st(ke,{disabled:o,onValueChange:a=>t("triggerType",a),value:e?.triggerType||"Manual",children:[Ie(Te,{className:"w-full",id:"triggerType",children:Ie(Ce,{placeholder:"Select trigger type"})}),st(Ae,{children:[Ie(se,{value:"Manual",children:st("div",{className:"flex items-center gap-2",children:[Ie(rp,{className:"h-4 w-4"}),"Manual"]})}),Ie(se,{value:"Schedule",children:st("div",{className:"flex items-center gap-2",children:[Ie(op,{className:"h-4 w-4"}),"Schedule"]})}),Ie(se,{value:"Webhook",children:st("div",{className:"flex items-center gap-2",children:[Ie(ap,{className:"h-4 w-4"}),"Webhook"]})})]})]})]}),e?.triggerType==="Webhook"&&st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(W,{className:"ml-1",children:"Webhook URL"}),st("div",{className:"flex gap-2",children:[Ie(ae,{className:"font-mono text-xs",disabled:!0,value:r||"Save workflow to generate webhook URL"}),Ie(R,{disabled:!r,onClick:s,size:"icon",variant:"outline",children:Ie(np,{className:"h-4 w-4"})})]})]}),st("div",{className:"space-y-2",children:[Ie(W,{children:"Request Schema (Optional)"}),Ie(no,{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."})]}),st("div",{className:"space-y-2",children:[Ie(W,{htmlFor:"webhookMockRequest",children:"Mock Request (Optional)"}),Ie("div",{className:"overflow-hidden rounded-md border",children:Ie(ft,{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"&&st(_a,{children:[st("div",{className:"space-y-2",children:[Ie(W,{className:"ml-1",htmlFor:"scheduleCron",children:"Cron Expression"}),Ie(ae,{disabled:o,id:"scheduleCron",onChange:a=>t("scheduleCron",a.target.value),placeholder:"0 9 * * * (every day at 9am)",value:e?.scheduleCron||""})]}),st("div",{className:"space-y-2",children:[Ie(W,{className:"ml-1",htmlFor:"scheduleTimezone",children:"Timezone"}),Ie(gl,{disabled:o,id:"scheduleTimezone",onValueChange:a=>t("scheduleTimezone",a),value:e?.scheduleTimezone||"America/New_York"})]})]})]})}var yl={"Database Query":Wo.codeGenerator,"HTTP Request":Bo.codeGenerator,Condition:zo.codeGenerator},$a=`async function actionStep(input: Record<string, unknown>) {
|
|
168
168
|
"use step";
|
|
169
169
|
|
|
170
170
|
console.log('Executing action');
|
|
171
171
|
return { success: true };
|
|
172
|
-
}`,
|
|
172
|
+
}`,ip=`async function unknownStep(input: Record<string, unknown>) {
|
|
173
173
|
"use step";
|
|
174
174
|
|
|
175
175
|
return input;
|
|
176
|
-
}`;function
|
|
176
|
+
}`;function lp(e,t){let o=e?.triggerType||"Manual";if(o==="Schedule"){let n=e?.scheduleCron||"0 9 * * *";return`{
|
|
177
177
|
"crons": [
|
|
178
178
|
{
|
|
179
179
|
"path": "${t?`/api/workflow-builder/workflow/${t}/cron`:"/api/workflow-builder/workflow/<workflowId>/cron"}",
|
|
@@ -189,7 +189,7 @@ export async function POST(request: NextRequest) {
|
|
|
189
189
|
await executeWorkflow(body);
|
|
190
190
|
|
|
191
191
|
return Response.json({ success: true });
|
|
192
|
-
}`:""}function lp(e){if(!e)return $a;if(yl[e])return yl[e];let t=pe(e);return t&&t.codegenTemplate||$a}var sn=(e,t)=>e.data.type==="trigger"?ip(e.data.config,t):e.data.type==="action"?lp(e.data.config?.actionType):sp;import{useAtom as Ua}from"jotai";import{Check as bl,ChevronDown as ja,ChevronRight as qa,Clock as up,Copy as mp,ExternalLink as pp,Loader2 as fp,Play as gp,X as yp}from"lucide-react";import hl from"next/image";import{useCallback as Hr,useEffect as _r,useRef as vp,useState as Io}from"react";function ln(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function vl(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 ln(r,"min");let s=Math.floor(r/60);if(s<24)return ln(s,"hour");let a=Math.floor(s/24);if(a<7)return ln(a,"day");let l=Math.floor(a/7);if(l<4)return ln(l,"week");let i=Math.floor(a/30);if(i<12)return ln(i,"month");let d=Math.floor(a/365);return ln(d,"year")}import{Loader2Icon as dp}from"lucide-react";import{jsx as cp}from"react/jsx-runtime";function Nt({className:e,...t}){let{ref:o,...n}=t;return cp(dp,{role:"status","aria-label":"Loading",className:x("size-4 animate-spin",e),...n})}import{Fragment as Ur,jsx as _,jsxs as Fe}from"react/jsx-runtime";function hp(e){return Ms(e)}function bp(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function wp(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function Ka(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 xp(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function wl({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return _(Ur,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(xp(r))return _("a",{className:"text-blue-500 underline hover:text-blue-400",href:r,rel:"noopener noreferrer",target:"_blank",children:n},r)}return n})})}function Np({data:e,isError:t=!1}){let[o,n]=Io(!1);return _(O,{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?_(bl,{className:"h-3 w-3 text-green-600"}):_(mp,{className:"h-3 w-3"})})}function $r({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:s}){let[a,l]=Io(o);return Fe("div",{children:[Fe("div",{className:"mb-2 flex w-full items-center justify-between",children:[Fe("button",{className:"flex items-center gap-1.5",onClick:()=>l(!a),type:"button",children:[a?_(ja,{className:"h-3 w-3 text-muted-foreground"}):_(qa,{className:"h-3 w-3 text-muted-foreground"}),_("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),Fe("div",{className:"flex items-center gap-1",children:[s&&_(O,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:_("a",{href:s,rel:"noopener noreferrer",target:"_blank",children:_(pp,{className:"h-3 w-3"})})}),n!==void 0&&_(Np,{data:n,isError:r})]})]}),a&&t]})}function kp({output:e,input:t,actionType:o}){let r=(o?pe(o):void 0)?.outputConfig,s=o?hp(o):void 0,a=r?.type!=="component"?r:s,l=a?bp(e,a):void 0,i=!(r||s)&&wp(e),c=(()=>{if(r?.type==="component"){let g=r.component;return _("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:_(g,{input:t,output:e})})}if(a&&l)switch(a.type){case"image":{let g=a.field==="base64"&&!l.startsWith("data:")?`data:image/png;base64,${l}`:l;return _("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:_(hl,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:g,unoptimized:!0,width:384})})}case"video":return _("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:_("video",{className:"max-h-96 w-auto rounded",controls:!0,src:l,children:_("track",{kind:"captions"})})});case"url":return _("div",{className:"overflow-hidden rounded-lg border bg-muted/50",children:_("iframe",{className:"h-96 w-full rounded",sandbox:"allow-scripts allow-same-origin",src:l,title:"Output preview"})});default:return null}return i?_("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:_(hl,{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,p=a?.type==="url"&&l?l:void 0;return Fe(Ur,{children:[_($r,{copyData:e,title:"Output",children:_("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:_(wl,{data:e})})}),u&&_($r,{defaultExpanded:!0,externalLink:p,title:"Result",children:c})]})}function Cp({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:s,isLast:a}){return Fe("div",{className:"relative flex gap-3",children:[Fe("div",{className:"relative -ml-px flex flex-col items-center pt-2",children:[!s&&_("div",{className:"absolute bottom-full h-2 w-px bg-border"}),_("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&&_("div",{className:"absolute top-[calc(0.5rem+1.25rem)] bottom-0 w-px bg-border"})]}),Fe("div",{className:"min-w-0 flex-1",children:[_("button",{className:"group w-full rounded-lg py-2 text-left transition-colors hover:bg-muted/50",onClick:o,type:"button",children:Fe("div",{className:"flex items-center gap-3",children:[_("div",{className:"min-w-0 flex-1",children:Fe("div",{className:"flex items-center gap-2",children:[t?_(ja,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):_(qa,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),_("span",{className:"truncate font-medium text-sm transition-colors group-hover:text-foreground",children:e.nodeName||e.nodeType})]})}),e.duration&&_("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&&Fe("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&_($r,{copyData:e.input,title:"Input",children:_("pre",{className:"overflow-auto rounded-lg border bg-muted/50 p-3 font-mono text-xs leading-relaxed",children:_(wl,{data:e.input})})}),e.output!==null&&e.output!==void 0&&_(kp,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&_($r,{copyData:e.error,defaultExpanded:!0,isError:!0,title:"Error",children:_("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)&&_("div",{className:"rounded-lg border bg-muted/30 py-4 text-center text-muted-foreground text-xs",children:"No data recorded"})]})]})]},e.id)}function dn({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=Ua($e),[r,s]=Ua(Qt),[,a]=Ua(pr),[l,i]=Io([]),[d,c]=Io({}),[u,p]=Io(new Set),[g,T]=Io(new Set),[v,y]=Io(!0),w=vp(null),k=Hr(async(D=!0)=>{if(!n){y(!1);return}try{D&&y(!0);let j=await q.workflow.getExecutions(n);i(j)}catch(j){console.error("Failed to load executions:",j),i([])}finally{D&&y(!1)}},[n]);_r(()=>{t&&(t.current=()=>k(!1))},[k,t]),_r(()=>{k()},[k]);let f=Hr((D,j)=>D.map(z=>({id:z.id,nodeId:z.nodeId,nodeName:z.nodeName,nodeType:z.nodeType,status:z.status,startedAt:new Date(z.startedAt),completedAt:z.completedAt?new Date(z.completedAt):null,duration:z.duration,input:z.input,output:z.output,error:z.error})),[]),A=Hr(async D=>{try{let j=await q.workflow.getExecutionLogs(D),z=f(j.logs,j.execution.workflow);c(re=>({...re,[D]:z})),D===r&&a(Ka(z))}catch(j){console.error("Failed to load execution logs:",j),c(z=>({...z,[D]:[]}))}},[f,r,a]);_r(()=>{if(l.length===0)return;let D=l[0];D.status==="running"&&D.id!==w.current&&(w.current=D.id,s(D.id),p(j=>{let z=new Set(j);return z.add(D.id),z}),A(D.id),o&&o(D.id))},[l,s,A,o]);let I=Hr(async D=>{try{let j=await q.workflow.getExecutionLogs(D),z=f(j.logs,j.execution.workflow);c(re=>({...re,[D]:z})),D===r&&a(Ka(z))}catch(j){console.error(`Failed to refresh logs for ${D}:`,j)}},[f,r,a]);_r(()=>{if(!(e&&n))return;let j=setInterval(async()=>{try{let z=await q.workflow.getExecutions(n);i(z);for(let re of u)await I(re)}catch(z){console.error("Failed to poll executions:",z)}},2e3);return()=>clearInterval(j)},[e,n,u,I]);let C=async D=>{let j=new Set(u);j.has(D)?j.delete(D):(j.add(D),await A(D)),p(j)},h=D=>{if(r===D){s(null),a({});return}s(D);let j=d[D]||[];a(Ka(j))},m=D=>{let j=new Set(g);j.has(D)?j.delete(D):j.add(D),T(j)},S=D=>{switch(D){case"success":return _(bl,{className:"h-3 w-3 text-white"});case"error":return _(yp,{className:"h-3 w-3 text-white"});case"running":return _(fp,{className:"h-3 w-3 animate-spin text-white"});default:return _(up,{className:"h-3 w-3 text-white"})}},J=D=>{switch(D){case"success":return"bg-green-600";case"error":return"bg-red-600";case"running":return"bg-blue-600";default:return"bg-muted-foreground"}};return v?_("div",{className:"flex items-center justify-center py-12",children:_(Nt,{})}):l.length===0?Fe("div",{className:"flex flex-col items-center justify-center py-16",children:[_("div",{className:"mb-3 rounded-lg border border-dashed p-4",children:_(gp,{className:"h-6 w-6 text-muted-foreground"})}),_("div",{className:"font-medium text-foreground text-sm",children:"No runs yet"}),_("div",{className:"mt-1 text-muted-foreground text-xs",children:"Execute your workflow to see runs here"})]}):_("div",{className:"space-y-3",children:l.map((D,j)=>{let z=u.has(D.id),re=r===D.id,P=(d[D.id]||[]).sort((V,X)=>new Date(V.startedAt).getTime()-new Date(X.startedAt).getTime());return Fe("div",{className:x("overflow-hidden rounded-lg border bg-card transition-all",re&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[Fe("div",{className:"flex w-full items-center gap-3 p-4",children:[_("button",{className:"flex size-5 shrink-0 items-center justify-center rounded-full border-0 transition-colors hover:bg-muted",onClick:()=>C(D.id),type:"button",children:_("div",{className:x("flex size-5 items-center justify-center rounded-full border-0",J(D.status)),children:S(D.status)})}),Fe("button",{className:"min-w-0 flex-1 text-left transition-colors hover:opacity-80",onClick:()=>h(D.id),type:"button",children:[_("div",{className:"mb-1 flex items-center gap-2",children:Fe("span",{className:"font-semibold text-sm",children:["Run #",l.length-j]})}),Fe("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[_("span",{children:vl(D.startedAt)}),D.duration&&Fe(Ur,{children:[_("span",{children:"\u2022"}),_("span",{className:"tabular-nums",children:Number.parseInt(D.duration,10)<1e3?`${D.duration}ms`:`${(Number.parseInt(D.duration,10)/1e3).toFixed(2)}s`})]}),P.length>0&&Fe(Ur,{children:[_("span",{children:"\u2022"}),Fe("span",{children:[P.length," ",P.length===1?"step":"steps"]})]})]})]}),_("button",{className:"flex shrink-0 items-center justify-center rounded p-1 transition-colors hover:bg-muted",onClick:()=>C(D.id),type:"button",children:z?_(ja,{className:"h-4 w-4 text-muted-foreground"}):_(qa,{className:"h-4 w-4 text-muted-foreground"})})]}),z&&_("div",{className:"border-t bg-muted/20",children:P.length===0?_("div",{className:"py-8 text-center text-muted-foreground text-xs",children:"No steps recorded"}):_("div",{className:"p-4",children:P.map((V,X)=>_(Cp,{getStatusDotClass:J,getStatusIcon:S,isExpanded:g.has(V.id),isFirst:X===0,isLast:X===P.length-1,log:V,onToggle:()=>m(V.id)},V.id))})})]},D.id)})})}import{Fragment as co,jsx as L,jsxs as $}from"react/jsx-runtime";var Pp=/[^a-zA-Z0-9\s]/g,Ep=/\s+/,Al={"Database Query":"database"},Dp=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=Bn(!1),s=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",l=[];e.length>0&&l.push(`${e.length} ${s}`),t.length>0&&l.push(`${t.length} ${a}`);let i=l.join(" and ");return $(co,{children:[$("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"})}),$("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[$("div",{className:"space-y-2",children:[L(F,{children:"Selection"}),$("p",{className:"text-muted-foreground text-sm",children:[i," selected"]})]}),L("div",{className:"flex items-center gap-2 pt-4",children:$(O,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[L(jr,{className:"mr-2 size-4"}),"Delete"]})})]})]}),L(Go,{onOpenChange:r,open:n,children:$(Ho,{children:[$(_o,{children:[L(Uo,{children:"Delete Selected Items"}),$(Ko,{children:["Are you sure you want to delete ",i,"? This action cannot be undone."]})]}),$($o,{children:[L(qo,{children:"Cancel"}),L(jo,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},Rp=()=>{let[e]=io(be),[t]=io(_e),[o]=io(oe),n=Ya(ue),[r]=io(wt),[s]=io($e),[a,l]=io(pt),i=Ya(Xt),d=lo(Zt),c=lo(eo),u=lo(to),p=lo(Xs),g=lo(Qs),T=lo(Zs),v=lo(yr),y=lo(ur),[w,k]=io(Jt),[f,A]=Bn(!1),[I,C]=Bn(!1),[h,m]=Bn(!1),[S,J]=Bn(!1),[D,j]=io(Ft),z=Tl(null),re=Tl({}),P=o.find(ee=>ee.id===e),V=n.find(ee=>ee.id===t),X=o.filter(ee=>ee.selected),W=n.filter(ee=>ee.selected),U=X.length+W.length>1;Cl(()=>{if(!P||D!=="code")return;let ee=P.data.config?.actionType==="Condition",ve=P.data.type==="trigger"&&P.data.config?.triggerType==="Manual";(ee||ve)&&j("properties")},[P,D,j]);let N=Ya(mt);Cl(()=>{if(!(P&&i))return;let ee=P.data.config?.actionType,ve=P.data.config?.integrationId;if(!(ee&&ve))return;let E=pe(ee)?.integration||Al[ee];if(!E||N.some(ce=>ce.id===ve))return;let Y=N.filter(ce=>ce.type===E);if(Y.length===1){let ce={...P.data.config,integrationId:Y[0].id};d({id:P.id,data:{config:ce}})}else if(Y.length===0){let ce={...P.data.config,integrationId:void 0};d({id:P.id,data:{config:ce}})}},[P,N,i,d]);let M=Ip(()=>{let ve=`${a.replace(Pp,"").split(Ep).map((E,H)=>H===0?E.toLowerCase():E.charAt(0).toUpperCase()+E.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:Q}=tr(o,n,{functionName:ve});return Q},[o,n,a]),b=()=>{P&&navigator.clipboard.writeText(sn(P))},R=()=>{navigator.clipboard.writeText(M),Kr.success("Code copied to clipboard")},G=()=>{e&&(c(e),A(!1))},te=()=>{if(P){let ee=P.data.enabled??!0;d({id:P.id,data:{enabled:!ee}})}},de=()=>{t&&(u(t),C(!1))},B=async()=>{if(s)try{await q.workflow.deleteExecutions(s),v(),m(!1)}catch(ee){console.error("Failed to delete runs:",ee);let ve=ee instanceof Error?ee.message:"Failed to delete runs";Kr.error(ve)}},xe=ee=>{P&&d({id:P.id,data:{label:ee}})},qe=ee=>{P&&d({id:P.id,data:{description:ee}})},Ye=Sp(async(ee,ve,Q,E)=>{let Y=pe(ve)?.integration||Al[ve];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(Re=>Re.type===Y);if(Ee.length===1&&!E.aborted){let Re={...Q,actionType:ve,integrationId:Ee[0].id};d({id:ee,data:{config:Re}})}}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})}},[d,y]),He=(ee,ve)=>{if(P){let Q={...P.data.config,[ee]:ve};if(ee==="actionType"&&P.data.config?.integrationId&&(Q={...Q,integrationId:void 0}),d({id:P.id,data:{config:Q}}),ee==="actionType"){let E=re.current[P.id];E&&E.abort();let H=new AbortController;re.current[P.id]=H,y(Y=>new Set(Y).add(P.id)),Ye(P.id,ve,Q,H.signal)}}},qt=async ee=>{if(l(ee),s)try{await q.workflow.update(s,{name:ee,nodes:o,edges:n})}catch(ve){console.error("Failed to update workflow name:",ve),Kr.error("Failed to update workspace name")}},St=async()=>{J(!0);try{z.current&&await z.current()}catch(ee){console.error("Failed to refresh runs:",ee),Kr.error("Failed to refresh runs")}finally{J(!1)}};return U?L(Dp,{onDelete:p,selectedEdges:W,selectedNodes:X}):V?$(co,{children:[$("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"})}),$("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),L(se,{disabled:!0,id:"edge-id",value:V.id})]}),$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),L(se,{disabled:!0,id:"edge-source",value:V.source})]}),$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),L(se,{disabled:!0,id:"edge-target",value:V.target})]}),i&&L("div",{className:"flex items-center gap-2 pt-4",children:$(O,{className:"text-muted-foreground",onClick:()=>C(!0),size:"sm",variant:"ghost",children:[L(jr,{className:"mr-2 size-4"}),"Delete"]})})]})]}),L(Go,{onOpenChange:C,open:I,children:$(Ho,{children:[$(_o,{children:[L(Uo,{children:"Delete Edge"}),L(Ko,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),$($o,{children:[L(qo,{children:"Cancel"}),L(jo,{onClick:de,children:"Delete"})]})]})})]}):P?$(co,{children:[$(ha,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:j,value:D,children:[$(ba,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[L(vo,{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"?L(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,i&&L(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),$(ho,{className:"flex flex-col overflow-hidden",value:"properties",children:[P.data.type==="action"&&!P.data.config?.actionType&&i&&L("div",{className:"flex min-h-0 flex-1 flex-col px-4 pt-4",children:L(Vr,{disabled:r,isNewlyCreated:P?.id===w,onSelectAction:ee=>{He("actionType",ee),P?.id===w&&k(null)}})}),!(P.data.type==="action"&&!P.data.config?.actionType&&i)&&$("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),L(se,{readOnly:!0,id:"node-id",value:P?.id||""})]}),P.data.type==="trigger"&&L(Gr,{config:P.data.config||{},disabled:r||!i,onUpdateConfig:He,workflowId:s??void 0}),P.data.type==="action"&&!P.data.config?.actionType&&!i&&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."})}),P.data.type==="action"&&P.data.config?.actionType?L(Mr,{config:P.data.config||{},disabled:r||!i,isOwner:i,onUpdateConfig:He}):null,P.data.type!=="action"||P.data.config?.actionType?$(co,{children:[$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"label",children:"Label"}),L(se,{disabled:r||!i,id:"label",onChange:ee=>xe(ee.target.value),value:P.data.label})]}),$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"description",children:"Description"}),L(se,{disabled:r||!i,id:"description",onChange:ee=>qe(ee.target.value),placeholder:"Optional description",value:P.data.description||""})]})]}):null,!i&&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."})}),i&&$("div",{className:"flex items-center gap-2 pt-4",children:[P.data.type==="action"&&L(O,{className:"text-muted-foreground",onClick:te,size:"sm",variant:"ghost",children:P.data.enabled===!1?$(co,{children:[L(Ap,{className:"mr-2 size-4"}),"Disabled"]}):$(co,{children:[L(Tp,{className:"mr-2 size-4"}),"Enabled"]})}),$(O,{className:"text-muted-foreground",onClick:()=>A(!0),size:"sm",variant:"ghost",children:[L(jr,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),L(ho,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let ee=P.data.config?.triggerType,ve="",Q="typescript";return P.data.type==="trigger"?ee==="Schedule"?(ve="vercel.json",Q="json"):ee==="Webhook"&&(ve=`app/api${P.data.config?.webhookPath||"/webhook"}/route.ts`,Q="typescript"):ve=`steps/${P.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,$(co,{children:[ve&&$("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[$("div",{className:"flex items-center gap-2",children:[L(Nl,{className:"size-3.5 text-muted-foreground"}),L("code",{className:"text-muted-foreground text-xs",children:ve})]}),$(O,{className:"text-muted-foreground",onClick:b,size:"sm",variant:"ghost",children:[L(xl,{className:"mr-2 size-4"}),"Copy"]})]}),L("div",{className:"flex-1 overflow-hidden",children:L(ft,{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:sn(P)})})]})})()}),i&&$(ho,{className:"flex flex-col overflow-hidden",value:"runs",children:[$("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[$(O,{className:"text-muted-foreground",disabled:S,onClick:St,size:"sm",variant:"ghost",children:[L(kl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),$(O,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[L(Ja,{className:"mr-2 size-4"}),"Clear All"]})]}),L("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:L(dn,{isActive:D==="runs",onRefreshRef:z})})]})]}),L(Go,{onOpenChange:m,open:h,children:$(Ho,{children:[$(_o,{children:[L(Uo,{children:"Delete All Runs"}),L(Ko,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),$($o,{children:[L(qo,{children:"Cancel"}),L(jo,{onClick:B,children:"Delete"})]})]})}),L(Go,{onOpenChange:A,open:f,children:$(Ho,{children:[$(_o,{children:[L(Uo,{children:"Delete Step"}),L(Ko,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),$($o,{children:[L(qo,{children:"Cancel"}),L(jo,{onClick:G,children:"Delete"})]})]})})]}):$(co,{children:[$(ha,{className:"size-full",defaultValue:"properties",onValueChange:j,value:D,children:[$(ba,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[L(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),L(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),i&&L(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),L(ho,{className:"flex flex-col overflow-hidden",value:"properties",children:$("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:[$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),L(se,{disabled:!i,id:"workflow-name",onChange:ee=>qt(ee.target.value),value:a})]}),$("div",{className:"space-y-2",children:[L(F,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),L(se,{disabled:!0,id:"workflow-id",value:s||"Not saved"})]}),!i&&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."})}),i&&$("div",{className:"flex items-center gap-2 pt-4",children:[$(O,{className:"text-muted-foreground",onClick:()=>g(!0),size:"sm",variant:"ghost",children:[L(Ja,{className:"mr-2 size-4"}),"Clear"]}),$(O,{className:"text-muted-foreground",onClick:()=>T(!0),size:"sm",variant:"ghost",children:[L(jr,{className:"mr-2 size-4"}),"Delete"]})]})]})}),i&&$(ho,{className:"flex flex-col overflow-hidden",value:"runs",children:[$("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[$(O,{className:"text-muted-foreground",disabled:S,onClick:St,size:"sm",variant:"ghost",children:[L(kl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),$(O,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[L(Ja,{className:"mr-2 size-4"}),"Clear All"]})]}),L("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:L(dn,{isActive:D==="runs",onRefreshRef:z})})]}),$(ho,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:[$("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 pb-2",children:[$("div",{className:"flex items-center gap-2",children:[L(Nl,{className:"size-3.5 text-muted-foreground"}),$("code",{className:"text-muted-foreground text-xs",children:["workflows/",a.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"workflow",".ts"]})]}),$(O,{className:"text-muted-foreground",onClick:R,size:"sm",variant:"ghost",children:[L(xl,{className:"mr-2 size-4"}),"Copy"]})]}),L("div",{className:"flex-1 overflow-hidden",children:L(ft,{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:M})})]})]}),L(Go,{onOpenChange:m,open:h,children:$(Ho,{children:[$(_o,{children:[L(Uo,{children:"Delete All Runs"}),L(Ko,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),$($o,{children:[L(qo,{children:"Cancel"}),L(jo,{onClick:B,children:"Delete"})]})]})})]})},Xa=()=>L("div",{className:"hidden size-full flex-col bg-background md:flex",children:L(Rp,{})});import{jsx as Tt,jsxs as qr}from"react/jsx-runtime";var es=({workflowId:e})=>{let t=zp(),o=zt(),[n,r]=Bt(wt),[s,a]=Bt(gr),[l]=Bt(oe),[i]=Bt(ue),[d]=Bt($e),[c]=Bt(Qt),u=kt(oe),p=kt(ue),g=kt($e),T=kt(pt),v=kt(Zt),y=kt(tt),[w,k]=Bt(ei),f=kt(mr),A=kt(ir),I=kt(lr),[C,h]=Bt(dr),[m,S]=Bt(js),J=kt(ar),[D,j]=Bt(Xt),z=kt(mt),re=kt(rr),P=Op(Pt),[V,X]=Qa(30),[W,U]=Qa(C),[N,M]=Qa(!1),b=Po(!1),R=Po(!1);Ct(()=>{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&&X(Y)}let H=document.cookie.split("; ").find(Y=>Y.startsWith("sidebar-collapsed="));H&&S(H.split("=")[1]==="true")},[S]);let G=Po(!1);Ct(()=>{if(!G.current){G.current=!0;return}document.cookie=`sidebar-width=${V}; path=/; max-age=31536000`},[V]),Ct(()=>{R.current&&(document.cookie=`sidebar-collapsed=${m}; path=/; max-age=31536000`)},[m]),Ct(()=>{let E=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),C||!E){U(!0),h(!0);return}I(!0);let H=setTimeout(()=>{U(!0),h(!0)},100),Y=setTimeout(()=>I(!1),400);return()=>{clearTimeout(H),clearTimeout(Y),I(!1)}},[C,h,I]),Ct(()=>{let E=H=>{(H.metaKey||H.ctrlKey)&&H.key==="b"&&(H.preventDefault(),I(!0),S(Y=>!Y),setTimeout(()=>I(!1),350))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[I,S]),Ct(()=>(A(!o&&W&&!m?`${V}%`:null),()=>{A(null)}),[o,A,V,W,m]);let te=uo(E=>{E.preventDefault(),b.current=!0,M(!0);let H=ce=>{if(!b.current)return;let Ee=(window.innerWidth-ce.clientX)/window.innerWidth*100;X(Math.min(50,Math.max(20,Ee)))},Y=()=>{b.current=!1,M(!1),document.removeEventListener("mousemove",H),document.removeEventListener("mouseup",Y),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",H),document.addEventListener("mouseup",Y),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),de=Po(null),B=Po(null),xe=Po(l);Ct(()=>{xe.current=l},[l]);let qe=uo(async E=>{r(!0),g(e),T("AI Generated Workflow");try{let H=await q.ai.generate(E),Y=(H.nodes||[]).map(ce=>({...ce,selected:!1}));u(Y),p(H.edges||[]),T(H.name||"AI Generated Workflow"),await q.workflow.update(e,{name:H.name,description:H.description,nodes:H.nodes,edges:H.edges})}catch(H){console.error("Failed to generate workflow:",H),Za.error("Failed to generate workflow")}finally{r(!1)}},[e,r,g,T,u,p]),Ye=uo(async()=>{try{let E=await q.workflow.getById(e);if(!E){k(!0);return}let H=E.nodes.map(Y=>({...Y,selected:!1,data:{...Y.data,status:"idle"}}));u(H),p(E.edges),g(E.id),T(E.name),J(E.visibility??"private"),j(E.isOwner!==!1),y(!1),k(!1)}catch(E){console.error("Failed to load workflow:",E),Za.error("Failed to load workflow")}},[e,u,p,g,T,J,j,y,k]),He=Po(null);Ct(()=>{(async()=>{let H=t?.get("generating")==="true",Y=sessionStorage.getItem("ai-prompt"),ce=sessionStorage.getItem("generating-workflow-id");d===e&&l.length>0||(H&&Y&&ce===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await qe(Y)):await Ye())})()},[e,t,d,l.length,qe,Ye]),Ct(()=>{if(l.length===0||!d||!D)return;let E=He.current;if(E&&E.workflowId===d&&E.version===P)return;(async()=>{try{let Y=await q.integration.getAll();z(Y),re(!0);let ce=new Set(Y.map(Re=>Re.id)),Ee=l.map(Re=>ai(Re,Y,ce)).filter(Re=>Re!==null);for(let Re of Ee){let Cn=l.find(ma=>ma.id===Re.nodeId);Cn&&v({id:Re.nodeId,data:{config:{...Cn.data.config,integrationId:Re.newIntegrationId}}})}He.current={workflowId:d,version:P},Ee.length>0&&y(!0)}catch(Y){console.error("Failed to auto-fix integrations:",Y)}})()},[l,d,P,D,v,z,re,y]);let qt=uo(async()=>{if(!(!d||n)){a(!0);try{await q.workflow.update(d,{nodes:l,edges:i}),y(!1)}catch(E){console.error("Failed to save workflow:",E),Za.error("Failed to save workflow")}finally{a(!1)}}},[d,l,i,n,a,y]),St=uo(E=>E.tagName==="INPUT"||E.tagName==="TEXTAREA",[]),ee=uo(E=>E.closest(".monaco-editor")!==null,[]),ve=uo(E=>(E.metaKey||E.ctrlKey)&&E.key==="s"?(E.preventDefault(),E.stopPropagation(),qt(),!0):!1,[qt]),Q=uo((E,H)=>(E.metaKey||E.ctrlKey)&&E.key==="Enter"?(St(H)||ee(H)||(E.preventDefault(),E.stopPropagation(),f(!0)),!0):!1,[f,St,ee]);return Ct(()=>{let E=H=>{let Y=H.target;ve(H)||Q(H,Y)};return document.addEventListener("keydown",E,!0),()=>document.removeEventListener("keydown",E,!0)},[ve,Q]),Ct(()=>()=>{de.current&&clearInterval(de.current),B.current&&clearInterval(B.current)},[]),Ct(()=>{if(B.current&&(clearInterval(B.current),B.current=null),!c){for(let H of xe.current)v({id:H.id,data:{status:"idle"}});return}let E=async()=>{try{let H=await q.workflow.getExecutionStatus(c);for(let Y of H.nodeStatuses)v({id:Y.nodeId,data:{status:Y.status}});H.status!=="running"&&B.current&&(clearInterval(B.current),B.current=null)}catch(H){console.error("Failed to poll selected execution status:",H),B.current&&(clearInterval(B.current),B.current=null)}};return E(),B.current=setInterval(E,500),()=>{B.current&&(clearInterval(B.current),B.current=null)}},[c,v]),qr("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[w&&Tt("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:qr("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[Tt("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),Tt("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),Tt(O,{asChild:!0,children:Tt(Fp,{href:"/",children:"New Workflow"})})]})}),!o&&m&&Tt("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:Tt(Lp,{className:"size-4"})}),!o&&qr("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:W&&!m?"translateX(0)":"translateX(100%)"},children:[qr("div",{"aria-orientation":"vertical","aria-valuenow":V,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:te,role:"separator",tabIndex:0,children:[Tt("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(N||m)&&Tt("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:Tt(Mp,{className:"size-4"})})]}),Tt(Xa,{})]}),o&&Tt(Xa,{})]})};import{useAtomValue as ts,useSetAtom as Vn}from"jotai";import{nanoid as Vp}from"nanoid";import{useRouter as Gp}from"next/navigation";import{useCallback as Il,useEffect as Yr,useRef as Hp}from"react";import{toast as _p}from"sonner";import{anonymousClient as Wp}from"better-auth/client/plugins";import{createAuthClient as Bp}from"better-auth/react";var Eo=Bp({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[Wp()]}),{signIn:Jk,signOut:Sl,signUp:Xk,useSession:cn}=Eo;function $p(){return{id:Vp(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var Pl=()=>{let e=Gp(),{data:t}=cn(),o=ts(oe),n=ts(ue),r=Vn(oe),s=Vn(ue),a=Vn(pt),l=Vn(dr),i=Vn(cr),d=Hp(!1),c=ts(pt);Yr(()=>{l(!1)},[l]),Yr(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=Il(async()=>{t||(await Eo.signIn.anonymous(),await new Promise(g=>setTimeout(g,100)))},[t]),p=Il(()=>{let g=$p();r([g])},[r]);return Yr(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:p},draggable:!1,selectable:!1}]),s([]),a("New Workflow"),d.current=!1},[r,s,a,p]),Yr(()=>{(async()=>{let T=o.filter(v=>v.type!=="add");if(!(T.length===0||d.current)){d.current=!0;try{await u();let v=await q.workflow.create({name:"Untitled Workflow",description:"",nodes:T,edges:n});sessionStorage.setItem("animate-sidebar","true"),i(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${v.id}`)}catch(v){console.error("Failed to create workflow:",v),_p.error("Failed to create workflow")}}})()},[o,n,e,u,i]),null};import{useRouter as Up}from"next/navigation";import{useEffect as Kp}from"react";var El=()=>{let e=Up();return Kp(()=>{(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 un}from"react/jsx-runtime";var Yp=()=>{let t=qp().slug;return!t||t.length===0?un(Pl,{}):t[0]==="auth"&&t.length===2?un("main",{className:"flex items-center justify-center min-h-screen",children:un(jp,{path:t[1]})}):t[0]==="workflows"&&t.length===1?un(El,{}):t[0]==="workflows"&&t.length===2?un("div",{className:"pointer-events-none relative z-10",children:un(es,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as dv}from"@xyflow/react";import{Provider as cv}from"jotai";import*as vc from"react";import{AnimatePresence as Qp,LayoutGroup as Ol,motion as pn,useReducedMotion as Ll}from"motion/react";import{useCallback as Hn,useLayoutEffect as _n,useRef as mo,useState as Ml}from"react";import{Drawer as Gn}from"vaul";import{Dialog as mn}from"radix-ui";import{XIcon as Jp}from"lucide-react";import{jsx as Do,jsxs as os}from"react/jsx-runtime";function Jr({...e}){return Do(mn.Root,{"data-slot":"dialog",...e})}function ns({...e}){return Do(mn.Portal,{"data-slot":"dialog-portal",...e})}function Xp({className:e,...t}){return Do(mn.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 Dl({className:e,children:t,showCloseButton:o=!0,...n}){return os(ns,{"data-slot":"dialog-portal",children:[Do(Xp,{}),os(mn.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&&os(mn.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:[Do(Jp,{}),Do("span",{className:"sr-only",children:"Close"})]})]})]})}function Rl({className:e,...t}){return Do(mn.Title,{"data-slot":"dialog-title",className:x("text-lg leading-none font-semibold",e),...t})}import{jsx as Le,jsxs as as}from"react/jsx-runtime";var rs={type:"spring",stiffness:400,damping:35,mass:.8},Zp={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 Fl(e,t){return e?"0%":t?"-35%":"100%"}function zl(e){let t=mo(e),o=mo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),_n(()=>{t.current=e},[e]),o.current}function tf(){let{stack:e,closeAll:t,pop:o}=ne(),n=Ll(),[r,s]=Ml(0),a=mo(null),l=mo(!1),i=mo(e),d=zl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,p=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:i.current.length,renderStackLength:u.length}),_n(()=>{let f=c&&!l.current;if(l.current=c,f&&s(0),a.current){let A=a.current.offsetHeight;A>0&&s(A)}},[e,c]);let g=e[e.length-1],T=n?{duration:.01}:rs,v=d===1,y=Hn(()=>{g?.options.closeOnBackdropClick!==!1&&t()},[g?.options.closeOnBackdropClick,t]),w=Hn(f=>{f.key==="Escape"&&g?.options.closeOnEscape!==!1&&o()},[g?.options.closeOnEscape,o]);_n(()=>{if(c)return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[c,w]);let k=Hn(()=>{console.log("[DesktopOverlay] handleExitComplete called"),i.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&i.current.length===0?null:Le(Qp,{onExitComplete:k,children:c&&Le(Jr,{modal:!1,open:!0,children:as(ns,{forceMount:!0,children:[Le(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}}),Le(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:ef,children:Le(Ol,{children:Le(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:rs,children:Le("div",{className:"relative",ref:a,children:u.map((f,A)=>{let I=A===p,C=A<p,m=I&&v&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Le(pn.div,{animate:{x:Fl(I,C),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:T,children:Le(f.component,{overlayId:f.id,...f.props})},f.id)})})})})})]})})})}function of(){let{stack:e,closeAll:t,pop:o}=ne(),n=Ll(),[r,s]=Ml(0),a=mo(null),l=mo(!1),i=mo(e),d=zl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,p=u.length-1;_n(()=>{let f=c&&!l.current;if(l.current=c,f&&s(0),a.current){let A=a.current.offsetHeight;A>0&&s(A)}},[e,c]);let g=e[e.length-1],T=u[p],v=n?{duration:.01}:rs,y=d===1,w=Hn(f=>{f.key==="Escape"&&g?.options.closeOnEscape!==!1&&o()},[g?.options.closeOnEscape,o]);_n(()=>{if(c)return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[c,w]);let k=Hn(()=>{c||(i.current=[])},[c]);return Le(Gn.Root,{onAnimationEnd:k,onOpenChange:f=>{f||t()},open:c,children:as(Gn.Portal,{children:[Le(Gn.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),as(Gn.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:[Le(Gn.Title,{className:"sr-only",children:T?.options.title||"Dialog"}),Le("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),Le(Ol,{children:Le(pn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:Zp,children:Le("div",{className:"relative",ref:a,children:u.map((f,A)=>{let I=A===p,C=A<p,m=I&&y&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Le(pn.div,{animate:{x:Fl(I,C),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:v,children:Le(f.component,{overlayId:f.id,...f.props})},f.id)})})})}),Le("div",{className:"h-safe-area-inset-bottom"})]})]})})}function Wl(){return zt()?Le(of,{}):Le(tf,{})}import{useAtom as nf}from"jotai";import{useEffect as rf,useRef as Bl}from"react";import{atom as _t}from"jotai";var je=_t([]),LC=_t(e=>e(je).length>0),MC=_t(e=>e(je).length);function ss(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var FC=_t(null,(e,t,o)=>{let n=ss(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[r]),n}),zC=_t(null,(e,t,o)=>{let n=ss(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[...e(je),r]),n}),WC=_t(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))}),BC=_t(null,(e,t,o)=>{let n=e(je),r=ss(),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}),VC=_t(null,(e,t)=>{let o=e(je);for(let n of o)n.options.onClose?.();t(je,[])}),GC=_t(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 Vl(){let{stack:e}=ne(),[t,o]=nf(je),n=Bl(!1),r=Bl(!1);return rf(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as af,jsx as Gl,jsxs as sf}from"react/jsx-runtime";var Hl=()=>sf(af,{children:[Gl(Wl,{}),Gl(Vl,{})]});import{CircleCheckIcon as lf,InfoIcon as df,Loader2Icon as cf,OctagonXIcon as uf,TriangleAlertIcon as mf}from"lucide-react";import{useTheme as pf}from"next-themes";import{Toaster as ff}from"sonner";import{jsx as fn}from"react/jsx-runtime";var _l=({...e})=>{let{theme:t="system"}=pf();return fn(ff,{theme:t,className:"toaster group",icons:{success:fn(lf,{className:"size-4"}),info:fn(df,{className:"size-4"}),warning:fn(mf,{className:"size-4"}),error:fn(uf,{className:"size-4"}),loading:fn(cf,{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 ov}from"next/navigation";import{ConnectionMode as qy,MiniMap as Yy,useReactFlow as Jy}from"@xyflow/react";import{useAtom as er,useAtomValue as Ds,useSetAtom as go}from"jotai";import{useCallback as bt,useEffect as ua,useMemo as Xy,useRef as Lo,useState as dc}from"react";import{Background as gf,ReactFlow as yf}from"@xyflow/react";import"@xyflow/react/dist/style.css";import{jsx as vf,jsxs as hf}from"react/jsx-runtime";var $l=({children:e,...t})=>hf(yf,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[vf(gf,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]});import{jsx as Ul,jsxs as bf}from"react/jsx-runtime";var Kl=({fromX:e,fromY:t,toX:o,toY:n})=>bf("g",{children:[Ul("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}),Ul("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as kf}from"@xyflow/react";import{useAtom as Cf}from"jotai";import{MapPin as Tf,MapPinXInside as Af,Maximize2 as Sf,ZoomIn as If,ZoomOut as Pf}from"lucide-react";import{cva as wf}from"class-variance-authority";import{Slot as u0}from"radix-ui";import{jsx as Nf}from"react/jsx-runtime";var xf=wf("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 Vt({className:e,orientation:t,...o}){return Nf("div",{role:"group","data-slot":"button-group","data-orientation":t,className:x(xf({orientation:t}),e),...o})}import{jsx as $t,jsxs as Ef}from"react/jsx-runtime";var jl=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=kf(),[n,r]=Cf(sr);return Ef(Vt,{orientation:"vertical",children:[$t(O,{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:$t(If,{className:"size-4"})}),$t(O,{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:$t(Pf,{className:"size-4"})}),$t(O,{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:$t(Sf,{className:"size-4"})}),$t(O,{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?$t(Tf,{className:"size-4"}):$t(Af,{className:"size-4"})})]})};import{useReactFlow as Ff}from"@xyflow/react";import{useAtom as gn,useAtomValue as zf}from"jotai";import{ArrowUp as Wf}from"lucide-react";import{useCallback as Bf,useEffect as Vf,useRef as Yl,useState as is}from"react";import{toast as ls}from"sonner";import{motion as Df}from"motion/react";import{memo as Rf,useMemo as Of}from"react";import{jsx as Mf}from"react/jsx-runtime";var Lf=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let s=Df.create(t),a=Of(()=>(e?.length??0)*r,[e,r]);return Mf(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})},ql=Rf(Lf);import{Fragment as Gf,jsx as Ut,jsxs as ds}from"react/jsx-runtime";function Jl({workflowId:e,onWorkflowCreated:t}){let[o,n]=gn(wt),[r,s]=is(""),[a,l]=is(!1),[i,d]=is(!1),c=Yl(null),u=Yl(null),p=zf(oe),[g,T]=gn(ue),[v,y]=gn(oe),[w,k]=gn($e),[f,A]=gn(pt),[I,C]=gn(be),{fitView:h}=Ff(),m=p.filter(z=>z.type!=="add"),S=m.length>0;Vf(()=>{let z=re=>{(re.metaKey||re.ctrlKey)&&re.key==="k"&&(re.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",z),()=>{window.removeEventListener("keydown",z)}},[]);let J=()=>{l(!0),d(!0)},D=z=>{u.current?.contains(z.relatedTarget)||(d(!1),r.trim()||l(!1))},j=Bf(async z=>{if(z.preventDefault(),!(!r.trim()||o)){n(!0);try{let re=S?{nodes:m,edges:g,name:f}:void 0;console.log("[AI Prompt] Generating workflow"),console.log("[AI Prompt] Has nodes:",S),console.log("[AI Prompt] Sending existing workflow:",!!re),re&&console.log("[AI Prompt] Existing workflow:",re.nodes.length,"nodes,",re.edges.length,"edges");let P=await q.ai.generateStream(r,W=>{let U=(W.edges||[]).map(b=>({...b,type:"animated"})),N=(W.nodes||[]).filter(b=>b.data?.type==="trigger"),M=U;if(N.length>1){let b=N[0],R=(W.nodes||[]).filter(te=>te.data?.type!=="trigger");W.nodes=[b,...R];let G=N.slice(1).map(te=>te.id);M=U.filter(te=>!G.includes(te.source)&&!G.includes(te.target))}y(W.nodes||[]),T(M),W.name&&A(W.name),setTimeout(()=>{h({padding:.2,duration:200})},0)},re);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(W=>({...W,type:"animated"}));console.log("[AI Prompt] Validating nodes:",P.nodes);let X=(P.nodes||[]).filter(W=>{let U=W.data?.type,N=W.data?.config||{};return console.log(`[AI Prompt] Checking node ${W.id}:`,{type:U,config:N,hasActionType:!!N.actionType,hasTriggerType:!!N.triggerType}),U==="trigger"?!N.triggerType:U==="action"?!N.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(P,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){k(e),console.log("[AI Prompt] Updating existing workflow:",e),console.log("[AI Prompt] Has existingWorkflow context:",!!re),re?(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"),ls.success("Generated workflow"));let W=P.nodes?.find(U=>U.selected);W&&C(W.id),await q.workflow.update(e,{name:P.name,description:P.description,nodes:P.nodes,edges:V})}else{let W=await q.workflow.create({name:P.name||"AI Generated Workflow",description:P.description||"",nodes:P.nodes||[],edges:V});k(W.id),ls.success("Created workflow"),t&&t(W.id)}s(""),l(!1),d(!1),c.current?.blur()}catch(re){console.error("Failed to generate workflow:",re),ls.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,S,p,g,n,k,y,T,A,C,t,h]);return Ut(Gf,{children:Ut("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:ds("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:z=>{(z.target===z.currentTarget||z.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:z=>{z.target===z.currentTarget&&z.preventDefault()},onSubmit:j,role:"search",children:[o&&r?Ut(ql,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Ut("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:D,onChange:z=>{s(z.target.value),z.target.style.height="auto",z.target.style.height=`${z.target.scrollHeight}px`},onFocus:J,onKeyDown:z=>{z.key==="Enter"&&!z.shiftKey?(z.preventDefault(),j(z)):z.key==="Escape"&&(z.preventDefault(),s(""),l(!1),d(!1),c.current?.blur())},placeholder:i?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Ut("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),ds("div",{className:"relative size-8 shrink-0 self-end",children:[Ut(O,{"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:ds("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:[Ut("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Ut(O,{"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:Ut(Wf,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as zg}from"@xyflow/react";import{useAtom as Ze,useAtomValue as zd,useSetAtom as Gt}from"jotai";import{Check as sa,ChevronDown as Wg,Copy as Bg,Download as Vg,Globe as Wd,Loader2 as la,Lock as Bd,Play as Gg,Plus as Vd,Redo2 as Gd,Save as Hg,Settings2 as _g,Trash2 as $g,Undo2 as Hd}from"lucide-react";import{nanoid as Ug}from"nanoid";import{useRouter as Kg}from"next/navigation";import{useEffect as Ts,useRef as jg,useState as Cs}from"react";import{toast as it}from"sonner";import{Panel as Hf}from"@xyflow/react";import{jsx as _f}from"react/jsx-runtime";var Xr=({className:e,...t})=>_f(Hf,{className:x("m-4 rounded-md border bg-card p-1",e),...t});var cs="https://vercel.new/workflow-builder",_0=`[](${cs})`;import{jsx as $n,jsxs as Xl}from"react/jsx-runtime";function Ql(){return $n(O,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:Xl("a",{href:cs,rel:"noopener noreferrer",target:"_blank",children:[Xl("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[$n("title",{children:"Vercel logomark"}),$n("path",{d:"m38 0 38 66H0z"})]}),$n("span",{className:"text-sm sm:hidden",children:"Deploy"}),$n("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as Zl}from"react/jsx-runtime";function ed({className:e}){return Zl("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:Zl("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 td(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 $f,useContext as Uf}from"react";import{jsx as eT}from"react/jsx-runtime";var Kf=$f(null);function od(){return Uf(Kf)}import{jsx as nd,jsxs as rd}from"react/jsx-runtime";var jf="https://github.com/vercel-labs/workflow-builder-template";function ad(){let e=od();return nd(O,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:rd("a",{className:"flex items-center",href:jf,rel:"noopener noreferrer",target:"_blank",children:[nd(ed,{className:"size-4.5"}),e!==null&&rd("span",{className:"hidden text-sm sm:inline",children:[td(e)," stars"]})]})})}import{useAtom as Kt,useAtomValue as sd,useSetAtom as Un}from"jotai";import{Code as id,Copy as ld,Eraser as us,Eye as qf,EyeOff as Yf,FileCode as dd,Play as cd,RefreshCw as ud,Settings2 as md,Trash2 as ms}from"lucide-react";import{useCallback as yn,useEffect as Jf,useRef as Xf,useState as Qf}from"react";import{toast as vn}from"sonner";import{Fragment as ps,jsx as Z,jsxs as le}from"react/jsx-runtime";var Zf={"Database Query":"database"},eg=/[^a-zA-Z0-9\s]/g,tg=/\s+/;function og(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 Qr({overlayId:e}){let{push:t,closeAll:o}=ne(),[n]=Kt(be),[r]=Kt(_e),[s]=Kt(oe),[a]=Kt(ue),[l]=Kt(wt),[i]=Kt($e),[d,c]=Kt(pt),u=sd(Xt),p=Un(Zt),g=Un(eo),T=Un(to),v=Un(yr),y=Un(fr),[w,k]=Kt(Jt),[f,A]=Kt(Ft),[I,C]=Qf(!1),h=Xf(null),m=s.find(B=>B.id===n),S=a.find(B=>B.id===r),J=sd(mt);Jf(()=>{if(!(m&&u))return;let B=m.data.config?.actionType,xe=m.data.config?.integrationId;if(!(B&&xe))return;let Ye=pe(B)?.integration||Zf[B];if(!Ye)return;let He=J.filter(St=>St.type===Ye);!He.some(St=>St.id===xe)&&He.length>0&&p({id:m.id,data:{config:{...m.data.config,integrationId:He[0].id}}})},[m,J,u,p]);let D=yn((B,xe)=>{m&&p({id:m.id,data:{config:{...m.data.config,[B]:xe}}})},[m,p]),j=yn(B=>{m&&p({id:m.id,data:{label:B}})},[m,p]),z=yn(B=>{m&&p({id:m.id,data:{description:B}})},[m,p]),re=yn(()=>{m&&p({id:m.id,data:{enabled:m.data.enabled===!1}})},[m,p]),P=yn(()=>{t(Oe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{m&&(g(m.id),o())}})},[m,g,o,t]),V=yn(()=>{m&&(navigator.clipboard.writeText(sn(m,i)),vn.success("Code copied to clipboard"))},[m]),X=async()=>{h.current&&(C(!0),await h.current(),C(!1))},W=()=>{t(Oe,{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),v(),h.current&&await h.current(),vn.success("All runs deleted")}catch(B){console.error("Failed to delete runs:",B),vn.error("Failed to delete runs")}}})},U=m&&(m.data.type!=="trigger"||m.data.config?.triggerType!=="Manual")&&m.data.config?.actionType!=="Condition",N=()=>{if(!m)switch(f==="properties"||f==="code"||f==="runs"&&u?f:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(f){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},M=async B=>{if(c(B),i)try{await q.workflow.update(i,{name:B})}catch(xe){console.error("Failed to update workflow name:",xe)}},b=()=>{t(Oe,{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(Oe,{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(i)try{await q.workflow.delete(i),o(),vn.success("Workflow deleted successfully"),window.location.href="/"}catch(B){console.error("Failed to delete workflow:",B),vn.error("Failed to delete workflow. Please try again.")}}})},G=(()=>{let xe=`${d.replace(eg,"").split(tg).map((Ye,He)=>He===0?Ye.toLowerCase():Ye.charAt(0).toUpperCase()+Ye.slice(1).toLowerCase()).join("")}Workflow`,{code:qe}=tr(s,a,{functionName:xe});return qe})(),te=()=>{navigator.clipboard.writeText(G),vn.success("Code copied to clipboard")},de=()=>{r&&t(Oe,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{T(r),o()}})};if(S&&!m)return le("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:"Connection"}),le("div",{className:"flex-1 space-y-4 overflow-y-auto px-6 pt-4 pb-6",children:[le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"edge-id",children:"Connection ID"}),Z(se,{disabled:!0,id:"edge-id",value:S.id})]}),le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"edge-source",children:"Source"}),Z(se,{disabled:!0,id:"edge-source",value:S.source})]}),le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"edge-target",children:"Target"}),Z(se,{disabled:!0,id:"edge-target",value:S.target})]}),u&&Z("div",{className:"pt-2",children:le(O,{onClick:de,variant:"ghost",children:[Z(ms,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!m){let B=f==="properties"||f==="code"||f==="runs"&&u?f:"properties";return le("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:N()}),le("div",{className:"flex-1 overflow-y-auto",children:[B==="properties"&&le("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"workflow-name",children:"Workflow Name"}),Z(se,{disabled:!u,id:"workflow-name",onChange:xe=>M(xe.target.value),value:d})]}),le("div",{className:"space-y-2",children:[Z(F,{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&&le("div",{className:"flex items-center gap-2 pt-2",children:[le(O,{onClick:b,variant:"ghost",children:[Z(us,{className:"mr-2 size-4"}),"Clear"]}),le(O,{onClick:R,variant:"ghost",children:[Z(ms,{className:"mr-2 size-4"}),"Delete"]})]})]}),B==="code"&&le("div",{className:"flex flex-col",children:[le("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[le("div",{className:"flex items-center gap-2",children:[Z(dd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),le(O,{className:"h-7 text-xs",onClick:te,size:"sm",variant:"ghost",children:[Z(ld,{className:"mr-1 size-3"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(ft,{defaultLanguage:"typescript",height:"100%",options:{readOnly:!0,minimap:{enabled:!1},lineNumbers:"on",scrollBeyondLastLine:!1,fontSize:12,wordWrap:"on"},value:G})})]}),B==="runs"&&u&&le("div",{className:"flex h-full flex-col",children:[le("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[Z(O,{className:"text-muted-foreground",disabled:I,onClick:X,size:"icon",variant:"ghost",children:Z(ud,{className:`size-4 ${I?"animate-spin":""}`})}),Z(O,{className:"text-muted-foreground",onClick:W,size:"icon",variant:"ghost",children:Z(us,{className:"size-4"})})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(dn,{isActive:B==="runs",onRefreshRef:h})})]})]}),le("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[le("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:()=>A("properties"),type:"button",children:[Z(md,{className:"size-5"}),"Workflow"]}),le("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:()=>A("code"),type:"button",children:[Z(id,{className:"size-5"}),"Code"]}),u&&le("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:()=>A("runs"),type:"button",children:[Z(cd,{className:"size-5"}),"Runs"]})]})]})}return le("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:N()}),le("div",{className:"flex-1 overflow-y-auto",children:[f==="properties"&&le("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[m.data.type==="action"&&!m.data.config?.actionType&&u&&Z(Vr,{disabled:l,isNewlyCreated:m?.id===w,onSelectAction:B=>{D("actionType",B),m?.id===w&&k(null)}}),m.data.type==="trigger"&&Z(Gr,{config:m.data.config||{},disabled:l||!u,onUpdateConfig:D,workflowId:i??void 0}),m.data.type==="action"&&m.data.config?.actionType!==void 0&&Z(Mr,{config:m.data.config||{},disabled:l||!u,isOwner:u,onUpdateConfig:D}),(m.data.type!=="action"||m.data.config?.actionType!==void 0)&&le(ps,{children:[le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"label",children:"Label"}),Z(se,{disabled:l||!u,id:"label",onChange:B=>j(B.target.value),value:m.data.label})]}),le("div",{className:"space-y-2",children:[Z(F,{htmlFor:"description",children:"Description"}),Z(se,{disabled:l||!u,id:"description",onChange:B=>z(B.target.value),placeholder:"Optional description",value:m.data.description||""})]})]}),u&&le("div",{className:"flex items-center gap-2 pt-2",children:[m.data.type==="action"&&Z(O,{className:"text-muted-foreground",onClick:re,size:"sm",variant:"ghost",children:m.data.enabled===!1?le(ps,{children:[Z(Yf,{className:"mr-2 size-4"}),"Disabled"]}):le(ps,{children:[Z(qf,{className:"mr-2 size-4"}),"Enabled"]})}),le(O,{className:"text-muted-foreground",onClick:P,size:"sm",variant:"ghost",children:[Z(ms,{className:"mr-2 size-4"}),"Delete"]})]})]}),U&&le("div",{className:`flex flex-col ${f==="code"?"":"invisible absolute -z-10"}`,children:[le("div",{className:"flex shrink-0 items-center justify-between border-b bg-muted/30 px-3 py-2",children:[le("div",{className:"flex items-center gap-2",children:[Z(dd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:og(m)})]}),le(O,{className:"text-muted-foreground",onClick:V,size:"sm",variant:"ghost",children:[Z(ld,{className:"mr-2 size-4"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(ft,{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:sn(m,i)})})]}),f==="runs"&&u&&le("div",{className:"flex h-full flex-col",children:[le("div",{className:"flex shrink-0 items-center gap-2 border-b px-4 py-2",children:[le(O,{className:"text-muted-foreground",disabled:I,onClick:X,size:"sm",variant:"ghost",children:[Z(ud,{className:`mr-2 size-4 ${I?"animate-spin":""}`}),"Refresh"]}),le(O,{className:"text-muted-foreground",onClick:W,size:"sm",variant:"ghost",children:[Z(us,{className:"mr-2 size-4"}),"Clear All"]})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(dn,{isActive:f==="runs",onRefreshRef:h})})]})]}),le("div",{className:"flex shrink-0 items-center justify-around border-t bg-background pb-safe",children:[le("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${f==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>A("properties"),type:"button",children:[Z(md,{className:"size-5"}),"Properties"]}),U&&le("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${f==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>A("code"),type:"button",children:[Z(id,{className:"size-5"}),"Code"]}),u&&le("button",{className:`flex flex-1 flex-col items-center gap-1 py-3 font-medium text-xs transition-colors ${f==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>A("runs"),type:"button",children:[Z(cd,{className:"size-5"}),"Runs"]})]})]})}import{Download as ag,FlaskConical as sg}from"lucide-react";import{cva as ng}from"class-variance-authority";import{jsx as fs}from"react/jsx-runtime";var rg=ng("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 fs("div",{"data-slot":"alert",role:"alert",className:x(rg({variant:t}),e),...o})}function fd({className:e,...t}){return fs("div",{"data-slot":"alert-title",className:x("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function gd({className:e,...t}){return fs("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 hn,jsxs as Zr}from"react/jsx-runtime";function yd({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=ne();return Zr(De,{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:[Zr("div",{className:"flex items-center gap-2 text-muted-foreground",children:[hn(ag,{className:"size-5"}),hn("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),hn("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."}),Zr(pd,{className:"mt-4",children:[hn(sg,{className:"size-4"}),hn(fd,{children:"Experimental Feature"}),Zr(gd,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",hn("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 ig}from"lucide-react";import{jsx as po,jsxs as ea}from"react/jsx-runtime";function vd({overlayId:e,onConfirm:t}){let{closeAll:o}=ne();return ea(De,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[ea("div",{className:"flex items-center gap-2 text-muted-foreground",children:[po(ig,{className:"size-5 shrink-0"}),po("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),ea("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[po("li",{children:"View the workflow structure and steps"}),po("li",{children:"See action types and configurations"}),po("li",{children:"Duplicate the workflow to their own account"})]}),po("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),ea("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[po("li",{children:"Your integration credentials (API keys, tokens)"}),po("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as hd,useSetAtom as lg}from"jotai";import{AlertTriangle as dg}from"lucide-react";import{jsx as Qe,jsxs as ut}from"react/jsx-runtime";function bd({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:s}=ne(),a=lg(Pt),l=zt(),i=hd(Ht),d=hd(xo),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:p}=t,g=c.length+u.length+p.length,T=(k,f)=>{o(k,f),l?r(Qr,{}):s()},v=k=>{r(ro,{type:k,onSuccess:()=>{a(f=>f+1)}})},y=k=>{i?.integrationType===k&&d?.enabled&&d?.isVercelUser&&i?r(i.ConsentOverlay,{onConsent:()=>{a(I=>I+1)},onManualEntry:()=>v(k)}):v(k)};return ut(De,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{s(),n()}},{label:"Cancel",onClick:s}],overlayId:e,title:`Workflow Issues (${g})`,children:[ut("div",{className:"flex items-center gap-2 text-orange-500",children:[Qe(dg,{className:"size-5"}),Qe("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),ut("div",{className:"mt-4 space-y-4",children:[p.length>0&&ut("div",{className:"space-y-1",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),p.map(k=>ut("div",{className:"flex items-center gap-3 py-1",children:[Qe(Rt,{className:"size-4 shrink-0",integration:k.integrationType}),ut("p",{className:"min-w-0 flex-1 text-sm",children:[Qe("span",{className:"font-medium",children:k.integrationLabel}),ut("span",{className:"text-muted-foreground",children:[" \u2014 ",k.nodeNames.length>3?`${k.nodeNames.slice(0,3).join(", ")} +${k.nodeNames.length-3} more`:k.nodeNames.join(", ")]})]}),Qe(O,{className:"shrink-0",onClick:()=>y(k.integrationType),size:"sm",variant:"outline",children:"Add"})]},k.integrationType))]}),c.length>0&&ut("div",{className:"space-y-2",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(k=>ut("div",{children:[Qe("p",{className:"font-medium text-sm",children:k.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:k.brokenReferences.map((f,A)=>ut("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[ut("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[Qe("span",{className:"font-mono",children:f.displayText})," in ",f.fieldLabel]}),Qe(O,{className:"shrink-0",onClick:()=>T(k.nodeId,f.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${k.nodeId}-${f.fieldKey}-${A}`))})]},k.nodeId))]}),u.length>0&&ut("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(k=>ut("div",{children:[Qe("p",{className:"font-medium text-sm",children:k.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:k.missingFields.map(f=>ut("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:f.fieldLabel}),Qe(O,{className:"shrink-0",onClick:()=>T(k.nodeId,f.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${k.nodeId}-${f.fieldKey}`))})]},k.nodeId))]})]})]})}import{jsx as gs,jsxs as cg}from"react/jsx-runtime";function wd({className:e}){return cg("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[gs("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"}),gs("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"}),gs("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 Pg,LogOut as Eg,Moon as Dg,Plug as Rg,Settings as Og,Sun as Lg}from"lucide-react";import{useTheme as Mg}from"next-themes";import Fg from"next/link";import{useEffect as Ld,useState as Md}from"react";import{Copy as ug,Key as mg,Trash2 as pg}from"lucide-react";import{useCallback as fg,useEffect as gg,useState as bn}from"react";import{toast as wn}from"sonner";import{jsx as Be,jsxs as At}from"react/jsx-runtime";function yg({overlayId:e,onCreated:t}){let{pop:o}=ne(),[n,r]=bn(""),[s,a]=bn(!1);return At(De,{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 d=await i.json();t(d),wn.success("API key created successfully"),o()}catch(i){console.error("Failed to create API key:",i),wn.error(i instanceof Error?i.message:"Failed to create API key")}finally{a(!1)}},loading:s}],overlayId:e,title:"Create API Key",children:[Be("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),At("div",{className:"space-y-2",children:[Be(F,{htmlFor:"key-name",children:"Label (optional)"}),Be(se,{id:"key-name",onChange:i=>r(i.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function xd({overlayId:e}){let{push:t,closeAll:o}=ne(),[n,r]=bn(!0),[s,a]=bn([]),[l,i]=bn(null),[d,c]=bn(null),u=fg(async()=>{r(!0);try{let w=await fetch("/api/api-keys");if(!w.ok)throw new Error("Failed to load API keys");let k=await w.json();a(k)}catch(w){console.error("Failed to load API keys:",w),wn.error("Failed to load API keys")}finally{r(!1)}},[]);gg(()=>{u()},[u]);let p=w=>{i(w.key??null),a(k=>[w,...k])},g=async w=>{c(w);try{if(!(await fetch(`/api/api-keys/${w}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(f=>f.filter(A=>A.id!==w)),wn.success("API key deleted")}catch(k){console.error("Failed to delete API key:",k),wn.error("Failed to delete API key")}finally{c(null)}},T=w=>{t(Oe,{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:()=>g(w)})},v=w=>{navigator.clipboard.writeText(w),wn.success("Copied to clipboard")},y=w=>new Date(w).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return At(De,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(yg,{onCreated:p})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Be("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Be("div",{className:"flex items-center justify-center py-8",children:Be(Nt,{})}):At("div",{className:"space-y-4",children:[l&&At("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Be("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!"}),At("div",{className:"flex items-center gap-2",children:[Be("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:l}),Be(O,{onClick:()=>v(l),size:"sm",variant:"outline",children:Be(ug,{className:"size-4"})})]}),Be(O,{className:"mt-2",onClick:()=>i(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),s.length===0?At("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Be(mg,{className:"mx-auto mb-2 size-8 opacity-50"}),Be("p",{children:"No API keys yet"}),Be("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Be("div",{className:"space-y-2",children:s.map(w=>At("div",{className:"flex items-center justify-between rounded-md border p-3",children:[At("div",{className:"min-w-0 flex-1",children:[At("div",{className:"flex items-center gap-2",children:[At("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[w.keyPrefix,"..."]}),w.name&&Be("span",{className:"truncate text-sm",children:w.name})]}),At("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",y(w.createdAt),w.lastUsedAt&&` \xB7 Last used ${y(w.lastUsedAt)}`]})]}),Be(O,{disabled:d===w.id,onClick:()=>T(w.id),size:"sm",variant:"ghost",children:d===w.id?Be(Nt,{className:"size-4"}):Be(pg,{className:"size-4 text-destructive"})})]},w.id))})]})]})}import{useSetAtom as kg}from"jotai";import{Search as Cg}from"lucide-react";import{useCallback as hs,useEffect as Tg,useRef as Ag,useState as kd}from"react";import{Pencil as vg,Trash2 as hg}from"lucide-react";import{useCallback as bg,useEffect as wg,useMemo as xg,useState as ys}from"react";import{toast as ta}from"sonner";import{jsx as Ge,jsxs as vs}from"react/jsx-runtime";var Ng={database:"Database"};function Nd({onIntegrationChange:e,filter:t=""}){let{push:o}=ne(),[n,r]=ys([]),[s,a]=ys(!0),[l,i]=ys(null),d=bg(async()=>{try{a(!0);let v=await q.integration.getAll();r(v)}catch(v){console.error("Failed to load integrations:",v),ta.error("Failed to load integrations")}finally{a(!1)}},[]);wg(()=>{d()},[d]);let c=xg(()=>{let v=Yt(),y=t.toLowerCase();return n.map(w=>({...w,label:v[w.type]||Ng[w.type]||w.type})).filter(w=>t?w.label.toLowerCase().includes(y)||w.name.toLowerCase().includes(y)||w.type.toLowerCase().includes(y):!0).sort((w,k)=>{let f=w.label.localeCompare(k.label);return f!==0?f:w.name.localeCompare(k.name)})},[n,t]),u=v=>{o(Rr,{integration:v,onSuccess:()=>{d(),e?.()},onDelete:()=>{d(),e?.()}})},p=v=>{o(La,{integration:v,onSuccess:()=>{d(),e?.()}})},g=async v=>{try{i(v);let y=await q.integration.testConnection(v);y.status==="success"?ta.success(y.message||"Connection successful"):ta.error(y.message||"Connection test failed")}catch(y){console.error("Connection test failed:",y),ta.error(y instanceof Error?y.message:"Connection test failed")}finally{i(null)}};return s?Ge("div",{className:"flex items-center justify-center py-8",children:Ge(Nt,{})}):Ge("div",{className:"space-y-1",children:n.length===0?Ge("div",{className:"py-8 text-center",children:Ge("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?Ge("div",{className:"py-8 text-center",children:Ge("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):Ge("div",{className:"space-y-1",children:c.map(v=>vs("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[vs("div",{className:"flex items-center gap-2",children:[Ge(Rt,{className:"size-4",integration:v.type==="ai-gateway"?"vercel":v.type}),Ge("span",{className:"font-medium text-sm",children:v.label}),Ge("span",{className:"text-muted-foreground text-sm",children:v.name})]}),vs("div",{className:"flex items-center gap-1",children:[Ge(O,{className:"h-7 px-2",disabled:l===v.id,onClick:()=>g(v.id),size:"sm",variant:"outline",children:l===v.id?Ge(Nt,{className:"size-3"}):Ge("span",{className:"text-xs",children:"Test"})}),Ge(O,{className:"size-7",onClick:()=>u(v),size:"icon",variant:"outline",children:Ge(vg,{className:"size-3"})}),Ge(O,{className:"size-7",onClick:()=>p(v),size:"icon",variant:"outline",children:Ge(hg,{className:"size-3"})})]})]},v.id))})})}import{jsx as Ro,jsxs as bs}from"react/jsx-runtime";function Cd({overlayId:e}){let{push:t,closeAll:o}=ne(),[n,r]=kd(!0),[s,a]=kd(""),l=kg(Pt),i=Ag(!1),d=hs(async()=>{r(!0);try{await new Promise(g=>setTimeout(g,0))}finally{r(!1)}},[]);Tg(()=>{d(),i.current=!1,a("")},[d]);let c=hs(()=>{i.current&&l(g=>g+1),o()},[o,l]),u=hs(()=>{i.current=!0},[]);return bs(De,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(Fi,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[Ro("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?Ro("div",{className:"flex items-center justify-center py-8",children:Ro(Nt,{})}):bs("div",{className:"space-y-4",children:[bs("div",{className:"relative",children:[Ro(Cg,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ro(se,{className:"pl-9",onChange:g=>a(g.target.value),placeholder:"Filter connections...",value:s})]}),Ro("div",{className:"max-h-[300px] overflow-y-auto",children:Ro(Nd,{filter:s,onIntegrationChange:u})})]})]})}import{useCallback as Id,useEffect as Sg,useState as ra}from"react";import{toast as Pd}from"sonner";import{jsx as na}from"react/jsx-runtime";function oa({className:e,...t}){return na("div",{"data-slot":"card",className:x("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Td({className:e,...t}){return na("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function Ad({className:e,...t}){return na("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function ws({className:e,...t}){return na("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import{jsx as Kn,jsxs as xs}from"react/jsx-runtime";function Sd({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return Kn(oa,{className:"border-0 py-0 shadow-none",children:xs(ws,{className:"space-y-4 p-0",children:[xs("div",{className:"space-y-2",children:[Kn(F,{className:"ml-1",htmlFor:"accountName",children:"Name"}),Kn(se,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),xs("div",{className:"space-y-2",children:[Kn(F,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),Kn(se,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as aa,jsxs as Ig}from"react/jsx-runtime";function Ed({overlayId:e}){let{closeAll:t}=ne(),[o,n]=ra(!0),[r,s]=ra(!1),[a,l]=ra(""),[i,d]=ra(""),c=Id(async()=>{try{let g=await q.user.get();l(g.name||""),d(g.email||"")}catch(g){console.error("Failed to load account:",g)}},[]),u=Id(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return Sg(()=>{u()},[u]),Ig(De,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{s(!0),await q.user.update({name:a,email:i}),await c(),Pd.success("Settings saved"),t()}catch(g){console.error("Failed to save account:",g),Pd.error("Failed to save settings")}finally{s(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[aa("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?aa("div",{className:"flex items-center justify-center py-8",children:aa(Nt,{})}):aa(Sd,{accountEmail:i,accountName:a,onEmailChange:d,onNameChange:l})]})}import{Avatar as Ns}from"radix-ui";import{jsx as ks}from"react/jsx-runtime";function Dd({className:e,...t}){return ks(Ns.Root,{"data-slot":"avatar",className:x("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function Rd({className:e,...t}){return ks(Ns.Image,{"data-slot":"avatar-image",className:x("aspect-square size-full",e),...t})}function Od({className:e,...t}){return ks(Ns.Fallback,{"data-slot":"avatar-fallback",className:x("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as he,jsxs as Ot}from"react/jsx-runtime";var Fd=()=>{let{data:e,isPending:t}=cn(),{theme:o,setTheme:n}=Mg(),{open:r}=ne(),[s,a]=Md(null),[l,i]=Md(!1);Ld(()=>{i(!0)},[]),Ld(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&q.user.get().then(g=>a(g.providerId)).catch(()=>a(null))},[e?.user]);let d=async()=>{await Sl()},c=s==="vercel"||s==="github"||s==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(g=>g[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!l?he("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?he("div",{className:"flex items-center gap-2",children:he(O,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:he(Fg,{href:"/auth/sign-in",children:"Sign In"})})}):Ot(To,{children:[he(Ao,{asChild:!0,children:he(O,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ot(Dd,{className:"h-9 w-9",children:[he(Rd,{alt:e?.user?.name||"",src:e?.user?.image||""}),he(Od,{children:u()})]})})}),Ot(So,{align:"end",className:"w-56",children:[he(ol,{children:Ot("div",{className:"flex flex-col space-y-1",children:[he("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),he("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),he(Fn,{}),!c&&Ot(ht,{onClick:()=>r(Ed),children:[he(Og,{className:"size-4"}),he("span",{children:"Settings"})]}),Ot(ht,{onClick:()=>r(Cd),children:[he(Rg,{className:"size-4"}),he("span",{children:"Connections"})]}),Ot(ht,{onClick:()=>r(xd),children:[he(Pg,{className:"size-4"}),he("span",{children:"API Keys"})]}),Ot(nl,{children:[Ot(rl,{children:[he(Lg,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),he(Dg,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),he("span",{children:"Theme"})]}),he(al,{children:Ot(tl,{onValueChange:n,value:o,children:[he(Br,{value:"light",children:"Light"}),he(Br,{value:"dark",children:"Dark"}),he(Br,{value:"system",children:"System"})]})})]}),he(Fn,{}),Ot(ht,{onClick:d,children:[he(Eg,{className:"size-4"}),he("span",{children:"Logout"})]})]})]})};import{Fragment as ia,jsx as K,jsxs as Pe}from"react/jsx-runtime";function _d(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var qg={"Database Query":"database"},Yg={database:"Database"};function Jg(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 Kd(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Jg(r);for(let l of a)o.push({field:s,...l})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...Kd(r,s))}return o}function Xg(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=Kd(r).filter(l=>!t.has(l.nodeId));if(a.length>0){let l=r.actionType,i=l?pe(l):void 0,d=i?fa(i.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||i?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=d.find(p=>p.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function Qg(e){return e==null||typeof e=="string"&&e.trim()===""}function Zg(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=pe(o);if(!n)return null;let s=fa(n.configFields).filter(a=>a.required&&Zg(a,t||{})&&Qg(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 ty(e){return e.map(ey).filter(t=>t!==null)}function oy(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,s=Yt();for(let a of e){if(a.data.enabled===!1)continue;let l=a.data.config?.actionType;if(!l)continue;let d=pe(l)?.integration||qg[l];if(!d||!Fo(d))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(d)){let p=r.get(d)||[],g=pe(l);p.push(a.data.label||g?.label||l),r.set(d,p)}}return Array.from(r.entries()).map(([a,l])=>({integrationType:a,integrationLabel:s[a]||Yg[a]||a,nodeNames:l}))}async function ny({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:s}){_d(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();s(l.executionId);let i=setInterval(async()=>{try{let d=await q.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=i}catch(a){console.error("Failed to execute workflow:",a),it.error(a instanceof Error?a.message:"Failed to execute workflow"),_d(t,o,"error"),r(!1)}}function ry({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:s,setIsSaving:a,setHasUnsavedChanges:l,setActiveTab:i,setNodes:d,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:p,userIntegrations:g}){let{open:T}=ne(),v=jg(null);Ts(()=>()=>{v.current&&clearInterval(v.current)},[]);let y=async()=>{if(e){a(!0);try{await q.workflow.update(e,{nodes:t,edges:o}),l(!1)}catch(A){console.error("Failed to save workflow:",A),it.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},w=async()=>{if(!e){it.error("Please save the workflow before executing");return}i("runs"),d(t.map(A=>({...A,selected:!1}))),c(o.map(A=>({...A,selected:!1}))),u(null),s(!0),await ny({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:v,setIsExecuting:s,setSelectedExecutionId:p})},k=(A,I)=>{u(A),i("properties"),I&&setTimeout(()=>{let C=document.getElementById(I);C&&(C.focus(),C.scrollIntoView({behavior:"smooth",block:"center"}))},100)};return{handleSave:y,handleExecute:async()=>{if(r)return;let A=Xg(t),I=ty(t),C=oy(t,g);if(A.length>0||I.length>0||C.length>0){T(bd,{issues:{brokenReferences:A,missingRequiredFields:I,missingIntegrations:C},onGoToStep:k,onRunAnyway:w});return}await w()}}}function ay(){let[e,t]=Ze(oe),[o,n]=Ze(ue),[r,s]=Ze(Ks),[a]=Ze(wt),l=Gt(fr),i=Gt(Zt),[d]=Ze($e),[c,u]=Ze(pt),[p,g]=Ze(ar),T=zd(Xt),v=Kg(),[y,w]=Ze(gr),[k,f]=Ze(tt),A=Gt(ti),I=Gt(oi),C=Gt(Vo),[h]=Ze(ni),[m]=Ze(ri),{data:S}=cn(),J=Gt(Ft),D=Gt(be),j=Gt(Qt),z=zd(mt),[re,P]=Ze(mr),[V,X]=Cs(!1),[W,U]=Cs(!1),[N,M]=Cs([]);return Ts(()=>{(async()=>{try{let R=await q.workflow.getAll();M(R)}catch(R){console.error("Failed to load workflows:",R)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:s,isGenerating:a,clearWorkflow:l,updateNodeData:i,currentWorkflowId:d,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:p,setWorkflowVisibility:g,isOwner:T,router:v,isSaving:y,setIsSaving:w,hasUnsavedChanges:k,setHasUnsavedChanges:f,undo:A,redo:I,addNode:C,canUndo:h,canRedo:m,session:S,isDownloading:V,setIsDownloading:X,isDuplicating:W,setIsDuplicating:U,allWorkflows:N,setAllWorkflows:M,setActiveTab:J,setNodes:t,setEdges:n,setSelectedNodeId:D,setSelectedExecutionId:j,userIntegrations:z,triggerExecute:re,setTriggerExecute:P}}function sy(e){let{open:t}=ne(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:s,updateNodeData:a,isExecuting:l,setIsExecuting:i,setIsSaving:d,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:p,setAllWorkflows:g,setIsDownloading:T,setIsDuplicating:v,setActiveTab:y,setNodes:w,setEdges:k,setSelectedNodeId:f,setSelectedExecutionId:A,userIntegrations:I,triggerExecute:C,setTriggerExecute:h,router:m,session:S}=e,{handleSave:J,handleExecute:D}=ry({currentWorkflowId:o,nodes:r,edges:s,updateNodeData:a,isExecuting:l,setIsExecuting:i,setIsSaving:d,setHasUnsavedChanges:c,setActiveTab:y,setNodes:w,setEdges:k,setSelectedNodeId:f,setSelectedExecutionId:A,userIntegrations:I});return Ts(()=>{C&&(h(!1),D())},[C,h,D]),{handleSave:J,handleExecute:D,handleClearWorkflow:()=>{t(Oe,{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(Oe,{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),it.success("Workflow deleted successfully"),window.location.href="/"}catch(W){console.error("Failed to delete workflow:",W),it.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){it.error("Please save the workflow before downloading");return}T(!0),it.info("Preparing workflow files for download...");try{let W=await q.workflow.download(o);if(!W.success)throw new Error(W.error||"Failed to prepare download");if(!W.files)throw new Error("No files to download");let U=(await import("jszip")).default,N=new U;for(let[G,te]of Object.entries(W.files))N.file(G,te);let M=await N.generateAsync({type:"blob"}),b=URL.createObjectURL(M),R=document.createElement("a");R.href=b,R.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(R),R.click(),document.body.removeChild(R),URL.revokeObjectURL(b),it.success("Workflow downloaded successfully!")}catch(W){it.error(W instanceof Error?W.message:"Failed to download workflow")}finally{T(!1)}},loadWorkflows:async()=>{try{let W=await q.workflow.getAll();g(W)}catch(W){console.error("Failed to load workflows:",W)}},handleToggleVisibility:async W=>{if(o){if(W==="public"){t(vd,{onConfirm:async()=>{try{await q.workflow.update(o,{visibility:"public"}),p("public"),it.success("Workflow is now public")}catch(U){console.error("Failed to update visibility:",U),it.error("Failed to update visibility. Please try again.")}}});return}try{await q.workflow.update(o,{visibility:W}),p(W),it.success("Workflow is now private")}catch(U){console.error("Failed to update visibility:",U),it.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){v(!0);try{S?.user||(await Eo.signIn.anonymous(),await new Promise(U=>setTimeout(U,100)));let W=await q.workflow.duplicate(o);it.success("Workflow duplicated successfully"),m.push(`/workflows/${W.id}`)}catch(W){console.error("Failed to duplicate workflow:",W),it.error("Failed to duplicate workflow. Please try again.")}finally{v(!1)}}}}}function iy({workflowId:e,state:t,actions:o}){let{open:n,push:r}=ne(),[s]=Ze(be),[a]=Ze(_e),[l]=Ze(oe),[i]=Ze(ue),d=Gt(eo),c=Gt(to),{screenToFlowPosition:u}=zg(),p=l.find(w=>w.id===s),g=i.find(w=>w.id===a),T=p||g;if(e&&!t.isOwner||!e)return null;let v=()=>{let k=!!s?"Node":"Connection";r(Oe,{title:`Delete ${k}`,message:`Are you sure you want to delete this ${k.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{s?d(s):a&&c(a)}})},y=()=>{let w=document.querySelector(".react-flow");if(!w)return;let k=w.getBoundingClientRect(),f=k.left+k.width/2,A=k.top+k.height/2,I=u({x:f,y:A}),C=192,h=192;I.x-=C/2,I.y-=h/2;let m=20,S=20,J={...I},D=!0,j=0,z=20;for(;D&&j<z;)D=t.nodes.some(P=>{let V=Math.abs(P.position.x-J.x),X=Math.abs(P.position.y-J.y);return V<S&&X<S}),D&&(J.x+=m,J.y+=m,j+=1);let re={id:Ug(),type:"action",position:J,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode(re),t.setSelectedNodeId(re.id),t.setActiveTab("properties")};return Pe(ia,{children:[K(Vt,{className:"flex lg:hidden",orientation:"vertical",children:K(O,{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:K(Vd,{className:"size-4"})})}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[K(O,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(Qr,{}),size:"icon",title:"Configuration",variant:"secondary",children:K(_g,{className:"size-4"})}),T&&K(O,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:v,size:"icon",title:"Delete",variant:"secondary",children:K($g,{className:"size-4"})})]}),K(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:K(O,{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:K(Vd,{className:"size-4"})})}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[K(O,{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:K(Hd,{className:"size-4"})}),K(O,{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:K(Gd,{className:"size-4"})})]}),Pe(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:[K(O,{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:K(Hd,{className:"size-4"})}),K(O,{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:K(Gd,{className:"size-4"})})]}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[K($d,{handleSave:o.handleSave,state:t}),K(Ud,{actions:o,state:t})]}),Pe(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:[K($d,{handleSave:o.handleSave,state:t}),K(Ud,{actions:o,state:t})]}),K(ly,{actions:o,state:t}),K(dy,{actions:o,state:t})]})}function $d({state:e,handleSave:t}){return Pe(O,{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?K(la,{className:"size-4 animate-spin"}):K(Hg,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&K("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function Ud({state:e,actions:t}){let{open:o}=ne(),n=()=>{o(yd,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return K(O,{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?K(la,{className:"size-4 animate-spin"}):K(Vg,{className:"size-4"})})}function ly({state:e,actions:t}){let o=e.workflowVisibility==="public";return Pe(To,{children:[K(Ao,{asChild:!0,children:K(O,{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?K(Wd,{className:"size-4"}):K(Bd,{className:"size-4"})})}),Pe(So,{align:"end",children:[Pe(ht,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[K(Bd,{className:"size-4"}),"Private",!o&&K(sa,{className:"ml-auto size-4"})]}),Pe(ht,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[K(Wd,{className:"size-4"}),"Public",o&&K(sa,{className:"ml-auto size-4"})]})]})]})}function dy({state:e,actions:t}){return K(O,{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?K(la,{className:"size-4 animate-spin"}):K(Gg,{className:"size-4"})})}function cy({isDuplicating:e,onDuplicate:t}){return Pe(O,{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?K(la,{className:"mr-2 size-4 animate-spin"}):K(Bg,{className:"mr-2 size-4"}),"Duplicate"]})}function uy({workflowId:e,state:t,actions:o}){return Pe("div",{className:"flex flex-col gap-1",children:[K("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(To,{onOpenChange:n=>n&&o.loadWorkflows(),children:[Pe(Ao,{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:[K(wd,{className:"size-4 shrink-0"}),K("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:Pe(ia,{children:[K("span",{className:"sm:hidden",children:"New"}),K("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),K(Wg,{className:"size-3 shrink-0 opacity-50"})]}),Pe(So,{align:"start",className:"w-64",children:[K(ht,{asChild:!0,className:"flex items-center justify-between",children:Pe("a",{href:"/",children:["New Workflow"," ",!e&&K(sa,{className:"size-4 shrink-0"})]})}),K(Fn,{}),t.allWorkflows.length===0?K(ht,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>Pe(ht,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[K("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&K(sa,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&K("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var jd=({workflowId:e})=>{let t=ay(),o=sy(t);return Pe(ia,{children:[K(Xr,{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:[K(uy,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&K("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),K("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:[K(iy,{actions:o,state:t,workflowId:e}),Pe("div",{className:"flex items-center gap-2",children:[!e&&Pe(ia,{children:[K(ad,{}),K(Ql,{})]}),e&&!t.isOwner&&K(cy,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),K(Fd,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as Qy,Zap as Zy}from"lucide-react";import{nanoid as Rs}from"nanoid";import{BaseEdge as Jd,getBezierPath as my,getSimpleBezierPath as py,Position as Oo,useInternalNode as qd}from"@xyflow/react";import{jsx as Xd}from"react/jsx-runtime";var fy=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:s,targetPosition:a,selected:l})=>{let[i]=py({sourceX:t,sourceY:o,sourcePosition:s,targetX:n,targetY:r,targetPosition:a});return Xd(Jd,{className:"stroke-1",id:e,path:i,style:{stroke:l?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},Yd=(e,t)=>{let o=t===Oo.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 Oo.Left:r=0;break;case Oo.Right:r=n.width;break;case Oo.Top:s=0;break;case Oo.Bottom:s=n.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let a=e.internals.positionAbsolute.x+n.x+r,l=e.internals.positionAbsolute.y+n.y+s;return[a,l]},gy=(e,t)=>{let o=Oo.Right,[n,r]=Yd(e,o),s=Oo.Left,[a,l]=Yd(t,s);return{sx:n,sy:r,tx:a,ty:l,sourcePos:o,targetPos:s}},yy=({id:e,source:t,target:o,style:n,selected:r})=>{let s=qd(t),a=qd(o);if(!(s&&a))return null;let{sx:l,sy:i,tx:d,ty:c,sourcePos:u,targetPos:p}=gy(s,a),[g]=my({sourceX:l,sourceY:i,sourcePosition:u,targetX:d,targetY:c,targetPosition:p});return Xd(Jd,{id:e,path:g,style:{...n,stroke:r?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},As={Temporary:fy,Animated:yy};import{useAtomValue as Xn}from"jotai";import{AlertTriangle as by,Check as wy,Code as xy,EyeOff as tc,XCircle as Ny,Zap as rc}from"lucide-react";import oc from"next/image";import{memo as ky,useState as Cy}from"react";import{Handle as Zd,Position as ec}from"@xyflow/react";import{Fragment as vy,jsx as fo,jsxs as Ss}from"react/jsx-runtime";var Qd=({className:e})=>Ss(vy,{children:[fo("style",{children:`
|
|
192
|
+
}`:""}function dp(e){if(!e)return $a;if(yl[e])return yl[e];let t=pe(e);return t&&t.codegenTemplate||$a}var sn=(e,t)=>e.data.type==="trigger"?lp(e.data.config,t):e.data.type==="action"?dp(e.data.config?.actionType):ip;import{useAtom as Ua}from"jotai";import{Check as wl,ChevronDown as ja,ChevronRight as qa,Clock as mp,Copy as pp,ExternalLink as fp,Loader2 as gp,Play as yp,Square as hl,X as vp}from"lucide-react";import bl from"next/image";import{useCallback as Bn,useEffect as _r,useRef as hp,useState as Io}from"react";function ln(e,t){return`${e} ${t}${e===1?"":"s"} ago`}function vl(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 ln(r,"min");let s=Math.floor(r/60);if(s<24)return ln(s,"hour");let a=Math.floor(s/24);if(a<7)return ln(a,"day");let l=Math.floor(a/7);if(l<4)return ln(l,"week");let i=Math.floor(a/30);if(i<12)return ln(i,"month");let d=Math.floor(a/365);return ln(d,"year")}import{Loader2Icon as cp}from"lucide-react";import{jsx as up}from"react/jsx-runtime";function Nt({className:e,...t}){let{ref:o,...n}=t;return up(cp,{role:"status","aria-label":"Loading",className:x("size-4 animate-spin",e),...n})}import{Fragment as Ur,jsx as H,jsxs as Fe}from"react/jsx-runtime";function bp(e){return Ms(e)}function wp(e,t){if(typeof e!="object"||e===null)return;let o=e[t.field];if(typeof o=="string"&&o.length>0)return o}function xp(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}function Ka(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 Np(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}function xl({data:e}){let o=JSON.stringify(e,null,2).split(/("https?:\/\/[^"]+"|"[^"]*")/g);return H(Ur,{children:o.map(n=>{if(n.startsWith('"')&&n.endsWith('"')){let r=n.slice(1,-1);if(Np(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 kp({data:e,isError:t=!1}){let[o,n]=Io(!1);return H(R,{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(wl,{className:"h-3 w-3 text-green-600"}):H(pp,{className:"h-3 w-3"})})}function $r({title:e,children:t,defaultExpanded:o=!1,copyData:n,isError:r=!1,externalLink:s}){let[a,l]=Io(o);return Fe("div",{children:[Fe("div",{className:"mb-2 flex w-full items-center justify-between",children:[Fe("button",{className:"flex items-center gap-1.5",onClick:()=>l(!a),type:"button",children:[a?H(ja,{className:"h-3 w-3 text-muted-foreground"}):H(qa,{className:"h-3 w-3 text-muted-foreground"}),H("span",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:e})]}),Fe("div",{className:"flex items-center gap-1",children:[s&&H(R,{asChild:!0,className:"h-7 px-2",size:"sm",variant:"ghost",children:H("a",{href:s,rel:"noopener noreferrer",target:"_blank",children:H(fp,{className:"h-3 w-3"})})}),n!==void 0&&H(kp,{data:n,isError:r})]})]}),a&&t]})}function Cp({output:e,input:t,actionType:o}){let r=(o?pe(o):void 0)?.outputConfig,s=o?bp(o):void 0,a=r?.type!=="component"?r:s,l=a?wp(e,a):void 0,i=!(r||s)&&xp(e),c=(()=>{if(r?.type==="component"){let g=r.component;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(g,{input:t,output:e})})}if(a&&l)switch(a.type){case"image":{let g=a.field==="base64"&&!l.startsWith("data:")?`data:image/png;base64,${l}`:l;return H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(bl,{alt:"Generated image",className:"max-h-96 w-auto rounded",height:384,src:g,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:l,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:l,title:"Output preview"})});default:return null}return i?H("div",{className:"overflow-hidden rounded-lg border bg-muted/50 p-3",children:H(bl,{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,p=a?.type==="url"&&l?l:void 0;return Fe(Ur,{children:[H($r,{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(xl,{data:e})})}),u&&H($r,{defaultExpanded:!0,externalLink:p,title:"Result",children:c})]})}function Tp({log:e,isExpanded:t,onToggle:o,getStatusIcon:n,getStatusDotClass:r,isFirst:s,isLast:a}){return Fe("div",{className:"relative flex gap-3",children:[Fe("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"})]}),Fe("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:Fe("div",{className:"flex items-center gap-3",children:[H("div",{className:"min-w-0 flex-1",children:Fe("div",{className:"flex items-center gap-2",children:[t?H(ja,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):H(qa,{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&&Fe("div",{className:"mt-2 mb-2 space-y-3 px-3",children:[e.input!==null&&e.input!==void 0&&H($r,{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(xl,{data:e.input})})}),e.output!==null&&e.output!==void 0&&H(Cp,{actionType:e.nodeType,input:e.input,output:e.output}),e.error&&H($r,{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 dn({isActive:e=!1,onRefreshRef:t,onStartRun:o}){let[n]=Ua($e),[r,s]=Ua(Qt),[,a]=Ua(fr),[l,i]=Io([]),[d,c]=Io({}),[u,p]=Io(new Set),[g,C]=Io(new Set),[v,y]=Io(!0),w=hp(null),k=Bn(async(L=!0)=>{if(!n){y(!1);return}try{L&&y(!0);let F=await j.workflow.getExecutions(n);i(F)}catch(F){console.error("Failed to load executions:",F),i([])}finally{L&&y(!1)}},[n]);_r(()=>{t&&(t.current=()=>k(!1))},[k,t]),_r(()=>{k()},[k]);let f=Bn((L,F)=>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})),[]),T=Bn(async L=>{try{let F=await j.workflow.getExecutionLogs(L),_=f(F.logs,F.execution.workflow);c(P=>({...P,[L]:_})),L===r&&a(Ka(_))}catch(F){console.error("Failed to load execution logs:",F),c(_=>({..._,[L]:[]}))}},[f,r,a]);_r(()=>{if(l.length===0)return;let L=l[0];L.status==="running"&&L.id!==w.current&&(w.current=L.id,s(L.id),p(F=>{let _=new Set(F);return _.add(L.id),_}),T(L.id),o&&o(L.id))},[l,s,T,o]);let I=Bn(async L=>{try{let F=await j.workflow.getExecutionLogs(L),_=f(F.logs,F.execution.workflow);c(P=>({...P,[L]:_})),L===r&&a(Ka(_))}catch(F){console.error(`Failed to refresh logs for ${L}:`,F)}},[f,r,a]);_r(()=>{if(!(e&&n))return;let F=setInterval(async()=>{try{let _=await j.workflow.getExecutions(n);i(_);for(let P of u)await I(P)}catch(_){console.error("Failed to poll executions:",_)}},2e3);return()=>clearInterval(F)},[e,n,u,I]);let A=Bn(async L=>{try{await j.workflow.cancelExecution(L),await k(!1)}catch(F){console.error("Failed to cancel execution:",F)}},[k]),h=async L=>{let F=new Set(u);F.has(L)?F.delete(L):(F.add(L),await T(L)),p(F)},m=L=>{if(r===L){s(null),a({});return}s(L);let F=d[L]||[];a(Ka(F))},S=L=>{let F=new Set(g);F.has(L)?F.delete(L):F.add(L),C(F)},X=L=>{switch(L){case"success":return H(wl,{className:"h-3 w-3 text-white"});case"error":return H(vp,{className:"h-3 w-3 text-white"});case"cancelled":return H(hl,{className:"h-3 w-3 text-white"});case"running":return H(gp,{className:"h-3 w-3 animate-spin text-white"});default:return H(mp,{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 v?H("div",{className:"flex items-center justify-center py-12",children:H(Nt,{})}):l.length===0?Fe("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(yp,{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:l.map((L,F)=>{let _=u.has(L.id),P=r===L.id,V=(d[L.id]||[]).sort((Y,M)=>new Date(Y.startedAt).getTime()-new Date(M.startedAt).getTime());return Fe("div",{className:x("overflow-hidden rounded-lg border bg-card transition-all",P&&"ring-2 ring-primary ring-offset-2 ring-offset-background"),children:[Fe("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:()=>h(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)})}),Fe("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:Fe("span",{className:"font-semibold text-sm",children:["Run #",l.length-F]})}),Fe("div",{className:"flex items-center gap-2 font-mono text-muted-foreground text-xs",children:[H("span",{children:vl(L.startedAt)}),L.duration&&Fe(Ur,{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&&Fe(Ur,{children:[H("span",{children:"\u2022"}),Fe("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:Y=>{Y.stopPropagation(),A(L.id)},title:"Stop execution",type:"button",children:H(hl,{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:()=>h(L.id),type:"button",children:_?H(ja,{className:"h-4 w-4 text-muted-foreground"}):H(qa,{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((Y,M)=>H(Tp,{getStatusDotClass:le,getStatusIcon:X,isExpanded:g.has(Y.id),isFirst:M===0,isLast:M===V.length-1,log:Y,onToggle:()=>S(Y.id)},Y.id))})})]},L.id)})})}import{Fragment as co,jsx as O,jsxs as U}from"react/jsx-runtime";var Ep=/[^a-zA-Z0-9\s]/g,Dp=/\s+/,Sl={"Database Query":"database"},Rp=({selectedNodes:e,selectedEdges:t,onDelete:o})=>{let[n,r]=Vn(!1),s=e.length===1?"node":"nodes",a=t.length===1?"line":"lines",l=[];e.length>0&&l.push(`${e.length} ${s}`),t.length>0&&l.push(`${t.length} ${a}`);let i=l.join(" and ");return U(co,{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(W,{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(R,{className:"text-muted-foreground",onClick:()=>r(!0),size:"sm",variant:"ghost",children:[O(jr,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(Go,{onOpenChange:r,open:n,children:U(Ho,{children:[U(_o,{children:[O(Uo,{children:"Delete Selected Items"}),U(Ko,{children:["Are you sure you want to delete ",i,"? This action cannot be undone."]})]}),U($o,{children:[O(qo,{children:"Cancel"}),O(jo,{onClick:()=>{o(),r(!1)},children:"Delete"})]})]})})]})},Op=()=>{let[e]=io(be),[t]=io(_e),[o]=io(oe),n=Ya(ue),[r]=io(wt),[s]=io($e),[a,l]=io(pt),i=Ya(Xt),d=lo(Zt),c=lo(eo),u=lo(to),p=lo(Xs),g=lo(Qs),C=lo(Zs),v=lo(vr),y=lo(mr),[w,k]=io(Jt),[f,T]=Vn(!1),[I,A]=Vn(!1),[h,m]=Vn(!1),[S,X]=Vn(!1),[le,L]=io(Ft),F=Al(null),_=Al({}),P=o.find(ee=>ee.id===e),V=n.find(ee=>ee.id===t),Y=o.filter(ee=>ee.selected),M=n.filter(ee=>ee.selected),K=Y.length+M.length>1;Tl(()=>{if(!P||le!=="code")return;let ee=P.data.config?.actionType==="Condition",ve=P.data.type==="trigger"&&P.data.config?.triggerType==="Manual";(ee||ve)&&L("properties")},[P,le,L]);let N=Ya(mt);Tl(()=>{if(!(P&&i))return;let ee=P.data.config?.actionType,ve=P.data.config?.integrationId;if(!(ee&&ve))return;let E=pe(ee)?.integration||Sl[ee];if(!E||N.some(ce=>ce.id===ve))return;let J=N.filter(ce=>ce.type===E);if(J.length===1){let ce={...P.data.config,integrationId:J[0].id};d({id:P.id,data:{config:ce}})}else if(J.length===0){let ce={...P.data.config,integrationId:void 0};d({id:P.id,data:{config:ce}})}},[P,N,i,d]);let z=Pp(()=>{let ve=`${a.replace(Ep,"").split(Dp).map((E,$)=>$===0?E.toLowerCase():E.charAt(0).toUpperCase()+E.slice(1).toLowerCase()).join("")||"execute"}Workflow`,{code:Q}=or(o,n,{functionName:ve});return Q},[o,n,a]),b=()=>{P&&navigator.clipboard.writeText(sn(P))},D=()=>{navigator.clipboard.writeText(z),Kr.success("Code copied to clipboard")},G=()=>{e&&(c(e),T(!1))},te=()=>{if(P){let ee=P.data.enabled??!0;d({id:P.id,data:{enabled:!ee}})}},de=()=>{t&&(u(t),A(!1))},B=async()=>{if(s)try{await j.workflow.deleteExecutions(s),v(),m(!1)}catch(ee){console.error("Failed to delete runs:",ee);let ve=ee instanceof Error?ee.message:"Failed to delete runs";Kr.error(ve)}},xe=ee=>{P&&d({id:P.id,data:{label:ee}})},qe=ee=>{P&&d({id:P.id,data:{description:ee}})},Ye=Ip(async(ee,ve,Q,E)=>{let J=pe(ve)?.integration||Sl[ve];if(!J){y(ce=>{let Ee=new Set(ce);return Ee.delete(ee),Ee});return}try{let ce=await j.integration.getAll();if(E.aborted)return;let Ee=ce.filter(Re=>Re.type===J);if(Ee.length===1&&!E.aborted){let Re={...Q,actionType:ve,integrationId:Ee[0].id};d({id:ee,data:{config:Re}})}}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})}},[d,y]),He=(ee,ve)=>{if(P){let Q={...P.data.config,[ee]:ve};if(ee==="actionType"&&P.data.config?.integrationId&&(Q={...Q,integrationId:void 0}),d({id:P.id,data:{config:Q}}),ee==="actionType"){let E=_.current[P.id];E&&E.abort();let $=new AbortController;_.current[P.id]=$,y(J=>new Set(J).add(P.id)),Ye(P.id,ve,Q,$.signal)}}},qt=async ee=>{if(l(ee),s)try{await j.workflow.update(s,{name:ee,nodes:o,edges:n})}catch(ve){console.error("Failed to update workflow name:",ve),Kr.error("Failed to update workspace name")}},St=async()=>{X(!0);try{F.current&&await F.current()}catch(ee){console.error("Failed to refresh runs:",ee),Kr.error("Failed to refresh runs")}finally{X(!1)}};return K?O(Rp,{onDelete:p,selectedEdges:M,selectedNodes:Y}):V?U(co,{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(W,{className:"ml-1",htmlFor:"edge-id",children:"Edge ID"}),O(ae,{disabled:!0,id:"edge-id",value:V.id})]}),U("div",{className:"space-y-2",children:[O(W,{className:"ml-1",htmlFor:"edge-source",children:"Source"}),O(ae,{disabled:!0,id:"edge-source",value:V.source})]}),U("div",{className:"space-y-2",children:[O(W,{className:"ml-1",htmlFor:"edge-target",children:"Target"}),O(ae,{disabled:!0,id:"edge-target",value:V.target})]}),i&&O("div",{className:"flex items-center gap-2 pt-4",children:U(R,{className:"text-muted-foreground",onClick:()=>A(!0),size:"sm",variant:"ghost",children:[O(jr,{className:"mr-2 size-4"}),"Delete"]})})]})]}),O(Go,{onOpenChange:A,open:I,children:U(Ho,{children:[U(_o,{children:[O(Uo,{children:"Delete Edge"}),O(Ko,{children:"Are you sure you want to delete this connection? This action cannot be undone."})]}),U($o,{children:[O(qo,{children:"Cancel"}),O(jo,{onClick:de,children:"Delete"})]})]})})]}):P?U(co,{children:[U(ha,{className:"size-full","data-testid":"properties-panel",defaultValue:"properties",onValueChange:L,value:le,children:[U(ba,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(vo,{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(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}):null,i&&O(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),U(ho,{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(Gr,{disabled:r,isNewlyCreated:P?.id===w,onSelectAction:ee=>{He("actionType",ee),P?.id===w&&k(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(W,{className:"ml-1",htmlFor:"node-id",children:"Node ID"}),O(ae,{readOnly:!0,id:"node-id",value:P?.id||""})]}),P.data.type==="trigger"&&O(Hr,{config:P.data.config||{},disabled:r||!i,onUpdateConfig:He,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(Fr,{config:P.data.config||{},disabled:r||!i,isOwner:i,onUpdateConfig:He}):null,P.data.type!=="action"||P.data.config?.actionType?U(co,{children:[U("div",{className:"space-y-2",children:[O(W,{className:"ml-1",htmlFor:"label",children:"Label"}),O(ae,{disabled:r||!i,id:"label",onChange:ee=>xe(ee.target.value),value:P.data.label})]}),U("div",{className:"space-y-2",children:[O(W,{className:"ml-1",htmlFor:"description",children:"Description"}),O(ae,{disabled:r||!i,id:"description",onChange:ee=>qe(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(R,{className:"text-muted-foreground",onClick:te,size:"sm",variant:"ghost",children:P.data.enabled===!1?U(co,{children:[O(Sp,{className:"mr-2 size-4"}),"Disabled"]}):U(co,{children:[O(Ap,{className:"mr-2 size-4"}),"Enabled"]})}),U(R,{className:"text-muted-foreground",onClick:()=>T(!0),size:"sm",variant:"ghost",children:[O(jr,{className:"mr-2 size-4"}),"Delete"]})]})]})]}),O(ho,{className:"flex flex-col overflow-hidden data-[state=inactive]:hidden",forceMount:!0,value:"code",children:(()=>{let ee=P.data.config?.triggerType,ve="",Q="typescript";return P.data.type==="trigger"?ee==="Schedule"?(ve="vercel.json",Q="json"):ee==="Webhook"&&(ve=`app/api${P.data.config?.webhookPath||"/webhook"}/route.ts`,Q="typescript"):ve=`steps/${P.data.config?.actionType?.toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"")||"action"}-step.ts`,U(co,{children:[ve&&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(kl,{className:"size-3.5 text-muted-foreground"}),O("code",{className:"text-muted-foreground text-xs",children:ve})]}),U(R,{className:"text-muted-foreground",onClick:b,size:"sm",variant:"ghost",children:[O(Nl,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(ft,{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:sn(P)})})]})})()}),i&&U(ho,{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(R,{className:"text-muted-foreground",disabled:S,onClick:St,size:"sm",variant:"ghost",children:[O(Cl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(R,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(Ja,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(dn,{isActive:le==="runs",onRefreshRef:F})})]})]}),O(Go,{onOpenChange:m,open:h,children:U(Ho,{children:[U(_o,{children:[O(Uo,{children:"Delete All Runs"}),O(Ko,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U($o,{children:[O(qo,{children:"Cancel"}),O(jo,{onClick:B,children:"Delete"})]})]})}),O(Go,{onOpenChange:T,open:f,children:U(Ho,{children:[U(_o,{children:[O(Uo,{children:"Delete Step"}),O(Ko,{children:"Are you sure you want to delete this node? This action cannot be undone."})]}),U($o,{children:[O(qo,{children:"Cancel"}),O(jo,{onClick:G,children:"Delete"})]})]})})]}):U(co,{children:[U(ha,{className:"size-full",defaultValue:"properties",onValueChange:L,value:le,children:[U(ba,{className:"h-14 w-full shrink-0 rounded-none border-b bg-transparent px-4 py-2.5",children:[O(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"properties",children:"Properties"}),O(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"code",children:"Code"}),i&&O(vo,{className:"bg-transparent text-muted-foreground data-[state=active]:text-foreground data-[state=active]:shadow-none",value:"runs",children:"Runs"})]}),O(ho,{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(W,{className:"ml-1",htmlFor:"workflow-name",children:"Workflow Name"}),O(ae,{disabled:!i,id:"workflow-name",onChange:ee=>qt(ee.target.value),value:a})]}),U("div",{className:"space-y-2",children:[O(W,{className:"ml-1",htmlFor:"workflow-id",children:"Workflow ID"}),O(ae,{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(R,{className:"text-muted-foreground",onClick:()=>g(!0),size:"sm",variant:"ghost",children:[O(Ja,{className:"mr-2 size-4"}),"Clear"]}),U(R,{className:"text-muted-foreground",onClick:()=>C(!0),size:"sm",variant:"ghost",children:[O(jr,{className:"mr-2 size-4"}),"Delete"]})]})]})}),i&&U(ho,{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(R,{className:"text-muted-foreground",disabled:S,onClick:St,size:"sm",variant:"ghost",children:[O(Cl,{className:`mr-2 size-4 ${S?"animate-spin":""}`}),"Refresh"]}),U(R,{className:"text-muted-foreground",onClick:()=>m(!0),size:"sm",variant:"ghost",children:[O(Ja,{className:"mr-2 size-4"}),"Clear All"]})]}),O("div",{className:"flex-1 space-y-4 overflow-y-auto p-4",children:O(dn,{isActive:le==="runs",onRefreshRef:F})})]}),U(ho,{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(kl,{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(R,{className:"text-muted-foreground",onClick:D,size:"sm",variant:"ghost",children:[O(Nl,{className:"mr-2 size-4"}),"Copy"]})]}),O("div",{className:"flex-1 overflow-hidden",children:O(ft,{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(Go,{onOpenChange:m,open:h,children:U(Ho,{children:[U(_o,{children:[O(Uo,{children:"Delete All Runs"}),O(Ko,{children:"Are you sure you want to delete all workflow runs? This action cannot be undone."})]}),U($o,{children:[O(qo,{children:"Cancel"}),O(jo,{onClick:B,children:"Delete"})]})]})})]})},Xa=()=>O("div",{className:"hidden size-full flex-col bg-background md:flex",children:O(Op,{})});import{jsx as Tt,jsxs as qr}from"react/jsx-runtime";var es=({workflowId:e})=>{let t=Wp(),o=zt(),[n,r]=Bt(wt),[s,a]=Bt(yr),[l]=Bt(oe),[i]=Bt(ue),[d]=Bt($e),[c]=Bt(Qt),u=kt(oe),p=kt(ue),g=kt($e),C=kt(pt),v=kt(Zt),y=kt(tt),[w,k]=Bt(ei),f=kt(pr),T=kt(lr),I=kt(dr),[A,h]=Bt(cr),[m,S]=Bt(js),X=kt(sr),[le,L]=Bt(Xt),F=kt(mt),_=kt(ar),P=Lp(Pt),[V,Y]=Qa(30),[M,K]=Qa(A),[N,z]=Qa(!1),b=Po(!1),D=Po(!1);Ct(()=>{if(D.current)return;D.current=!0;let E=document.cookie.split("; ").find(J=>J.startsWith("sidebar-width="));if(E){let J=Number.parseFloat(E.split("=")[1]);!Number.isNaN(J)&&J>=20&&J<=50&&Y(J)}let $=document.cookie.split("; ").find(J=>J.startsWith("sidebar-collapsed="));$&&S($.split("=")[1]==="true")},[S]);let G=Po(!1);Ct(()=>{if(!G.current){G.current=!0;return}document.cookie=`sidebar-width=${V}; path=/; max-age=31536000`},[V]),Ct(()=>{D.current&&(document.cookie=`sidebar-collapsed=${m}; path=/; max-age=31536000`)},[m]),Ct(()=>{let E=sessionStorage.getItem("animate-sidebar")==="true";if(sessionStorage.removeItem("animate-sidebar"),A||!E){K(!0),h(!0);return}I(!0);let $=setTimeout(()=>{K(!0),h(!0)},100),J=setTimeout(()=>I(!1),400);return()=>{clearTimeout($),clearTimeout(J),I(!1)}},[A,h,I]),Ct(()=>{let E=$=>{($.metaKey||$.ctrlKey)&&$.key==="b"&&($.preventDefault(),I(!0),S(J=>!J),setTimeout(()=>I(!1),350))};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[I,S]),Ct(()=>(T(!o&&M&&!m?`${V}%`:null),()=>{T(null)}),[o,T,V,M,m]);let te=uo(E=>{E.preventDefault(),b.current=!0,z(!0);let $=ce=>{if(!b.current)return;let Ee=(window.innerWidth-ce.clientX)/window.innerWidth*100;Y(Math.min(50,Math.max(20,Ee)))},J=()=>{b.current=!1,z(!1),document.removeEventListener("mousemove",$),document.removeEventListener("mouseup",J),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",$),document.addEventListener("mouseup",J),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]),de=Po(null),B=Po(null),xe=Po(l);Ct(()=>{xe.current=l},[l]);let qe=uo(async E=>{r(!0),g(e),C("AI Generated Workflow");try{let $=await j.ai.generate(E),J=($.nodes||[]).map(ce=>({...ce,selected:!1}));u(J),p($.edges||[]),C($.name||"AI Generated Workflow"),await j.workflow.update(e,{name:$.name,description:$.description,nodes:$.nodes,edges:$.edges})}catch($){console.error("Failed to generate workflow:",$),Za.error("Failed to generate workflow")}finally{r(!1)}},[e,r,g,C,u,p]),Ye=uo(async()=>{try{let E=await j.workflow.getById(e);if(!E){k(!0);return}let $=E.nodes.map(J=>({...J,selected:!1,data:{...J.data,status:"idle"}}));u($),p(E.edges),g(E.id),C(E.name),X(E.visibility??"private"),L(E.isOwner!==!1),y(!1),k(!1)}catch(E){console.error("Failed to load workflow:",E),Za.error("Failed to load workflow")}},[e,u,p,g,C,X,L,y,k]),He=Po(null);Ct(()=>{(async()=>{let $=t?.get("generating")==="true",J=sessionStorage.getItem("ai-prompt"),ce=sessionStorage.getItem("generating-workflow-id");d===e&&l.length>0||($&&J&&ce===e?(sessionStorage.removeItem("ai-prompt"),sessionStorage.removeItem("generating-workflow-id"),await qe(J)):await Ye())})()},[e,t,d,l.length,qe,Ye]),Ct(()=>{if(l.length===0||!d||!le)return;let E=He.current;if(E&&E.workflowId===d&&E.version===P)return;(async()=>{try{let J=await j.integration.getAll();F(J),_(!0);let ce=new Set(J.map(Re=>Re.id)),Ee=l.map(Re=>ai(Re,J,ce)).filter(Re=>Re!==null);for(let Re of Ee){let Cn=l.find(ma=>ma.id===Re.nodeId);Cn&&v({id:Re.nodeId,data:{config:{...Cn.data.config,integrationId:Re.newIntegrationId}}})}He.current={workflowId:d,version:P},Ee.length>0&&y(!0)}catch(J){console.error("Failed to auto-fix integrations:",J)}})()},[l,d,P,le,v,F,_,y]);let qt=uo(async()=>{if(!(!d||n)){a(!0);try{await j.workflow.update(d,{nodes:l,edges:i}),y(!1)}catch(E){console.error("Failed to save workflow:",E),Za.error("Failed to save workflow")}finally{a(!1)}}},[d,l,i,n,a,y]),St=uo(E=>E.tagName==="INPUT"||E.tagName==="TEXTAREA",[]),ee=uo(E=>E.closest(".monaco-editor")!==null,[]),ve=uo(E=>(E.metaKey||E.ctrlKey)&&E.key==="s"?(E.preventDefault(),E.stopPropagation(),qt(),!0):!1,[qt]),Q=uo((E,$)=>(E.metaKey||E.ctrlKey)&&E.key==="Enter"?(St($)||ee($)||(E.preventDefault(),E.stopPropagation(),f(!0)),!0):!1,[f,St,ee]);return Ct(()=>{let E=$=>{let J=$.target;ve($)||Q($,J)};return document.addEventListener("keydown",E,!0),()=>document.removeEventListener("keydown",E,!0)},[ve,Q]),Ct(()=>()=>{de.current&&clearInterval(de.current),B.current&&clearInterval(B.current)},[]),Ct(()=>{if(B.current&&(clearInterval(B.current),B.current=null),!c){for(let $ of xe.current)v({id:$.id,data:{status:"idle"}});return}let E=async()=>{try{let $=await j.workflow.getExecutionStatus(c);for(let J of $.nodeStatuses)v({id:J.nodeId,data:{status:J.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,v]),qr("div",{className:"flex h-dvh w-full flex-col overflow-hidden",children:[w&&Tt("div",{className:"pointer-events-auto absolute inset-0 z-20 flex items-center justify-center",children:qr("div",{className:"rounded-lg border bg-background p-8 text-center shadow-lg",children:[Tt("h1",{className:"mb-2 font-semibold text-2xl",children:"Workflow Not Found"}),Tt("p",{className:"mb-6 text-muted-foreground",children:"The workflow you're looking for doesn't exist or has been deleted."}),Tt(R,{asChild:!0,children:Tt(zp,{href:"/",children:"New Workflow"})})]})}),!o&&m&&Tt("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:Tt(Mp,{className:"size-4"})}),!o&&qr("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:M&&!m?"translateX(0)":"translateX(100%)"},children:[qr("div",{"aria-orientation":"vertical","aria-valuenow":V,className:"group absolute inset-y-0 left-0 z-10 w-3 cursor-col-resize",onMouseDown:te,role:"separator",tabIndex:0,children:[Tt("div",{className:"absolute inset-y-0 left-0 w-1 bg-transparent transition-colors group-hover:bg-blue-500 group-active:bg-blue-600"}),!(N||m)&&Tt("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:Tt(Fp,{className:"size-4"})})]}),Tt(Xa,{})]}),o&&Tt(Xa,{})]})};import{useAtomValue as ts,useSetAtom as Gn}from"jotai";import{nanoid as Gp}from"nanoid";import{useRouter as Hp}from"next/navigation";import{useCallback as Pl,useEffect as Yr,useRef as _p}from"react";import{toast as $p}from"sonner";import{anonymousClient as Bp}from"better-auth/client/plugins";import{createAuthClient as Vp}from"better-auth/react";var Eo=Vp({baseURL:typeof window<"u"?window.location.origin:"http://localhost:3000",plugins:[Bp()]}),{signIn:Xk,signOut:Il,signUp:Qk,useSession:cn}=Eo;function Up(){return{id:Gp(),type:"trigger",position:{x:0,y:0},data:{label:"",description:"",type:"trigger",config:{triggerType:"Manual"},status:"idle"}}}var El=()=>{let e=Hp(),{data:t}=cn(),o=ts(oe),n=ts(ue),r=Gn(oe),s=Gn(ue),a=Gn(pt),l=Gn(cr),i=Gn(ur),d=_p(!1),c=ts(pt);Yr(()=>{l(!1)},[l]),Yr(()=>{document.title=`${c} - AI Workflow Builder`},[c]);let u=Pl(async()=>{t||(await Eo.signIn.anonymous(),await new Promise(g=>setTimeout(g,100)))},[t]),p=Pl(()=>{let g=Up();r([g])},[r]);return Yr(()=>{r([{id:"add-node-placeholder",type:"add",position:{x:0,y:0},data:{label:"",type:"add",onClick:p},draggable:!1,selectable:!1}]),s([]),a("New Workflow"),d.current=!1},[r,s,a,p]),Yr(()=>{(async()=>{let C=o.filter(v=>v.type!=="add");if(!(C.length===0||d.current)){d.current=!0;try{await u();let v=await j.workflow.create({name:"Untitled Workflow",description:"",nodes:C,edges:n});sessionStorage.setItem("animate-sidebar","true"),i(!0),console.log("[Homepage] Navigating to workflow page"),e.replace(`/workflows/${v.id}`)}catch(v){console.error("Failed to create workflow:",v),$p.error("Failed to create workflow")}}})()},[o,n,e,u,i]),null};import{useRouter as Kp}from"next/navigation";import{useEffect as jp}from"react";var Dl=()=>{let e=Kp();return jp(()=>{(async()=>{try{let n=(await j.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 un}from"react/jsx-runtime";var Jp=()=>{let t=Yp().slug;return!t||t.length===0?un(El,{}):t[0]==="auth"&&t.length===2?un("main",{className:"flex items-center justify-center min-h-screen",children:un(qp,{path:t[1]})}):t[0]==="workflows"&&t.length===1?un(Dl,{}):t[0]==="workflows"&&t.length===2?un("div",{className:"pointer-events-none relative z-10",children:un(es,{workflowId:t[1]})}):null};import"virtual:workflow-builder-plugins";import{ReactFlowProvider as cv}from"@xyflow/react";import{Provider as uv}from"jotai";import*as hc from"react";import{AnimatePresence as Zp,LayoutGroup as Ll,motion as pn,useReducedMotion as Ml}from"motion/react";import{useCallback as _n,useLayoutEffect as $n,useRef as mo,useState as Fl}from"react";import{Drawer as Hn}from"vaul";import{Dialog as mn}from"radix-ui";import{XIcon as Xp}from"lucide-react";import{jsx as Do,jsxs as os}from"react/jsx-runtime";function Jr({...e}){return Do(mn.Root,{"data-slot":"dialog",...e})}function ns({...e}){return Do(mn.Portal,{"data-slot":"dialog-portal",...e})}function Qp({className:e,...t}){return Do(mn.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 Rl({className:e,children:t,showCloseButton:o=!0,...n}){return os(ns,{"data-slot":"dialog-portal",children:[Do(Qp,{}),os(mn.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&&os(mn.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:[Do(Xp,{}),Do("span",{className:"sr-only",children:"Close"})]})]})]})}function Ol({className:e,...t}){return Do(mn.Title,{"data-slot":"dialog-title",className:x("text-lg leading-none font-semibold",e),...t})}import{jsx as Le,jsxs as as}from"react/jsx-runtime";var rs={type:"spring",stiffness:400,damping:35,mass:.8},ef={type:"spring",stiffness:350,damping:30,mass:.8},tf={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 zl(e,t){return e?"0%":t?"-35%":"100%"}function Wl(e){let t=mo(e),o=mo(1);return e>t.current?o.current=1:e<t.current&&(o.current=-1),$n(()=>{t.current=e},[e]),o.current}function of(){let{stack:e,closeAll:t,pop:o}=ne(),n=Ml(),[r,s]=Fl(0),a=mo(null),l=mo(!1),i=mo(e),d=Wl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,p=u.length-1;console.log("[DesktopOverlay]",{isOpen:c,stackLength:e.length,frozenStackLength:i.current.length,renderStackLength:u.length}),$n(()=>{let f=c&&!l.current;if(l.current=c,f&&s(0),a.current){let T=a.current.offsetHeight;T>0&&s(T)}},[e,c]);let g=e[e.length-1],C=n?{duration:.01}:rs,v=d===1,y=_n(()=>{g?.options.closeOnBackdropClick!==!1&&t()},[g?.options.closeOnBackdropClick,t]),w=_n(f=>{f.key==="Escape"&&g?.options.closeOnEscape!==!1&&o()},[g?.options.closeOnEscape,o]);$n(()=>{if(c)return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[c,w]);let k=_n(()=>{console.log("[DesktopOverlay] handleExitComplete called"),i.current=[]},[]);return console.log("[DesktopOverlay] Rendering, isOpen:",c),!c&&i.current.length===0?null:Le(Zp,{onExitComplete:k,children:c&&Le(Jr,{modal:!1,open:!0,children:as(ns,{forceMount:!0,children:[Le(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}}),Le(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:tf,children:Le(Ll,{children:Le(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:rs,children:Le("div",{className:"relative",ref:a,children:u.map((f,T)=>{let I=T===p,A=T<p,m=I&&v&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Le(pn.div,{animate:{x:zl(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:C,children:Le(f.component,{overlayId:f.id,...f.props})},f.id)})})})})})]})})})}function nf(){let{stack:e,closeAll:t,pop:o}=ne(),n=Ml(),[r,s]=Fl(0),a=mo(null),l=mo(!1),i=mo(e),d=Wl(e.length),c=e.length>0;c&&(i.current=e);let u=i.current,p=u.length-1;$n(()=>{let f=c&&!l.current;if(l.current=c,f&&s(0),a.current){let T=a.current.offsetHeight;T>0&&s(T)}},[e,c]);let g=e[e.length-1],C=u[p],v=n?{duration:.01}:rs,y=d===1,w=_n(f=>{f.key==="Escape"&&g?.options.closeOnEscape!==!1&&o()},[g?.options.closeOnEscape,o]);$n(()=>{if(c)return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[c,w]);let k=_n(()=>{c||(i.current=[])},[c]);return Le(Hn.Root,{onAnimationEnd:k,onOpenChange:f=>{f||t()},open:c,children:as(Hn.Portal,{children:[Le(Hn.Overlay,{className:"fixed inset-0 z-50 bg-black/60"}),as(Hn.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:[Le(Hn.Title,{className:"sr-only",children:C?.options.title||"Dialog"}),Le("div",{className:"mx-auto mt-3 h-1.5 w-12 shrink-0 rounded-full bg-muted-foreground/20"}),Le(Ll,{children:Le(pn.div,{className:"relative flex-1 overflow-hidden",layout:c,style:{minHeight:r>0?r:"auto"},transition:ef,children:Le("div",{className:"relative",ref:a,children:u.map((f,T)=>{let I=T===p,A=T<p,m=I&&y&&u.length>1?{x:"100%",scale:1,opacity:1}:!1;return Le(pn.div,{animate:{x:zl(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:v,children:Le(f.component,{overlayId:f.id,...f.props})},f.id)})})})}),Le("div",{className:"h-safe-area-inset-bottom"})]})]})})}function Bl(){return zt()?Le(nf,{}):Le(of,{})}import{useAtom as rf}from"jotai";import{useEffect as af,useRef as Vl}from"react";import{atom as _t}from"jotai";var je=_t([]),MC=_t(e=>e(je).length>0),FC=_t(e=>e(je).length);function ss(){return`overlay-${Date.now()}-${Math.random().toString(36).slice(2,9)}`}var zC=_t(null,(e,t,o)=>{let n=ss(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[r]),n}),WC=_t(null,(e,t,o)=>{let n=ss(),r={id:n,component:o.component,props:o.props??{},options:o.options??{}};return t(je,[...e(je),r]),n}),BC=_t(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))}),VC=_t(null,(e,t,o)=>{let n=e(je),r=ss(),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}),GC=_t(null,(e,t)=>{let o=e(je);for(let n of o)n.options.onClose?.();t(je,[])}),HC=_t(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 Gl(){let{stack:e}=ne(),[t,o]=rf(je),n=Vl(!1),r=Vl(!1);return af(()=>{if(n.current){n.current=!1;return}r.current=!0,o(e)},[e,o]),null}import{Fragment as sf,jsx as Hl,jsxs as lf}from"react/jsx-runtime";var _l=()=>lf(sf,{children:[Hl(Bl,{}),Hl(Gl,{})]});import{CircleCheckIcon as df,InfoIcon as cf,Loader2Icon as uf,OctagonXIcon as mf,TriangleAlertIcon as pf}from"lucide-react";import{useTheme as ff}from"next-themes";import{Toaster as gf}from"sonner";import{jsx as fn}from"react/jsx-runtime";var $l=({...e})=>{let{theme:t="system"}=ff();return fn(gf,{theme:t,className:"toaster group",icons:{success:fn(df,{className:"size-4"}),info:fn(cf,{className:"size-4"}),warning:fn(pf,{className:"size-4"}),error:fn(mf,{className:"size-4"}),loading:fn(uf,{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 nv}from"next/navigation";import{ConnectionMode as Yy,MiniMap as Jy,useReactFlow as Xy}from"@xyflow/react";import{useAtom as tr,useAtomValue as Ds,useSetAtom as go}from"jotai";import{useCallback as bt,useEffect as ua,useMemo as Qy,useRef as Lo,useState as cc}from"react";import{Background as yf,ReactFlow as vf}from"@xyflow/react";import"@xyflow/react/dist/style.css";import{jsx as hf,jsxs as bf}from"react/jsx-runtime";var Ul=({children:e,...t})=>bf(vf,{deleteKeyCode:["Backspace","Delete"],fitView:!0,panActivationKeyCode:null,selectionOnDrag:!1,zoomOnDoubleClick:!1,zoomOnPinch:!0,...t,children:[hf(yf,{bgColor:"var(--sidebar)",color:"var(--border)",gap:24,size:2}),e]});import{jsx as Kl,jsxs as wf}from"react/jsx-runtime";var jl=({fromX:e,fromY:t,toX:o,toY:n})=>wf("g",{children:[Kl("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}),Kl("circle",{cx:o,cy:n,fill:"#fff",r:3,stroke:"var(--color-ring)",strokeWidth:1})]});import{useReactFlow as Cf}from"@xyflow/react";import{useAtom as Tf}from"jotai";import{MapPin as Af,MapPinXInside as Sf,Maximize2 as If,ZoomIn as Pf,ZoomOut as Ef}from"lucide-react";import{cva as xf}from"class-variance-authority";import{Slot as m0}from"radix-ui";import{jsx as kf}from"react/jsx-runtime";var Nf=xf("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 Vt({className:e,orientation:t,...o}){return kf("div",{role:"group","data-slot":"button-group","data-orientation":t,className:x(Nf({orientation:t}),e),...o})}import{jsx as $t,jsxs as Df}from"react/jsx-runtime";var ql=()=>{let{zoomIn:e,zoomOut:t,fitView:o}=Cf(),[n,r]=Tf(ir);return Df(Vt,{orientation:"vertical",children:[$t(R,{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:$t(Pf,{className:"size-4"})}),$t(R,{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:$t(Ef,{className:"size-4"})}),$t(R,{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:$t(If,{className:"size-4"})}),$t(R,{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?$t(Af,{className:"size-4"}):$t(Sf,{className:"size-4"})})]})};import{useReactFlow as zf}from"@xyflow/react";import{useAtom as gn,useAtomValue as Wf}from"jotai";import{ArrowUp as Bf}from"lucide-react";import{useCallback as Vf,useEffect as Gf,useRef as Jl,useState as is}from"react";import{toast as ls}from"sonner";import{motion as Rf}from"motion/react";import{memo as Of,useMemo as Lf}from"react";import{jsx as Ff}from"react/jsx-runtime";var Mf=({children:e,as:t="p",className:o,duration:n=2,spread:r=2})=>{let s=Rf.create(t),a=Lf(()=>(e?.length??0)*r,[e,r]);return Ff(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})},Yl=Of(Mf);import{Fragment as Hf,jsx as Ut,jsxs as ds}from"react/jsx-runtime";function Xl({workflowId:e,onWorkflowCreated:t}){let[o,n]=gn(wt),[r,s]=is(""),[a,l]=is(!1),[i,d]=is(!1),c=Jl(null),u=Jl(null),p=Wf(oe),[g,C]=gn(ue),[v,y]=gn(oe),[w,k]=gn($e),[f,T]=gn(pt),[I,A]=gn(be),{fitView:h}=zf(),m=p.filter(F=>F.type!=="add"),S=m.length>0;Gf(()=>{let F=_=>{(_.metaKey||_.ctrlKey)&&_.key==="k"&&(_.preventDefault(),c.current?.focus())};return window.addEventListener("keydown",F),()=>{window.removeEventListener("keydown",F)}},[]);let X=()=>{l(!0),d(!0)},le=F=>{u.current?.contains(F.relatedTarget)||(d(!1),r.trim()||l(!1))},L=Vf(async F=>{if(F.preventDefault(),!(!r.trim()||o)){n(!0);try{let _=S?{nodes:m,edges:g,name:f}: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 j.ai.generateStream(r,M=>{let K=(M.edges||[]).map(b=>({...b,type:"animated"})),N=(M.nodes||[]).filter(b=>b.data?.type==="trigger"),z=K;if(N.length>1){let b=N[0],D=(M.nodes||[]).filter(te=>te.data?.type!=="trigger");M.nodes=[b,...D];let G=N.slice(1).map(te=>te.id);z=K.filter(te=>!G.includes(te.source)&&!G.includes(te.target))}y(M.nodes||[]),C(z),M.name&&T(M.name),setTimeout(()=>{h({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(M=>({...M,type:"animated"}));console.log("[AI Prompt] Validating nodes:",P.nodes);let Y=(P.nodes||[]).filter(M=>{let K=M.data?.type,N=M.data?.config||{};return console.log(`[AI Prompt] Checking node ${M.id}:`,{type:K,config:N,hasActionType:!!N.actionType,hasTriggerType:!!N.triggerType}),K==="trigger"?!N.triggerType:K==="action"?!N.actionType:!1});if(Y.length>0)throw console.error("[AI Prompt] AI generated incomplete nodes:",Y),console.error("[AI Prompt] Full workflow data:",JSON.stringify(P,null,2)),new Error(`Cannot create workflow: The AI tried to create ${Y.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){k(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"),ls.success("Generated workflow"));let M=P.nodes?.find(K=>K.selected);M&&A(M.id),await j.workflow.update(e,{name:P.name,description:P.description,nodes:P.nodes,edges:V})}else{let M=await j.workflow.create({name:P.name||"AI Generated Workflow",description:P.description||"",nodes:P.nodes||[],edges:V});k(M.id),ls.success("Created workflow"),t&&t(M.id)}s(""),l(!1),d(!1),c.current?.blur()}catch(_){console.error("Failed to generate workflow:",_),ls.error("Failed to generate workflow")}finally{n(!1)}}},[r,o,e,S,p,g,n,k,y,C,T,A,t,h]);return Ut(Hf,{children:Ut("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:ds("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:F=>{(F.target===F.currentTarget||F.target.tagName!=="BUTTON")&&c.current?.focus()},onMouseDown:F=>{F.target===F.currentTarget&&F.preventDefault()},onSubmit:L,role:"search",children:[o&&r?Ut(Yl,{className:"flex-1 text-sm whitespace-pre-wrap",duration:2,children:r}):Ut("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:F=>{s(F.target.value),F.target.style.height="auto",F.target.style.height=`${F.target.scrollHeight}px`},onFocus:X,onKeyDown:F=>{F.key==="Enter"&&!F.shiftKey?(F.preventDefault(),L(F)):F.key==="Escape"&&(F.preventDefault(),s(""),l(!1),d(!1),c.current?.blur())},placeholder:i?"Describe your workflow with natural language...":"Ask AI...",ref:c,rows:1,value:r}),Ut("div",{className:"sr-only",children:o?"Generating workflow, please wait...":""}),ds("div",{className:"relative size-8 shrink-0 self-end",children:[Ut(R,{"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:ds("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:[Ut("span",{className:"text-xs",children:"\u2318"}),"K"]})}),Ut(R,{"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:Ut(Bf,{"aria-hidden":"true",className:"size-4"})})]})]})})})}import{useReactFlow as Wg}from"@xyflow/react";import{useAtom as Ze,useAtomValue as Wd,useSetAtom as Gt}from"jotai";import{Check as sa,ChevronDown as Bg,Copy as Vg,Download as Gg,Globe as Bd,Loader2 as la,Lock as Vd,Play as Hg,Plus as Gd,Redo2 as Hd,Save as _g,Settings2 as $g,Trash2 as Ug,Undo2 as _d}from"lucide-react";import{nanoid as Kg}from"nanoid";import{useRouter as jg}from"next/navigation";import{useEffect as Ts,useRef as qg,useState as Cs}from"react";import{toast as it}from"sonner";import{Panel as _f}from"@xyflow/react";import{jsx as $f}from"react/jsx-runtime";var Xr=({className:e,...t})=>$f(_f,{className:x("m-4 rounded-md border bg-card p-1",e),...t});var cs="https://vercel.new/workflow-builder",$0=`[](${cs})`;import{jsx as Un,jsxs as Ql}from"react/jsx-runtime";function Zl(){return Un(R,{asChild:!0,className:"h-9 gap-1.5 border px-2 sm:px-3",size:"sm",variant:"secondary",children:Ql("a",{href:cs,rel:"noopener noreferrer",target:"_blank",children:[Ql("svg",{"aria-label":"Vercel logomark",className:"size-3.5",fill:"currentColor",viewBox:"0 0 76 76",children:[Un("title",{children:"Vercel logomark"}),Un("path",{d:"m38 0 38 66H0z"})]}),Un("span",{className:"text-sm sm:hidden",children:"Deploy"}),Un("span",{className:"hidden text-sm sm:inline",children:"Deploy Your Own"})]})})}import{jsx as ed}from"react/jsx-runtime";function td({className:e}){return ed("svg",{"aria-label":"GitHub",className:e,fill:"currentColor",role:"img",viewBox:"0 0 24 24",children:ed("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 od(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 Uf,useContext as Kf}from"react";import{jsx as tT}from"react/jsx-runtime";var jf=Uf(null);function nd(){return Kf(jf)}import{jsx as rd,jsxs as ad}from"react/jsx-runtime";var qf="https://github.com/vercel-labs/workflow-builder-template";function sd(){let e=nd();return rd(R,{asChild:!0,className:"h-9 gap-1.5 px-2 sm:px-3",size:"sm",variant:"ghost",children:ad("a",{className:"flex items-center",href:qf,rel:"noopener noreferrer",target:"_blank",children:[rd(td,{className:"size-4.5"}),e!==null&&ad("span",{className:"hidden text-sm sm:inline",children:[od(e)," stars"]})]})})}import{useAtom as Kt,useAtomValue as id,useSetAtom as Kn}from"jotai";import{Code as ld,Copy as dd,Eraser as us,Eye as Yf,EyeOff as Jf,FileCode as cd,Play as ud,RefreshCw as md,Settings2 as pd,Trash2 as ms}from"lucide-react";import{useCallback as yn,useEffect as Xf,useRef as Qf,useState as Zf}from"react";import{toast as vn}from"sonner";import{Fragment as ps,jsx as Z,jsxs as ie}from"react/jsx-runtime";var eg={"Database Query":"database"},tg=/[^a-zA-Z0-9\s]/g,og=/\s+/;function ng(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 Qr({overlayId:e}){let{push:t,closeAll:o}=ne(),[n]=Kt(be),[r]=Kt(_e),[s]=Kt(oe),[a]=Kt(ue),[l]=Kt(wt),[i]=Kt($e),[d,c]=Kt(pt),u=id(Xt),p=Kn(Zt),g=Kn(eo),C=Kn(to),v=Kn(vr),y=Kn(gr),[w,k]=Kt(Jt),[f,T]=Kt(Ft),[I,A]=Zf(!1),h=Qf(null),m=s.find(B=>B.id===n),S=a.find(B=>B.id===r),X=id(mt);Xf(()=>{if(!(m&&u))return;let B=m.data.config?.actionType,xe=m.data.config?.integrationId;if(!(B&&xe))return;let Ye=pe(B)?.integration||eg[B];if(!Ye)return;let He=X.filter(St=>St.type===Ye);!He.some(St=>St.id===xe)&&He.length>0&&p({id:m.id,data:{config:{...m.data.config,integrationId:He[0].id}}})},[m,X,u,p]);let le=yn((B,xe)=>{m&&p({id:m.id,data:{config:{...m.data.config,[B]:xe}}})},[m,p]),L=yn(B=>{m&&p({id:m.id,data:{label:B}})},[m,p]),F=yn(B=>{m&&p({id:m.id,data:{description:B}})},[m,p]),_=yn(()=>{m&&p({id:m.id,data:{enabled:m.data.enabled===!1}})},[m,p]),P=yn(()=>{t(Oe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{m&&(g(m.id),o())}})},[m,g,o,t]),V=yn(()=>{m&&(navigator.clipboard.writeText(sn(m,i)),vn.success("Code copied to clipboard"))},[m]),Y=async()=>{h.current&&(A(!0),await h.current(),A(!1))},M=()=>{t(Oe,{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 j.workflow.deleteExecutions(i),v(),h.current&&await h.current(),vn.success("All runs deleted")}catch(B){console.error("Failed to delete runs:",B),vn.error("Failed to delete runs")}}})},K=m&&(m.data.type!=="trigger"||m.data.config?.triggerType!=="Manual")&&m.data.config?.actionType!=="Condition",N=()=>{if(!m)switch(f==="properties"||f==="code"||f==="runs"&&u?f:"properties"){case"properties":return"Workflow";case"code":return"Code";case"runs":return"Runs";default:return"Workflow"}switch(f){case"properties":return"Properties";case"code":return"Code";case"runs":return"Runs";default:return"Properties"}},z=async B=>{if(c(B),i)try{await j.workflow.update(i,{name:B})}catch(xe){console.error("Failed to update workflow name:",xe)}},b=()=>{t(Oe,{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()}})},D=()=>{t(Oe,{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(i)try{await j.workflow.delete(i),o(),vn.success("Workflow deleted successfully"),window.location.href="/"}catch(B){console.error("Failed to delete workflow:",B),vn.error("Failed to delete workflow. Please try again.")}}})},G=(()=>{let xe=`${d.replace(tg,"").split(og).map((Ye,He)=>He===0?Ye.toLowerCase():Ye.charAt(0).toUpperCase()+Ye.slice(1).toLowerCase()).join("")}Workflow`,{code:qe}=or(s,a,{functionName:xe});return qe})(),te=()=>{navigator.clipboard.writeText(G),vn.success("Code copied to clipboard")},de=()=>{r&&t(Oe,{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(S&&!m)return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{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(W,{htmlFor:"edge-id",children:"Connection ID"}),Z(ae,{disabled:!0,id:"edge-id",value:S.id})]}),ie("div",{className:"space-y-2",children:[Z(W,{htmlFor:"edge-source",children:"Source"}),Z(ae,{disabled:!0,id:"edge-source",value:S.source})]}),ie("div",{className:"space-y-2",children:[Z(W,{htmlFor:"edge-target",children:"Target"}),Z(ae,{disabled:!0,id:"edge-target",value:S.target})]}),u&&Z("div",{className:"pt-2",children:ie(R,{onClick:de,variant:"ghost",children:[Z(ms,{className:"mr-2 size-4"}),"Delete Connection"]})})]})]});if(!m){let B=f==="properties"||f==="code"||f==="runs"&&u?f:"properties";return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:N()}),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(W,{htmlFor:"workflow-name",children:"Workflow Name"}),Z(ae,{disabled:!u,id:"workflow-name",onChange:xe=>z(xe.target.value),value:d})]}),ie("div",{className:"space-y-2",children:[Z(W,{htmlFor:"workflow-id",children:"Workflow ID"}),Z(ae,{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(R,{onClick:b,variant:"ghost",children:[Z(us,{className:"mr-2 size-4"}),"Clear"]}),ie(R,{onClick:D,variant:"ghost",children:[Z(ms,{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(cd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:"workflow.ts"})]}),ie(R,{className:"h-7 text-xs",onClick:te,size:"sm",variant:"ghost",children:[Z(dd,{className:"mr-1 size-3"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(ft,{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(R,{className:"text-muted-foreground",disabled:I,onClick:Y,size:"icon",variant:"ghost",children:Z(md,{className:`size-4 ${I?"animate-spin":""}`})}),Z(R,{className:"text-muted-foreground",onClick:M,size:"icon",variant:"ghost",children:Z(us,{className:"size-4"})})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(dn,{isActive:B==="runs",onRefreshRef:h})})]})]}),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:()=>T("properties"),type:"button",children:[Z(pd,{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:()=>T("code"),type:"button",children:[Z(ld,{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:()=>T("runs"),type:"button",children:[Z(ud,{className:"size-5"}),"Runs"]})]})]})}return ie("div",{className:"flex h-full max-h-[80vh] flex-col",children:[Z(en,{overlayId:e,title:N()}),ie("div",{className:"flex-1 overflow-y-auto",children:[f==="properties"&&ie("div",{className:"space-y-4 px-6 pt-4 pb-6",children:[m.data.type==="action"&&!m.data.config?.actionType&&u&&Z(Gr,{disabled:l,isNewlyCreated:m?.id===w,onSelectAction:B=>{le("actionType",B),m?.id===w&&k(null)}}),m.data.type==="trigger"&&Z(Hr,{config:m.data.config||{},disabled:l||!u,onUpdateConfig:le,workflowId:i??void 0}),m.data.type==="action"&&m.data.config?.actionType!==void 0&&Z(Fr,{config:m.data.config||{},disabled:l||!u,isOwner:u,onUpdateConfig:le}),(m.data.type!=="action"||m.data.config?.actionType!==void 0)&&ie(ps,{children:[ie("div",{className:"space-y-2",children:[Z(W,{htmlFor:"label",children:"Label"}),Z(ae,{disabled:l||!u,id:"label",onChange:B=>L(B.target.value),value:m.data.label})]}),ie("div",{className:"space-y-2",children:[Z(W,{htmlFor:"description",children:"Description"}),Z(ae,{disabled:l||!u,id:"description",onChange:B=>F(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(R,{className:"text-muted-foreground",onClick:_,size:"sm",variant:"ghost",children:m.data.enabled===!1?ie(ps,{children:[Z(Jf,{className:"mr-2 size-4"}),"Disabled"]}):ie(ps,{children:[Z(Yf,{className:"mr-2 size-4"}),"Enabled"]})}),ie(R,{className:"text-muted-foreground",onClick:P,size:"sm",variant:"ghost",children:[Z(ms,{className:"mr-2 size-4"}),"Delete"]})]})]}),K&&ie("div",{className:`flex flex-col ${f==="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(cd,{className:"size-3.5 text-muted-foreground"}),Z("code",{className:"text-muted-foreground text-xs",children:ng(m)})]}),ie(R,{className:"text-muted-foreground",onClick:V,size:"sm",variant:"ghost",children:[Z(dd,{className:"mr-2 size-4"}),"Copy"]})]}),Z("div",{className:"h-[400px]",children:Z(ft,{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:sn(m,i)})})]}),f==="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(R,{className:"text-muted-foreground",disabled:I,onClick:Y,size:"sm",variant:"ghost",children:[Z(md,{className:`mr-2 size-4 ${I?"animate-spin":""}`}),"Refresh"]}),ie(R,{className:"text-muted-foreground",onClick:M,size:"sm",variant:"ghost",children:[Z(us,{className:"mr-2 size-4"}),"Clear All"]})]}),Z("div",{className:"flex-1 overflow-y-auto p-4",children:Z(dn,{isActive:f==="runs",onRefreshRef:h})})]})]}),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 ${f==="properties"?"text-foreground":"text-muted-foreground"}`,onClick:()=>T("properties"),type:"button",children:[Z(pd,{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 ${f==="code"?"text-foreground":"text-muted-foreground"}`,onClick:()=>T("code"),type:"button",children:[Z(ld,{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 ${f==="runs"?"text-foreground":"text-muted-foreground"}`,onClick:()=>T("runs"),type:"button",children:[Z(ud,{className:"size-5"}),"Runs"]})]})]})}import{Download as sg,FlaskConical as ig}from"lucide-react";import{cva as rg}from"class-variance-authority";import{jsx as fs}from"react/jsx-runtime";var ag=rg("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 fd({className:e,variant:t,...o}){return fs("div",{"data-slot":"alert",role:"alert",className:x(ag({variant:t}),e),...o})}function gd({className:e,...t}){return fs("div",{"data-slot":"alert-title",className:x("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",e),...t})}function yd({className:e,...t}){return fs("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 hn,jsxs as Zr}from"react/jsx-runtime";function vd({overlayId:e,onExport:t,isDownloading:o}){let{closeAll:n}=ne();return Zr(De,{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:[Zr("div",{className:"flex items-center gap-2 text-muted-foreground",children:[hn(sg,{className:"size-5"}),hn("p",{className:"text-sm",children:"Export your workflow as a standalone Next.js project that you can run independently."})]}),hn("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."}),Zr(fd,{className:"mt-4",children:[hn(ig,{className:"size-4"}),hn(gd,{children:"Experimental Feature"}),Zr(yd,{className:"block",children:["This feature is experimental and may have limitations. If you encounter any issues, please"," ",hn("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 lg}from"lucide-react";import{jsx as po,jsxs as ea}from"react/jsx-runtime";function hd({overlayId:e,onConfirm:t}){let{closeAll:o}=ne();return ea(De,{actions:[{label:"Cancel",variant:"outline",onClick:o},{label:"Make Public",onClick:()=>{o(),t()}}],overlayId:e,title:"Make Workflow Public?",children:[ea("div",{className:"flex items-center gap-2 text-muted-foreground",children:[po(lg,{className:"size-5 shrink-0"}),po("p",{className:"text-sm",children:"Making this workflow public means anyone with the link can:"})]}),ea("ul",{className:"mt-3 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[po("li",{children:"View the workflow structure and steps"}),po("li",{children:"See action types and configurations"}),po("li",{children:"Duplicate the workflow to their own account"})]}),po("p",{className:"mt-4 font-medium text-foreground text-sm",children:"The following will remain private:"}),ea("ul",{className:"mt-2 list-inside list-disc space-y-1 text-muted-foreground text-sm",children:[po("li",{children:"Your integration credentials (API keys, tokens)"}),po("li",{children:"Execution logs and run history"})]})]})}import{useAtomValue as bd,useSetAtom as dg}from"jotai";import{AlertTriangle as cg}from"lucide-react";import{jsx as Qe,jsxs as ut}from"react/jsx-runtime";function wd({overlayId:e,issues:t,onGoToStep:o,onRunAnyway:n}){let{push:r,closeAll:s}=ne(),a=dg(Pt),l=zt(),i=bd(Ht),d=bd(xo),{brokenReferences:c,missingRequiredFields:u,missingIntegrations:p}=t,g=c.length+u.length+p.length,C=(k,f)=>{o(k,f),l?r(Qr,{}):s()},v=k=>{r(ro,{type:k,onSuccess:()=>{a(f=>f+1)}})},y=k=>{i?.integrationType===k&&d?.enabled&&d?.isVercelUser&&i?r(i.ConsentOverlay,{onConsent:()=>{a(I=>I+1)},onManualEntry:()=>v(k)}):v(k)};return ut(De,{actions:[{label:"Run Anyway",variant:"outline",onClick:()=>{s(),n()}},{label:"Cancel",onClick:s}],overlayId:e,title:`Workflow Issues (${g})`,children:[ut("div",{className:"flex items-center gap-2 text-orange-500",children:[Qe(cg,{className:"size-5"}),Qe("p",{className:"text-muted-foreground text-sm",children:"This workflow has issues that may cause it to fail."})]}),ut("div",{className:"mt-4 space-y-4",children:[p.length>0&&ut("div",{className:"space-y-1",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Missing Connections"}),p.map(k=>ut("div",{className:"flex items-center gap-3 py-1",children:[Qe(Rt,{className:"size-4 shrink-0",integration:k.integrationType}),ut("p",{className:"min-w-0 flex-1 text-sm",children:[Qe("span",{className:"font-medium",children:k.integrationLabel}),ut("span",{className:"text-muted-foreground",children:[" \u2014 ",k.nodeNames.length>3?`${k.nodeNames.slice(0,3).join(", ")} +${k.nodeNames.length-3} more`:k.nodeNames.join(", ")]})]}),Qe(R,{className:"shrink-0",onClick:()=>y(k.integrationType),size:"sm",variant:"outline",children:"Add"})]},k.integrationType))]}),c.length>0&&ut("div",{className:"space-y-2",children:[Qe("h4",{className:"font-medium text-muted-foreground text-xs uppercase tracking-wide",children:"Broken References"}),c.map(k=>ut("div",{children:[Qe("p",{className:"font-medium text-sm",children:k.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:k.brokenReferences.map((f,T)=>ut("div",{className:"flex items-center gap-3 py-0.5 pl-3",children:[ut("p",{className:"min-w-0 flex-1 text-muted-foreground text-sm",children:[Qe("span",{className:"font-mono",children:f.displayText})," in ",f.fieldLabel]}),Qe(R,{className:"shrink-0",onClick:()=>C(k.nodeId,f.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${k.nodeId}-${f.fieldKey}-${T}`))})]},k.nodeId))]}),u.length>0&&ut("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(k=>ut("div",{children:[Qe("p",{className:"font-medium text-sm",children:k.nodeLabel}),Qe("div",{className:"mt-1 space-y-0.5",children:k.missingFields.map(f=>ut("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:f.fieldLabel}),Qe(R,{className:"shrink-0",onClick:()=>C(k.nodeId,f.fieldKey),size:"sm",variant:"outline",children:"Fix"})]},`${k.nodeId}-${f.fieldKey}`))})]},k.nodeId))]})]})]})}import{jsx as gs,jsxs as ug}from"react/jsx-runtime";function xd({className:e}){return ug("svg",{className:e,fill:"none",height:"16",viewBox:"0 0 305 234",width:"16",xmlns:"http://www.w3.org/2000/svg",children:[gs("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"}),gs("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"}),gs("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 Eg,LogOut as Dg,Moon as Rg,Plug as Og,Settings as Lg,Sun as Mg}from"lucide-react";import{useTheme as Fg}from"next-themes";import zg from"next/link";import{useEffect as Md,useState as Fd}from"react";import{Copy as mg,Key as pg,Trash2 as fg}from"lucide-react";import{useCallback as gg,useEffect as yg,useState as bn}from"react";import{toast as wn}from"sonner";import{jsx as Be,jsxs as At}from"react/jsx-runtime";function vg({overlayId:e,onCreated:t}){let{pop:o}=ne(),[n,r]=bn(""),[s,a]=bn(!1);return At(De,{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 d=await i.json();t(d),wn.success("API key created successfully"),o()}catch(i){console.error("Failed to create API key:",i),wn.error(i instanceof Error?i.message:"Failed to create API key")}finally{a(!1)}},loading:s}],overlayId:e,title:"Create API Key",children:[Be("p",{className:"mb-4 text-muted-foreground text-sm",children:"Create a new API key for webhook authentication"}),At("div",{className:"space-y-2",children:[Be(W,{htmlFor:"key-name",children:"Label (optional)"}),Be(ae,{id:"key-name",onChange:i=>r(i.target.value),placeholder:"e.g., Production, Testing",value:n})]})]})}function Nd({overlayId:e}){let{push:t,closeAll:o}=ne(),[n,r]=bn(!0),[s,a]=bn([]),[l,i]=bn(null),[d,c]=bn(null),u=gg(async()=>{r(!0);try{let w=await fetch("/api/api-keys");if(!w.ok)throw new Error("Failed to load API keys");let k=await w.json();a(k)}catch(w){console.error("Failed to load API keys:",w),wn.error("Failed to load API keys")}finally{r(!1)}},[]);yg(()=>{u()},[u]);let p=w=>{i(w.key??null),a(k=>[w,...k])},g=async w=>{c(w);try{if(!(await fetch(`/api/api-keys/${w}`,{method:"DELETE"})).ok)throw new Error("Failed to delete API key");a(f=>f.filter(T=>T.id!==w)),wn.success("API key deleted")}catch(k){console.error("Failed to delete API key:",k),wn.error("Failed to delete API key")}finally{c(null)}},C=w=>{t(Oe,{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:()=>g(w)})},v=w=>{navigator.clipboard.writeText(w),wn.success("Copied to clipboard")},y=w=>new Date(w).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return At(De,{actions:[{label:"New API Key",variant:"outline",onClick:()=>t(vg,{onCreated:p})},{label:"Done",onClick:o}],overlayId:e,title:"API Keys",children:[Be("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys for webhook authentication"}),n?Be("div",{className:"flex items-center justify-center py-8",children:Be(Nt,{})}):At("div",{className:"space-y-4",children:[l&&At("div",{className:"rounded-md border border-yellow-500/50 bg-yellow-500/10 p-3",children:[Be("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!"}),At("div",{className:"flex items-center gap-2",children:[Be("code",{className:"flex-1 rounded bg-muted px-2 py-1 font-mono text-xs",children:l}),Be(R,{onClick:()=>v(l),size:"sm",variant:"outline",children:Be(mg,{className:"size-4"})})]}),Be(R,{className:"mt-2",onClick:()=>i(null),size:"sm",variant:"ghost",children:"Dismiss"})]}),s.length===0?At("div",{className:"py-8 text-center text-muted-foreground text-sm",children:[Be(pg,{className:"mx-auto mb-2 size-8 opacity-50"}),Be("p",{children:"No API keys yet"}),Be("p",{className:"text-xs",children:"Create an API key to authenticate webhook requests"})]}):Be("div",{className:"space-y-2",children:s.map(w=>At("div",{className:"flex items-center justify-between rounded-md border p-3",children:[At("div",{className:"min-w-0 flex-1",children:[At("div",{className:"flex items-center gap-2",children:[At("code",{className:"rounded bg-muted px-1.5 py-0.5 font-mono text-xs",children:[w.keyPrefix,"..."]}),w.name&&Be("span",{className:"truncate text-sm",children:w.name})]}),At("p",{className:"mt-1 text-muted-foreground text-xs",children:["Created ",y(w.createdAt),w.lastUsedAt&&` \xB7 Last used ${y(w.lastUsedAt)}`]})]}),Be(R,{disabled:d===w.id,onClick:()=>C(w.id),size:"sm",variant:"ghost",children:d===w.id?Be(Nt,{className:"size-4"}):Be(fg,{className:"size-4 text-destructive"})})]},w.id))})]})]})}import{useSetAtom as Cg}from"jotai";import{Search as Tg}from"lucide-react";import{useCallback as hs,useEffect as Ag,useRef as Sg,useState as Cd}from"react";import{Pencil as hg,Trash2 as bg}from"lucide-react";import{useCallback as wg,useEffect as xg,useMemo as Ng,useState as ys}from"react";import{toast as ta}from"sonner";import{jsx as Ge,jsxs as vs}from"react/jsx-runtime";var kg={database:"Database"};function kd({onIntegrationChange:e,filter:t=""}){let{push:o}=ne(),[n,r]=ys([]),[s,a]=ys(!0),[l,i]=ys(null),d=wg(async()=>{try{a(!0);let v=await j.integration.getAll();r(v)}catch(v){console.error("Failed to load integrations:",v),ta.error("Failed to load integrations")}finally{a(!1)}},[]);xg(()=>{d()},[d]);let c=Ng(()=>{let v=Yt(),y=t.toLowerCase();return n.map(w=>({...w,label:v[w.type]||kg[w.type]||w.type})).filter(w=>t?w.label.toLowerCase().includes(y)||w.name.toLowerCase().includes(y)||w.type.toLowerCase().includes(y):!0).sort((w,k)=>{let f=w.label.localeCompare(k.label);return f!==0?f:w.name.localeCompare(k.name)})},[n,t]),u=v=>{o(Or,{integration:v,onSuccess:()=>{d(),e?.()},onDelete:()=>{d(),e?.()}})},p=v=>{o(La,{integration:v,onSuccess:()=>{d(),e?.()}})},g=async v=>{try{i(v);let y=await j.integration.testConnection(v);y.status==="success"?ta.success(y.message||"Connection successful"):ta.error(y.message||"Connection test failed")}catch(y){console.error("Connection test failed:",y),ta.error(y instanceof Error?y.message:"Connection test failed")}finally{i(null)}};return s?Ge("div",{className:"flex items-center justify-center py-8",children:Ge(Nt,{})}):Ge("div",{className:"space-y-1",children:n.length===0?Ge("div",{className:"py-8 text-center",children:Ge("p",{className:"text-muted-foreground text-sm",children:"No connections configured yet"})}):c.length===0?Ge("div",{className:"py-8 text-center",children:Ge("p",{className:"text-muted-foreground text-sm",children:"No connections match your filter"})}):Ge("div",{className:"space-y-1",children:c.map(v=>vs("div",{className:"flex items-center justify-between rounded-md px-2 py-1.5",children:[vs("div",{className:"flex items-center gap-2",children:[Ge(Rt,{className:"size-4",integration:v.type==="ai-gateway"?"vercel":v.type}),Ge("span",{className:"font-medium text-sm",children:v.label}),Ge("span",{className:"text-muted-foreground text-sm",children:v.name})]}),vs("div",{className:"flex items-center gap-1",children:[Ge(R,{className:"h-7 px-2",disabled:l===v.id,onClick:()=>g(v.id),size:"sm",variant:"outline",children:l===v.id?Ge(Nt,{className:"size-3"}):Ge("span",{className:"text-xs",children:"Test"})}),Ge(R,{className:"size-7",onClick:()=>u(v),size:"icon",variant:"outline",children:Ge(hg,{className:"size-3"})}),Ge(R,{className:"size-7",onClick:()=>p(v),size:"icon",variant:"outline",children:Ge(bg,{className:"size-3"})})]})]},v.id))})})}import{jsx as Ro,jsxs as bs}from"react/jsx-runtime";function Td({overlayId:e}){let{push:t,closeAll:o}=ne(),[n,r]=Cd(!0),[s,a]=Cd(""),l=Cg(Pt),i=Sg(!1),d=hs(async()=>{r(!0);try{await new Promise(g=>setTimeout(g,0))}finally{r(!1)}},[]);Ag(()=>{d(),i.current=!1,a("")},[d]);let c=hs(()=>{i.current&&l(g=>g+1),o()},[o,l]),u=hs(()=>{i.current=!0},[]);return bs(De,{actions:[{label:"Add Connection",variant:"outline",onClick:()=>{t(Fi,{onSuccess:u})}},{label:"Done",onClick:c}],overlayId:e,title:"Connections",children:[Ro("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Manage API keys and credentials used by your workflows"}),n?Ro("div",{className:"flex items-center justify-center py-8",children:Ro(Nt,{})}):bs("div",{className:"space-y-4",children:[bs("div",{className:"relative",children:[Ro(Tg,{className:"absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground"}),Ro(ae,{className:"pl-9",onChange:g=>a(g.target.value),placeholder:"Filter connections...",value:s})]}),Ro("div",{className:"max-h-[300px] overflow-y-auto",children:Ro(kd,{filter:s,onIntegrationChange:u})})]})]})}import{useCallback as Pd,useEffect as Ig,useState as ra}from"react";import{toast as Ed}from"sonner";import{jsx as na}from"react/jsx-runtime";function oa({className:e,...t}){return na("div",{"data-slot":"card",className:x("text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ad({className:e,...t}){return na("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function Sd({className:e,...t}){return na("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function ws({className:e,...t}){return na("div",{"data-slot":"card-content",className:x("px-6",e),...t})}import{jsx as jn,jsxs as xs}from"react/jsx-runtime";function Id({accountName:e,accountEmail:t,onNameChange:o,onEmailChange:n}){return jn(oa,{className:"border-0 py-0 shadow-none",children:xs(ws,{className:"space-y-4 p-0",children:[xs("div",{className:"space-y-2",children:[jn(W,{className:"ml-1",htmlFor:"accountName",children:"Name"}),jn(ae,{id:"accountName",onChange:r=>o(r.target.value),placeholder:"Your name",value:e})]}),xs("div",{className:"space-y-2",children:[jn(W,{className:"ml-1",htmlFor:"accountEmail",children:"Email"}),jn(ae,{id:"accountEmail",onChange:r=>n(r.target.value),placeholder:"your.email@example.com",type:"email",value:t})]})]})})}import{jsx as aa,jsxs as Pg}from"react/jsx-runtime";function Dd({overlayId:e}){let{closeAll:t}=ne(),[o,n]=ra(!0),[r,s]=ra(!1),[a,l]=ra(""),[i,d]=ra(""),c=Pd(async()=>{try{let g=await j.user.get();l(g.name||""),d(g.email||"")}catch(g){console.error("Failed to load account:",g)}},[]),u=Pd(async()=>{n(!0);try{await c()}finally{n(!1)}},[c]);return Ig(()=>{u()},[u]),Pg(De,{actions:[{label:"Cancel",variant:"outline",onClick:t},{label:"Save",onClick:async()=>{try{s(!0),await j.user.update({name:a,email:i}),await c(),Ed.success("Settings saved"),t()}catch(g){console.error("Failed to save account:",g),Ed.error("Failed to save settings")}finally{s(!1)}},loading:r,disabled:o}],overlayId:e,title:"Settings",children:[aa("p",{className:"-mt-2 mb-4 text-muted-foreground text-sm",children:"Update your personal information"}),o?aa("div",{className:"flex items-center justify-center py-8",children:aa(Nt,{})}):aa(Id,{accountEmail:i,accountName:a,onEmailChange:d,onNameChange:l})]})}import{Avatar as Ns}from"radix-ui";import{jsx as ks}from"react/jsx-runtime";function Rd({className:e,...t}){return ks(Ns.Root,{"data-slot":"avatar",className:x("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...t})}function Od({className:e,...t}){return ks(Ns.Image,{"data-slot":"avatar-image",className:x("aspect-square size-full",e),...t})}function Ld({className:e,...t}){return ks(Ns.Fallback,{"data-slot":"avatar-fallback",className:x("bg-muted flex size-full items-center justify-center rounded-full",e),...t})}import{jsx as he,jsxs as Ot}from"react/jsx-runtime";var zd=()=>{let{data:e,isPending:t}=cn(),{theme:o,setTheme:n}=Fg(),{open:r}=ne(),[s,a]=Fd(null),[l,i]=Fd(!1);Md(()=>{i(!0)},[]),Md(()=>{e?.user&&!e.user.name?.startsWith("Anonymous")&&j.user.get().then(g=>a(g.providerId)).catch(()=>a(null))},[e?.user]);let d=async()=>{await Il()},c=s==="vercel"||s==="github"||s==="google",u=()=>e?.user?.name?e.user.name.split(" ").map(g=>g[0]).join("").toUpperCase().slice(0,2):e?.user?.email?e.user.email.slice(0,2).toUpperCase():"U";return t||!l?he("div",{className:"h-9 w-9"}):!e?.user||e.user.name==="Anonymous"||e.user.email?.startsWith("temp-")?he("div",{className:"flex items-center gap-2",children:he(R,{className:"h-9 disabled:opacity-100 disabled:[&>*]:text-muted-foreground",size:"sm",variant:"default",asChild:!0,children:he(zg,{href:"/auth/sign-in",children:"Sign In"})})}):Ot(To,{children:[he(Ao,{asChild:!0,children:he(R,{className:"relative h-9 w-9 rounded-full border p-0",variant:"ghost",children:Ot(Rd,{className:"h-9 w-9",children:[he(Od,{alt:e?.user?.name||"",src:e?.user?.image||""}),he(Ld,{children:u()})]})})}),Ot(So,{align:"end",className:"w-56",children:[he(ol,{children:Ot("div",{className:"flex flex-col space-y-1",children:[he("p",{className:"font-medium text-sm leading-none",children:e?.user?.name||"User"}),he("p",{className:"text-muted-foreground text-xs leading-none",children:e?.user?.email})]})}),he(Fn,{}),!c&&Ot(ht,{onClick:()=>r(Dd),children:[he(Lg,{className:"size-4"}),he("span",{children:"Settings"})]}),Ot(ht,{onClick:()=>r(Td),children:[he(Og,{className:"size-4"}),he("span",{children:"Connections"})]}),Ot(ht,{onClick:()=>r(Nd),children:[he(Eg,{className:"size-4"}),he("span",{children:"API Keys"})]}),Ot(nl,{children:[Ot(rl,{children:[he(Mg,{className:"size-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0"}),he(Rg,{className:"absolute size-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100"}),he("span",{children:"Theme"})]}),he(al,{children:Ot(tl,{onValueChange:n,value:o,children:[he(Vr,{value:"light",children:"Light"}),he(Vr,{value:"dark",children:"Dark"}),he(Vr,{value:"system",children:"System"})]})})]}),he(Fn,{}),Ot(ht,{onClick:d,children:[he(Dg,{className:"size-4"}),he("span",{children:"Logout"})]})]})]})};import{Fragment as ia,jsx as q,jsxs as Pe}from"react/jsx-runtime";function $d(e,t,o){for(let n of e)t({id:n.id,data:{status:o}})}var Yg={"Database Query":"database"},Jg={database:"Database"};function Xg(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 jd(e,t=""){let o=[];for(let[n,r]of Object.entries(e)){let s=t?`${t}.${n}`:n;if(typeof r=="string"){let a=Xg(r);for(let l of a)o.push({field:s,...l})}else typeof r=="object"&&r!==null&&!Array.isArray(r)&&o.push(...jd(r,s))}return o}function Qg(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=jd(r).filter(l=>!t.has(l.nodeId));if(a.length>0){let l=r.actionType,i=l?pe(l):void 0,d=i?fa(i.configFields):[];o.push({nodeId:n.id,nodeLabel:n.data.label||i?.label||"Unnamed Step",brokenReferences:a.map(c=>{let u=d.find(p=>p.key===c.field);return{fieldKey:c.field,fieldLabel:u?.label||c.field,referencedNodeId:c.nodeId,displayText:c.displayText}})})}}return o}function Zg(e){return e==null||typeof e=="string"&&e.trim()===""}function ey(e,t){return e.showWhen?t[e.showWhen.field]===e.showWhen.equals:!0}function ty(e){if(e.data.enabled===!1)return null;let t=e.data.config,o=t?.actionType;if(!o)return null;let n=pe(o);if(!n)return null;let s=fa(n.configFields).filter(a=>a.required&&ey(a,t||{})&&Zg(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 oy(e){return e.map(ty).filter(t=>t!==null)}function ny(e,t){let o=new Set(t.map(a=>a.type)),n=new Set(t.map(a=>a.id)),r=new Map,s=Yt();for(let a of e){if(a.data.enabled===!1)continue;let l=a.data.config?.actionType;if(!l)continue;let d=pe(l)?.integration||Yg[l];if(!d||!Fo(d))continue;let c=a.data.config?.integrationId;if(!(c&&n.has(c))&&!o.has(d)){let p=r.get(d)||[],g=pe(l);p.push(a.data.label||g?.label||l),r.set(d,p)}}return Array.from(r.entries()).map(([a,l])=>({integrationType:a,integrationLabel:s[a]||Jg[a]||a,nodeNames:l}))}async function ry({workflowId:e,nodes:t,updateNodeData:o,pollingIntervalRef:n,setIsExecuting:r,setSelectedExecutionId:s}){$d(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();s(l.executionId);let i=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=i}catch(a){console.error("Failed to execute workflow:",a),it.error(a instanceof Error?a.message:"Failed to execute workflow"),$d(t,o,"error"),r(!1)}}function ay({currentWorkflowId:e,nodes:t,edges:o,updateNodeData:n,isExecuting:r,setIsExecuting:s,setIsSaving:a,setHasUnsavedChanges:l,setActiveTab:i,setNodes:d,setEdges:c,setSelectedNodeId:u,setSelectedExecutionId:p,userIntegrations:g}){let{open:C}=ne(),v=qg(null);Ts(()=>()=>{v.current&&clearInterval(v.current)},[]);let y=async()=>{if(e){a(!0);try{await j.workflow.update(e,{nodes:t,edges:o}),l(!1)}catch(T){console.error("Failed to save workflow:",T),it.error("Failed to save workflow. Please try again.")}finally{a(!1)}}},w=async()=>{if(!e){it.error("Please save the workflow before executing");return}i("runs"),d(t.map(T=>({...T,selected:!1}))),c(o.map(T=>({...T,selected:!1}))),u(null),s(!0),await ry({workflowId:e,nodes:t,updateNodeData:n,pollingIntervalRef:v,setIsExecuting:s,setSelectedExecutionId:p})},k=(T,I)=>{u(T),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 T=Qg(t),I=oy(t),A=ny(t,g);if(T.length>0||I.length>0||A.length>0){C(wd,{issues:{brokenReferences:T,missingRequiredFields:I,missingIntegrations:A},onGoToStep:k,onRunAnyway:w});return}await w()}}}function sy(){let[e,t]=Ze(oe),[o,n]=Ze(ue),[r,s]=Ze(Ks),[a]=Ze(wt),l=Gt(gr),i=Gt(Zt),[d]=Ze($e),[c,u]=Ze(pt),[p,g]=Ze(sr),C=Wd(Xt),v=jg(),[y,w]=Ze(yr),[k,f]=Ze(tt),T=Gt(ti),I=Gt(oi),A=Gt(Vo),[h]=Ze(ni),[m]=Ze(ri),{data:S}=cn(),X=Gt(Ft),le=Gt(be),L=Gt(Qt),F=Wd(mt),[_,P]=Ze(pr),[V,Y]=Cs(!1),[M,K]=Cs(!1),[N,z]=Cs([]);return Ts(()=>{(async()=>{try{let D=await j.workflow.getAll();z(D)}catch(D){console.error("Failed to load workflows:",D)}})()},[]),{nodes:e,edges:o,isExecuting:r,setIsExecuting:s,isGenerating:a,clearWorkflow:l,updateNodeData:i,currentWorkflowId:d,workflowName:c,setCurrentWorkflowName:u,workflowVisibility:p,setWorkflowVisibility:g,isOwner:C,router:v,isSaving:y,setIsSaving:w,hasUnsavedChanges:k,setHasUnsavedChanges:f,undo:T,redo:I,addNode:A,canUndo:h,canRedo:m,session:S,isDownloading:V,setIsDownloading:Y,isDuplicating:M,setIsDuplicating:K,allWorkflows:N,setAllWorkflows:z,setActiveTab:X,setNodes:t,setEdges:n,setSelectedNodeId:le,setSelectedExecutionId:L,userIntegrations:F,triggerExecute:_,setTriggerExecute:P}}function iy(e){let{open:t}=ne(),{currentWorkflowId:o,workflowName:n,nodes:r,edges:s,updateNodeData:a,isExecuting:l,setIsExecuting:i,setIsSaving:d,setHasUnsavedChanges:c,clearWorkflow:u,setWorkflowVisibility:p,setAllWorkflows:g,setIsDownloading:C,setIsDuplicating:v,setActiveTab:y,setNodes:w,setEdges:k,setSelectedNodeId:f,setSelectedExecutionId:T,userIntegrations:I,triggerExecute:A,setTriggerExecute:h,router:m,session:S}=e,{handleSave:X,handleExecute:le}=ay({currentWorkflowId:o,nodes:r,edges:s,updateNodeData:a,isExecuting:l,setIsExecuting:i,setIsSaving:d,setHasUnsavedChanges:c,setActiveTab:y,setNodes:w,setEdges:k,setSelectedNodeId:f,setSelectedExecutionId:T,userIntegrations:I});return Ts(()=>{A&&(h(!1),le())},[A,h,le]),{handleSave:X,handleExecute:le,handleClearWorkflow:()=>{t(Oe,{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(Oe,{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),it.success("Workflow deleted successfully"),window.location.href="/"}catch(M){console.error("Failed to delete workflow:",M),it.error("Failed to delete workflow. Please try again.")}}})},handleDownload:async()=>{if(!o){it.error("Please save the workflow before downloading");return}C(!0),it.info("Preparing workflow files for download...");try{let M=await j.workflow.download(o);if(!M.success)throw new Error(M.error||"Failed to prepare download");if(!M.files)throw new Error("No files to download");let K=(await import("jszip")).default,N=new K;for(let[G,te]of Object.entries(M.files))N.file(G,te);let z=await N.generateAsync({type:"blob"}),b=URL.createObjectURL(z),D=document.createElement("a");D.href=b,D.download=`${n.toLowerCase().replace(/[^a-z0-9]/g,"-")}-workflow.zip`,document.body.appendChild(D),D.click(),document.body.removeChild(D),URL.revokeObjectURL(b),it.success("Workflow downloaded successfully!")}catch(M){it.error(M instanceof Error?M.message:"Failed to download workflow")}finally{C(!1)}},loadWorkflows:async()=>{try{let M=await j.workflow.getAll();g(M)}catch(M){console.error("Failed to load workflows:",M)}},handleToggleVisibility:async M=>{if(o){if(M==="public"){t(hd,{onConfirm:async()=>{try{await j.workflow.update(o,{visibility:"public"}),p("public"),it.success("Workflow is now public")}catch(K){console.error("Failed to update visibility:",K),it.error("Failed to update visibility. Please try again.")}}});return}try{await j.workflow.update(o,{visibility:M}),p(M),it.success("Workflow is now private")}catch(K){console.error("Failed to update visibility:",K),it.error("Failed to update visibility. Please try again.")}}},handleDuplicate:async()=>{if(o){v(!0);try{S?.user||(await Eo.signIn.anonymous(),await new Promise(K=>setTimeout(K,100)));let M=await j.workflow.duplicate(o);it.success("Workflow duplicated successfully"),m.push(`/workflows/${M.id}`)}catch(M){console.error("Failed to duplicate workflow:",M),it.error("Failed to duplicate workflow. Please try again.")}finally{v(!1)}}}}}function ly({workflowId:e,state:t,actions:o}){let{open:n,push:r}=ne(),[s]=Ze(be),[a]=Ze(_e),[l]=Ze(oe),[i]=Ze(ue),d=Gt(eo),c=Gt(to),{screenToFlowPosition:u}=Wg(),p=l.find(w=>w.id===s),g=i.find(w=>w.id===a),C=p||g;if(e&&!t.isOwner||!e)return null;let v=()=>{let k=!!s?"Node":"Connection";r(Oe,{title:`Delete ${k}`,message:`Are you sure you want to delete this ${k.toLowerCase()}? This action cannot be undone.`,confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{s?d(s):a&&c(a)}})},y=()=>{let w=document.querySelector(".react-flow");if(!w)return;let k=w.getBoundingClientRect(),f=k.left+k.width/2,T=k.top+k.height/2,I=u({x:f,y:T}),A=192,h=192;I.x-=A/2,I.y-=h/2;let m=20,S=20,X={...I},le=!0,L=0,F=20;for(;le&&L<F;)le=t.nodes.some(P=>{let V=Math.abs(P.position.x-X.x),Y=Math.abs(P.position.y-X.y);return V<S&&Y<S}),le&&(X.x+=m,X.y+=m,L+=1);let _={id:Kg(),type:"action",position:X,data:{label:"",description:"",type:"action",config:{},status:"idle"}};t.addNode(_),t.setSelectedNodeId(_.id),t.setActiveTab("properties")};return Pe(ia,{children:[q(Vt,{className:"flex lg:hidden",orientation:"vertical",children:q(R,{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:q(Gd,{className:"size-4"})})}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[q(R,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:()=>n(Qr,{}),size:"icon",title:"Configuration",variant:"secondary",children:q($g,{className:"size-4"})}),C&&q(R,{className:"border hover:bg-black/5 dark:hover:bg-white/5",onClick:v,size:"icon",title:"Delete",variant:"secondary",children:q(Ug,{className:"size-4"})})]}),q(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:q(R,{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:q(Gd,{className:"size-4"})})}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[q(R,{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:q(_d,{className:"size-4"})}),q(R,{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:q(Hd,{className:"size-4"})})]}),Pe(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:[q(R,{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:q(_d,{className:"size-4"})}),q(R,{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:q(Hd,{className:"size-4"})})]}),Pe(Vt,{className:"flex lg:hidden",orientation:"vertical",children:[q(Ud,{handleSave:o.handleSave,state:t}),q(Kd,{actions:o,state:t})]}),Pe(Vt,{className:"hidden lg:flex",orientation:"horizontal",children:[q(Ud,{handleSave:o.handleSave,state:t}),q(Kd,{actions:o,state:t})]}),q(dy,{actions:o,state:t}),q(cy,{actions:o,state:t})]})}function Ud({state:e,handleSave:t}){return Pe(R,{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?q(la,{className:"size-4 animate-spin"}):q(_g,{className:"size-4"}),e.hasUnsavedChanges&&!e.isSaving&&q("div",{className:"absolute top-1.5 right-1.5 size-2 rounded-full bg-primary"})]})}function Kd({state:e,actions:t}){let{open:o}=ne(),n=()=>{o(vd,{onExport:t.handleDownload,isDownloading:e.isDownloading})};return q(R,{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?q(la,{className:"size-4 animate-spin"}):q(Gg,{className:"size-4"})})}function dy({state:e,actions:t}){let o=e.workflowVisibility==="public";return Pe(To,{children:[q(Ao,{asChild:!0,children:q(R,{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?q(Bd,{className:"size-4"}):q(Vd,{className:"size-4"})})}),Pe(So,{align:"end",children:[Pe(ht,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("private"),children:[q(Vd,{className:"size-4"}),"Private",!o&&q(sa,{className:"ml-auto size-4"})]}),Pe(ht,{className:"flex items-center gap-2",onClick:()=>t.handleToggleVisibility("public"),children:[q(Bd,{className:"size-4"}),"Public",o&&q(sa,{className:"ml-auto size-4"})]})]})]})}function cy({state:e,actions:t}){return q(R,{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?q(la,{className:"size-4 animate-spin"}):q(Hg,{className:"size-4"})})}function uy({isDuplicating:e,onDuplicate:t}){return Pe(R,{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?q(la,{className:"mr-2 size-4 animate-spin"}):q(Vg,{className:"mr-2 size-4"}),"Duplicate"]})}function my({workflowId:e,state:t,actions:o}){return Pe("div",{className:"flex flex-col gap-1",children:[q("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(To,{onOpenChange:n=>n&&o.loadWorkflows(),children:[Pe(Ao,{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:[q(xd,{className:"size-4 shrink-0"}),q("p",{className:"truncate font-medium text-sm",children:e?t.workflowName:Pe(ia,{children:[q("span",{className:"sm:hidden",children:"New"}),q("span",{className:"hidden sm:inline",children:"New Workflow"})]})}),q(Bg,{className:"size-3 shrink-0 opacity-50"})]}),Pe(So,{align:"start",className:"w-64",children:[q(ht,{asChild:!0,className:"flex items-center justify-between",children:Pe("a",{href:"/",children:["New Workflow"," ",!e&&q(sa,{className:"size-4 shrink-0"})]})}),q(Fn,{}),t.allWorkflows.length===0?q(ht,{disabled:!0,children:"No workflows found"}):t.allWorkflows.filter(n=>n.name!=="__current__").map(n=>Pe(ht,{className:"flex items-center justify-between",onClick:()=>t.router.push(`/workflows/${n.id}`),children:[q("span",{className:"truncate",children:n.name}),n.id===t.currentWorkflowId&&q(sa,{className:"size-4 shrink-0"})]},n.id))]})]})}),e&&!t.isOwner&&q("span",{className:"text-muted-foreground text-xs uppercase lg:hidden",children:"Read-only"})]})}var qd=({workflowId:e})=>{let t=sy(),o=iy(t);return Pe(ia,{children:[q(Xr,{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:[q(my,{actions:o,state:t,workflowId:e}),e&&!t.isOwner&&q("span",{className:"hidden text-muted-foreground text-xs uppercase lg:inline",children:"Read-only"})]})}),q("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:[q(ly,{actions:o,state:t,workflowId:e}),Pe("div",{className:"flex items-center gap-2",children:[!e&&Pe(ia,{children:[q(sd,{}),q(Zl,{})]}),e&&!t.isOwner&&q(uy,{isDuplicating:t.isDuplicating,onDuplicate:o.handleDuplicate}),q(zd,{})]})]})})]})};import"@xyflow/react/dist/style.css";import{PlayCircle as Zy,Zap as ev}from"lucide-react";import{nanoid as Rs}from"nanoid";import{BaseEdge as Xd,getBezierPath as py,getSimpleBezierPath as fy,Position as Oo,useInternalNode as Yd}from"@xyflow/react";import{jsx as Qd}from"react/jsx-runtime";var gy=({id:e,sourceX:t,sourceY:o,targetX:n,targetY:r,sourcePosition:s,targetPosition:a,selected:l})=>{let[i]=fy({sourceX:t,sourceY:o,sourcePosition:s,targetX:n,targetY:r,targetPosition:a});return Qd(Xd,{className:"stroke-1",id:e,path:i,style:{stroke:l?"var(--muted-foreground)":"var(--border)",strokeDasharray:"5, 5"}})},Jd=(e,t)=>{let o=t===Oo.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 Oo.Left:r=0;break;case Oo.Right:r=n.width;break;case Oo.Top:s=0;break;case Oo.Bottom:s=n.height;break;default:throw new Error(`Invalid handle position: ${t}`)}let a=e.internals.positionAbsolute.x+n.x+r,l=e.internals.positionAbsolute.y+n.y+s;return[a,l]},yy=(e,t)=>{let o=Oo.Right,[n,r]=Jd(e,o),s=Oo.Left,[a,l]=Jd(t,s);return{sx:n,sy:r,tx:a,ty:l,sourcePos:o,targetPos:s}},vy=({id:e,source:t,target:o,style:n,selected:r})=>{let s=Yd(t),a=Yd(o);if(!(s&&a))return null;let{sx:l,sy:i,tx:d,ty:c,sourcePos:u,targetPos:p}=yy(s,a),[g]=py({sourceX:l,sourceY:i,sourcePosition:u,targetX:d,targetY:c,targetPosition:p});return Qd(Xd,{id:e,path:g,style:{...n,stroke:r?"var(--muted-foreground)":"var(--border)",strokeWidth:2,animation:"dashdraw 0.5s linear infinite",strokeDasharray:5}})},As={Temporary:gy,Animated:vy};import{useAtomValue as Qn}from"jotai";import{AlertTriangle as wy,Check as xy,Code as Ny,EyeOff as oc,XCircle as ky,Zap as ac}from"lucide-react";import nc from"next/image";import{memo as Cy,useState as Ty}from"react";import{Handle as ec,Position as tc}from"@xyflow/react";import{Fragment as hy,jsx as fo,jsxs as Ss}from"react/jsx-runtime";var Zd=({className:e})=>Ss(hy,{children:[fo("style",{children:`
|
|
193
193
|
@property --angle {
|
|
194
194
|
syntax: "<angle>";
|
|
195
195
|
initial-value: 0deg;
|
|
@@ -214,4 +214,4 @@ export async function POST(request: NextRequest) {
|
|
|
214
214
|
transparent 100%
|
|
215
215
|
);
|
|
216
216
|
}
|
|
217
|
-
`}),fo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Ss("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[fo("defs",{children:Ss("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[fo("stop",{offset:"0%",stopColor:"#60a5fa"}),fo("stop",{offset:"50%",stopColor:"#3b82f6"}),fo("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),fo("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)"}})]})}),fo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as jn,jsxs as hy}from"react/jsx-runtime";var qn=({handles:e,className:t,status:o,...n})=>hy(oa,{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"&&jn(Qd,{}),e.target&&jn(Zd,{position:ec.Left,type:"target"}),e.source&&jn(Zd,{position:ec.Right,type:"source"}),n.children]});var Yn=e=>jn(Td,{...e}),Jn=e=>jn(Ad,{...e});import{Fragment as Oy,jsx as Ne,jsxs as jt}from"react/jsx-runtime";var Ty=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"},Ay=e=>{if(nc[e])return nc[e];let t=pe(e);return t?.integration&&It(t.integration)?.label||"System"};function Sy(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var Iy=e=>{if(["Database Query"].includes(e))return!0;let o=pe(e);return o?Fo(o.integration):!1},Py=e=>{switch(e){case"HTTP Request":return Bo.icon;case"Database Query":return Wo.icon;case"Execute Code":return Ne(xy,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return zo.icon;case"Loop":return Fr.icon;case"Merge":return zr.icon;case"Switch":return Wr.icon;default:break}let t=pe(e);if(t){let o=It(t.integration);if(o?.icon){let n=o.icon;return Ne(n,{className:"size-12"})}}return Ne(rc,{className:"size-12 text-amber-300",strokeWidth:1.5})},Ey=({status:e})=>!e||e==="idle"||e==="running"?null:jt("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"&&Ne(wy,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Ne(Ny,{className:"size-3.5 text-white",strokeWidth:2.5})]}),Dy=({model:e})=>e?Ne("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:Ty(e)}):null;function Ry({base64:e}){let[t,o]=Cy(!1);return jt(Oy,{children:[Ne("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:Ne(oc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Ne(Jr,{onOpenChange:o,open:t,children:jt(Dl,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Ne(Rl,{className:"sr-only",children:"Generated Image"}),Ne("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Ne(oc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var Is=ky(({data:e,selected:t,id:o})=>{let n=Xn(Qt),r=Xn(pr),s=Xn(ur),a=Xn(_s),l=Xn(rr);if(!e)return null;let i=e.config?.actionType||"",d=e.status,c=r[o],u=n&&i==="Generate Image"&&c?.output&&Sy(c.output);if(!i){let h=e.enabled===!1;return jt(qn,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",h&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:d,children:[h&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ne(tc,{className:"size-3.5 text-white"})}),jt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Ne(rc,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),jt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ne(Yn,{className:"text-base",children:e.label||"Action"}),Ne(Jn,{className:"text-xs",children:"Select an action"})]})]})]})}let p=pe(i),g=e.label||p?.label||i,T=e.description||Ay(i),v=Iy(i),y=s.has(o),w=e.config?.integrationId,k=w&&a.has(w),f=l&&v&&!k&&!y,I=i==="Generate Text"?e.config?.aiModel||"meta/llama-4-scout":i==="Generate Image"?e.config?.imageModel||"google/imagen-4.0-generate":null,C=e.enabled===!1;return jt(qn,{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",C&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:d,children:[C&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ne(tc,{className:"size-3.5 text-white"})}),!C&&f&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Ne(by,{className:"size-3.5 text-white"})}),Ne(Ey,{status:d}),jt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Ne(Ry,{base64:c.output.base64}):Py(i),jt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ne(Yn,{className:"text-base",children:g}),T&&Ne(Jn,{className:"text-xs",children:T}),I&&Ne(Dy,{model:I})]})]})]})});Is.displayName="ActionNode";import{Plus as Ly}from"lucide-react";import{jsx as xn,jsxs as da}from"react/jsx-runtime";function ac({data:e}){return da("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:[da("div",{className:"text-center",children:[xn("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),da("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",xn("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"}),","," ",xn("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"}),","," ",xn("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"," ",xn("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"})]})]}),da(O,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[xn(Ly,{className:"size-4"}),"Add a Step"]})]})}import{Check as My,Clock as Fy,Play as zy,Webhook as Wy,XCircle as By}from"lucide-react";import{memo as Vy}from"react";import{jsx as Qn,jsxs as ca}from"react/jsx-runtime";var Ps=Vy(({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=zy;return o==="Schedule"?a=Fy:o==="Webhook"&&(a=Wy),ca(qn,{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"&&ca("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"&&Qn(My,{className:"size-3.5 text-white",strokeWidth:2.5}),s==="error"&&Qn(By,{className:"size-3.5 text-white",strokeWidth:2.5})]}),ca("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Qn(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),ca("div",{className:"flex flex-col items-center gap-1 text-center",children:[Qn(Yn,{className:"text-base",children:n}),r&&Qn(Jn,{className:"text-xs",children:r})]})]})]})});Ps.displayName="TriggerNode";import{useAtomValue as Gy,useSetAtom as Zn}from"jotai";import{Link2Off as Hy,Plus as _y,Trash2 as $y}from"lucide-react";import{nanoid as Uy}from"nanoid";import{useCallback as kn,useEffect as Ky,useRef as jy}from"react";import{jsx as Nn,jsxs as lc}from"react/jsx-runtime";function sc({menuState:e,onClose:t}){let o=Gy(oe),n=Zn(eo),r=Zn(to),s=Zn(Vo),a=Zn(be),l=Zn(Ft),{open:i}=ne(),d=jy(null),c=kn(()=>{if(e?.nodeId){let v=e.nodeId;t(),i(Oe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(v)}})}},[e,n,t,i]),u=kn(()=>{if(e?.edgeId){let v=e.edgeId;t(),i(Oe,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(v)}})}},[e,r,t,i]),p=kn(()=>{if(e?.flowPosition){let y={id:Uy(),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),l("properties")}t()},[e,s,a,l,t]);if(Ky(()=>{if(!e)return;let v=k=>{d.current&&!d.current.contains(k.target)&&t()},y=k=>{k.key==="Escape"&&t()},w=setTimeout(()=>{document.addEventListener("mousedown",v),document.addEventListener("keydown",y)},0);return()=>{clearTimeout(w),document.removeEventListener("mousedown",v),document.removeEventListener("keydown",y)}},[e,t]),!e)return null;let g=!!(e.nodeId&&o.find(v=>v.id===e.nodeId)?.data.type==="trigger"),T=()=>e.nodeId&&o.find(y=>y.id===e.nodeId)?.data.label||"Step";return lc("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"&&Nn(Es,{disabled:g,icon:Nn($y,{className:"size-4"}),label:`Delete ${T()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&Nn(Es,{icon:Nn(Hy,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&Nn(Es,{icon:Nn(_y,{className:"size-4"}),label:"Add Step",onClick:p})]})}function Es({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return lc("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 ic(e,t){let o=kn((s,a)=>{s.preventDefault(),t({type:"node",position:{x:s.clientX,y:s.clientY},nodeId:a.id})},[t]),n=kn((s,a)=>{s.preventDefault(),t({type:"edge",position:{x:s.clientX,y:s.clientY},edgeId:a.id})},[t]),r=kn(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 Mo,jsxs as cc}from"react/jsx-runtime";var ev=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:Qy,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:Zy,defaultConfig:{}}],tv={animated:As.Animated,temporary:As.Temporary};function uc(){let[e,t]=er(oe),[o,n]=er(ue),[r]=er(wt),s=Ds($e),[a]=er(sr),l=Ds(ir),i=Ds(lr),[d,c]=er(cr),u=go(qs),p=go(Ys),g=go(be),T=go(_e),v=go(Vo),y=go(tt),w=go(Lt),k=go(Ft),{screenToFlowPosition:f,fitView:A,getViewport:I,setViewport:C}=Jy(),h=Lo(null),m=Lo(null),S=Lo(!1),J=Lo(!1),[D,j]=dc(!1),[z,re]=dc(null),{onNodeContextMenu:P,onEdgeContextMenu:V,onPaneContextMenu:X}=ic(f,re),W=bt(()=>{re(null)},[]),U=Lo(void 0),N=e.some(Q=>Q.type!=="add"),M=Lo(!1),b=Lo(!1);ua(()=>{if(d&&!b.current){if(b.current=!0,document.cookie.split("; ").find(Ee=>Ee.startsWith("sidebar-collapsed="))?.split("=")[1]==="true")return;let H=I(),ce=window.innerWidth*.3/2;C({...H,x:H.x-ce},{duration:0})}},[d,I,C]),ua(()=>{if(U.current!==s){if(d&&J.current){U.current=s,j(!0),c(!1);return}setTimeout(()=>{A({maxZoom:1,minZoom:.5,padding:.2,duration:0}),U.current=s,J.current=!0,j(!0),c(!1)},0)}},[s,A,d,c]),ua(()=>{s||(N&&!M.current?(M.current=!0,setTimeout(()=>{A({maxZoom:1,minZoom:.5,padding:.2,duration:0}),J.current=!0,j(!0)},0)):N||(M.current=!1))},[s,N,A]),ua(()=>{let Q=E=>{(E.metaKey||E.ctrlKey)&&E.key==="/"&&(E.preventDefault(),A({padding:.2,duration:300}))};return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[A]);let R=Xy(()=>({trigger:Ps,action:Is,add:ac}),[]),G=bt((Q,E)=>{let H=e.find(Y=>Y.id===Q);return!H||H.type==="add"?!1:E==="target"?H.type!=="trigger":!0},[e]),te=bt(Q=>!(!(Q.source&&Q.target)||Q.source===Q.target),[]),de=bt(Q=>{let E={id:Rs(),...Q,type:"animated"};n([...o,E]),y(!0),w({immediate:!0})},[o,n,y,w]),B=bt((Q,E)=>{g(E.id)},[g]),xe=bt((Q,E)=>{h.current=E.nodeId,m.current=E.handleType},[]),qe=bt(Q=>{let E="changedTouches"in Q?Q.changedTouches[0].clientX:Q.clientX,H="changedTouches"in Q?Q.changedTouches[0].clientY:Q.clientY;return{clientX:E,clientY:H}},[]),Ye=bt((Q,E,H)=>{let Y=Q.target.closest(".react-flow")?.getBoundingClientRect(),ce=Y?E-Y.left:E,Ee=Y?H-Y.top:H;return{adjustedX:ce,adjustedY:Ee}},[]),He=bt(Q=>{let E=Q.getAttribute("data-id"),H=m.current==="source",Y=H?"target":"source",ce=h.current;E&&ce&&E!==ce&&G(E,Y)&&de({source:H?ce:E,target:H?E:ce,sourceHandle:null,targetHandle:null})},[G,de]),qt=bt((Q,E,H)=>{let Y=h.current;if(!Y)return;let{adjustedX:ce,adjustedY:Ee}=Ye(Q,E,H),Re=ev.find(pa=>pa.type==="action");if(!Re)return;let Cn=f({x:ce,y:Ee}),ma=192;Cn.y-=ma/2;let Tn={id:Rs(),type:Re.type,position:Cn,data:{label:Re.label,description:Re.description,type:Re.type,config:Re.defaultConfig,status:"idle"},selected:!0};v(Tn),g(Tn.id),k("properties"),setTimeout(()=>{t(pa=>pa.map(Ls=>({...Ls,selected:Ls.id===Tn.id})))},50);let Os=m.current==="source",bc={id:Rs(),source:Os?Y:Tn.id,target:Os?Tn.id:Y,type:"animated"};n([...o,bc]),y(!0),w({immediate:!0}),S.current=!0,setTimeout(()=>{S.current=!1},100)},[Ye,f,v,o,n,t,g,k,y,w]),St=bt(Q=>{if(!h.current)return;let{clientX:E,clientY:H}=qe(Q),Y="changedTouches"in Q?document.elementFromPoint(E,H):Q.target;if(!Y){h.current=null;return}let ce=Y.closest(".react-flow__node"),Ee=Y.closest(".react-flow__handle");if(ce&&!Ee&&m.current){He(ce),h.current=null,m.current=null;return}ce||Ee||qt(Q,E,H),h.current=null,m.current=null},[qe,He,qt]),ee=bt(()=>{S.current||(g(null),T(null),W())},[g,T,W]),ve=bt(({nodes:Q})=>{S.current&&Q.length===0||(Q.length===0?g(null):Q.length===1&&g(Q[0].id))},[g]);return cc("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:D?1:0,width:l?`calc(100% - ${l})`:"100%",transition:i?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[Mo("div",{className:"pointer-events-auto",children:Mo(jd,{workflowId:s??void 0})}),cc($l,{className:"bg-background",connectionLineComponent:Kl,connectionMode:qy.Strict,edges:o,edgeTypes:tv,elementsSelectable:!r,isValidConnection:te,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:R,onConnect:r?void 0:de,onConnectEnd:r?void 0:St,onConnectStart:r?void 0:xe,onEdgeContextMenu:r?void 0:V,onEdgesChange:r?void 0:p,onNodeClick:r?void 0:B,onNodeContextMenu:r?void 0:P,onNodesChange:r?void 0:u,onPaneClick:ee,onPaneContextMenu:r?void 0:X,onSelectionChange:r?void 0:ve,children:[Mo(Xr,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:Mo(jl,{})}),a&&Mo(Yy,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),s&&Mo(Jl,{workflowId:s}),Mo(sc,{menuState:z,onClose:W})]})}import{jsx as mc}from"react/jsx-runtime";function pc(){let e=ov();return e==="/"||e.startsWith("/workflows/")?mc("div",{className:"fixed inset-0 z-0",children:mc(uc,{})}):null}import{AuthUIProvider as nv}from"@daveyplate/better-auth-ui";import rv from"next/link";import{useRouter as av}from"next/navigation";import{jsx as sv}from"react/jsx-runtime";var fc=e=>{let t=av(),{children:o,...n}=e;return sv(nv,{...n,authClient:Eo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:rv,children:o})};import{ThemeProvider as iv}from"next-themes";import{jsx as lv}from"react/jsx-runtime";var gc=({children:e,...t})=>lv(iv,{...t,children:e});import{jsx as yo,jsxs as yc}from"react/jsx-runtime";function uv(e){return Ci(),yc(Di,{children:[yo(vc.Suspense,{children:yc(dv,{children:[yo(pc,{}),e.children]})}),yo(_l,{}),yo(Hl,{})]})}var hc=e=>{let{children:t,...o}=e;return yo(gc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:yo(fc,{...o,children:yo(cv,{children:yo(uv,{children:t})})})})};import{jsx as pv}from"react/jsx-runtime";var mv=e=>{let{children:t,...o}=e;return pv(hc,{...o,children:t})};function fv(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function gv(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{mv as Layout,es as WorkflowEditor,Yp as WorkflowPage,fv as isAiGatewayManagedKeysEnabled,gv as isAiGatewayManagedKeysEnabledClient};
|
|
217
|
+
`}),fo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] animate-border-mask",e),children:Ss("svg",{className:"h-full w-full overflow-visible",xmlns:"http://www.w3.org/2000/svg",children:[fo("defs",{children:Ss("linearGradient",{id:"gradient-glow",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[fo("stop",{offset:"0%",stopColor:"#60a5fa"}),fo("stop",{offset:"50%",stopColor:"#3b82f6"}),fo("stop",{offset:"100%",stopColor:"#60a5fa"})]})}),fo("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)"}})]})}),fo("div",{className:x("pointer-events-none absolute inset-0 rounded-[inherit] border-2 border-blue-500/10",e)})]});import{jsx as qn,jsxs as by}from"react/jsx-runtime";var Yn=({handles:e,className:t,status:o,...n})=>by(oa,{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"&&qn(Zd,{}),e.target&&qn(ec,{position:tc.Left,type:"target"}),e.source&&qn(ec,{position:tc.Right,type:"source"}),n.children]});var Jn=e=>qn(Ad,{...e}),Xn=e=>qn(Sd,{...e});import{Fragment as Ly,jsx as Ne,jsxs as jt}from"react/jsx-runtime";var Ay=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,rc={"HTTP Request":"System","Database Query":"Database",Condition:"Condition","Execute Code":"System",Loop:"Loop",Switch:"Switch",Merge:"Merge"},Sy=e=>{if(rc[e])return rc[e];let t=pe(e);return t?.integration&&It(t.integration)?.label||"System"};function Iy(e){return typeof e=="object"&&e!==null&&"base64"in e&&typeof e.base64=="string"&&e.base64.length>100}var Py=e=>{if(["Database Query"].includes(e))return!0;let o=pe(e);return o?Fo(o.integration):!1},Ey=e=>{switch(e){case"HTTP Request":return Bo.icon;case"Database Query":return Wo.icon;case"Execute Code":return Ne(Ny,{className:"size-12 text-green-300",strokeWidth:1.5});case"Condition":return zo.icon;case"Loop":return zr.icon;case"Merge":return Wr.icon;case"Switch":return Br.icon;default:break}let t=pe(e);if(t){let o=It(t.integration);if(o?.icon){let n=o.icon;return Ne(n,{className:"size-12"})}}return Ne(ac,{className:"size-12 text-amber-300",strokeWidth:1.5})},Dy=({status:e})=>!e||e==="idle"||e==="running"?null:jt("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"&&Ne(xy,{className:"size-3.5 text-white",strokeWidth:2.5}),e==="error"&&Ne(ky,{className:"size-3.5 text-white",strokeWidth:2.5})]}),Ry=({model:e})=>e?Ne("div",{className:"rounded-full border border-muted-foreground/50 px-2 py-0.5 font-medium text-[10px] text-muted-foreground",children:Ay(e)}):null;function Oy({base64:e}){let[t,o]=Ty(!1);return jt(Ly,{children:[Ne("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:Ne(nc,{alt:"Generated image",className:"object-cover",fill:!0,sizes:"48px",src:`data:image/png;base64,${e}`,unoptimized:!0})}),Ne(Jr,{onOpenChange:o,open:t,children:jt(Rl,{className:"max-w-3xl p-2",showCloseButton:!1,children:[Ne(Ol,{className:"sr-only",children:"Generated Image"}),Ne("div",{className:"relative aspect-square w-full overflow-hidden rounded-lg",children:Ne(nc,{alt:"Generated image",className:"object-contain",fill:!0,sizes:"(max-width: 768px) 100vw, 768px",src:`data:image/png;base64,${e}`,unoptimized:!0})})]})})]})}var Is=Cy(({data:e,selected:t,id:o})=>{let n=Qn(Qt),r=Qn(fr),s=Qn(mr),a=Qn(_s),l=Qn(ar);if(!e)return null;let i=e.config?.actionType||"",d=e.status,c=r[o],u=n&&i==="Generate Image"&&c?.output&&Iy(c.output);if(!i){let h=e.enabled===!1;return jt(Yn,{className:x("flex h-48 w-48 flex-col items-center justify-center shadow-none transition-all duration-150 ease-out",t&&"border-primary",h&&"opacity-50"),"data-testid":`action-node-${o}`,handles:{target:!0,source:!0},status:d,children:[h&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ne(oc,{className:"size-3.5 text-white"})}),jt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Ne(ac,{className:"size-12 text-muted-foreground",strokeWidth:1.5}),jt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ne(Jn,{className:"text-base",children:e.label||"Action"}),Ne(Xn,{className:"text-xs",children:"Select an action"})]})]})]})}let p=pe(i),g=e.label||p?.label||i,C=e.description||Sy(i),v=Py(i),y=s.has(o),w=e.config?.integrationId,k=w&&a.has(w),f=l&&v&&!k&&!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 jt(Yn,{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:d,children:[A&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-gray-500/50 p-1",children:Ne(oc,{className:"size-3.5 text-white"})}),!A&&f&&Ne("div",{className:"absolute top-2 left-2 rounded-full bg-orange-500/50 p-1",children:Ne(wy,{className:"size-3.5 text-white"})}),Ne(Dy,{status:d}),jt("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[u?Ne(Oy,{base64:c.output.base64}):Ey(i),jt("div",{className:"flex flex-col items-center gap-1 text-center",children:[Ne(Jn,{className:"text-base",children:g}),C&&Ne(Xn,{className:"text-xs",children:C}),I&&Ne(Ry,{model:I})]})]})]})});Is.displayName="ActionNode";import{Plus as My}from"lucide-react";import{jsx as xn,jsxs as da}from"react/jsx-runtime";function sc({data:e}){return da("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:[da("div",{className:"text-center",children:[xn("h1",{className:"mb-2 font-bold text-3xl",children:"AI Workflow Builder Template"}),da("p",{className:"text-muted-foreground text-sm",children:["Powered by"," ",xn("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"}),","," ",xn("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"}),","," ",xn("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"," ",xn("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"})]})]}),da(R,{className:"gap-2 shadow-lg",onClick:e.onClick,size:"default",children:[xn(My,{className:"size-4"}),"Add a Step"]})]})}import{Check as Fy,Clock as zy,Play as Wy,Webhook as By,XCircle as Vy}from"lucide-react";import{memo as Gy}from"react";import{jsx as Zn,jsxs as ca}from"react/jsx-runtime";var Ps=Gy(({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=Wy;return o==="Schedule"?a=zy:o==="Webhook"&&(a=By),ca(Yn,{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"&&ca("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"&&Zn(Fy,{className:"size-3.5 text-white",strokeWidth:2.5}),s==="error"&&Zn(Vy,{className:"size-3.5 text-white",strokeWidth:2.5})]}),ca("div",{className:"flex flex-col items-center justify-center gap-3 p-6",children:[Zn(a,{className:"size-12 text-blue-500",strokeWidth:1.5}),ca("div",{className:"flex flex-col items-center gap-1 text-center",children:[Zn(Jn,{className:"text-base",children:n}),r&&Zn(Xn,{className:"text-xs",children:r})]})]})]})});Ps.displayName="TriggerNode";import{useAtomValue as Hy,useSetAtom as er}from"jotai";import{Link2Off as _y,Plus as $y,Trash2 as Uy}from"lucide-react";import{nanoid as Ky}from"nanoid";import{useCallback as kn,useEffect as jy,useRef as qy}from"react";import{jsx as Nn,jsxs as dc}from"react/jsx-runtime";function ic({menuState:e,onClose:t}){let o=Hy(oe),n=er(eo),r=er(to),s=er(Vo),a=er(be),l=er(Ft),{open:i}=ne(),d=qy(null),c=kn(()=>{if(e?.nodeId){let v=e.nodeId;t(),i(Oe,{title:"Delete Step",message:"Are you sure you want to delete this node? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{n(v)}})}},[e,n,t,i]),u=kn(()=>{if(e?.edgeId){let v=e.edgeId;t(),i(Oe,{title:"Delete Connection",message:"Are you sure you want to delete this connection? This action cannot be undone.",confirmLabel:"Delete",confirmVariant:"destructive",onConfirm:()=>{r(v)}})}},[e,r,t,i]),p=kn(()=>{if(e?.flowPosition){let y={id:Ky(),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),l("properties")}t()},[e,s,a,l,t]);if(jy(()=>{if(!e)return;let v=k=>{d.current&&!d.current.contains(k.target)&&t()},y=k=>{k.key==="Escape"&&t()},w=setTimeout(()=>{document.addEventListener("mousedown",v),document.addEventListener("keydown",y)},0);return()=>{clearTimeout(w),document.removeEventListener("mousedown",v),document.removeEventListener("keydown",y)}},[e,t]),!e)return null;let g=!!(e.nodeId&&o.find(v=>v.id===e.nodeId)?.data.type==="trigger"),C=()=>e.nodeId&&o.find(y=>y.id===e.nodeId)?.data.label||"Step";return dc("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"&&Nn(Es,{disabled:g,icon:Nn(Uy,{className:"size-4"}),label:`Delete ${C()}`,onClick:c,variant:"destructive"}),e.type==="edge"&&Nn(Es,{icon:Nn(_y,{className:"size-4"}),label:"Delete Connection",onClick:u,variant:"destructive"}),e.type==="pane"&&Nn(Es,{icon:Nn($y,{className:"size-4"}),label:"Add Step",onClick:p})]})}function Es({icon:e,label:t,onClick:o,variant:n="default",disabled:r}){return dc("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 lc(e,t){let o=kn((s,a)=>{s.preventDefault(),t({type:"node",position:{x:s.clientX,y:s.clientY},nodeId:a.id})},[t]),n=kn((s,a)=>{s.preventDefault(),t({type:"edge",position:{x:s.clientX,y:s.clientY},edgeId:a.id})},[t]),r=kn(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 Mo,jsxs as uc}from"react/jsx-runtime";var tv=[{type:"trigger",label:"",description:"",displayLabel:"Trigger",icon:Zy,defaultConfig:{triggerType:"Manual"}},{type:"action",label:"",description:"",displayLabel:"Action",icon:ev,defaultConfig:{}}],ov={animated:As.Animated,temporary:As.Temporary};function mc(){let[e,t]=tr(oe),[o,n]=tr(ue),[r]=tr(wt),s=Ds($e),[a]=tr(ir),l=Ds(lr),i=Ds(dr),[d,c]=tr(ur),u=go(qs),p=go(Ys),g=go(be),C=go(_e),v=go(Vo),y=go(tt),w=go(Lt),k=go(Ft),{screenToFlowPosition:f,fitView:T,getViewport:I,setViewport:A}=Xy(),h=Lo(null),m=Lo(null),S=Lo(!1),X=Lo(!1),[le,L]=cc(!1),[F,_]=cc(null),{onNodeContextMenu:P,onEdgeContextMenu:V,onPaneContextMenu:Y}=lc(f,_),M=bt(()=>{_(null)},[]),K=Lo(void 0),N=e.some(Q=>Q.type!=="add"),z=Lo(!1),b=Lo(!1);ua(()=>{if(d&&!b.current){if(b.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})}},[d,I,A]),ua(()=>{if(K.current!==s){if(d&&X.current){K.current=s,L(!0),c(!1);return}setTimeout(()=>{T({maxZoom:1,minZoom:.5,padding:.2,duration:0}),K.current=s,X.current=!0,L(!0),c(!1)},0)}},[s,T,d,c]),ua(()=>{s||(N&&!z.current?(z.current=!0,setTimeout(()=>{T({maxZoom:1,minZoom:.5,padding:.2,duration:0}),X.current=!0,L(!0)},0)):N||(z.current=!1))},[s,N,T]),ua(()=>{let Q=E=>{(E.metaKey||E.ctrlKey)&&E.key==="/"&&(E.preventDefault(),T({padding:.2,duration:300}))};return window.addEventListener("keydown",Q),()=>{window.removeEventListener("keydown",Q)}},[T]);let D=Qy(()=>({trigger:Ps,action:Is,add:sc}),[]),G=bt((Q,E)=>{let $=e.find(J=>J.id===Q);return!$||$.type==="add"?!1:E==="target"?$.type!=="trigger":!0},[e]),te=bt(Q=>!(!(Q.source&&Q.target)||Q.source===Q.target),[]),de=bt(Q=>{let E={id:Rs(),...Q,type:"animated"};n([...o,E]),y(!0),w({immediate:!0})},[o,n,y,w]),B=bt((Q,E)=>{g(E.id)},[g]),xe=bt((Q,E)=>{h.current=E.nodeId,m.current=E.handleType},[]),qe=bt(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=bt((Q,E,$)=>{let J=Q.target.closest(".react-flow")?.getBoundingClientRect(),ce=J?E-J.left:E,Ee=J?$-J.top:$;return{adjustedX:ce,adjustedY:Ee}},[]),He=bt(Q=>{let E=Q.getAttribute("data-id"),$=m.current==="source",J=$?"target":"source",ce=h.current;E&&ce&&E!==ce&&G(E,J)&&de({source:$?ce:E,target:$?E:ce,sourceHandle:null,targetHandle:null})},[G,de]),qt=bt((Q,E,$)=>{let J=h.current;if(!J)return;let{adjustedX:ce,adjustedY:Ee}=Ye(Q,E,$),Re=tv.find(pa=>pa.type==="action");if(!Re)return;let Cn=f({x:ce,y:Ee}),ma=192;Cn.y-=ma/2;let Tn={id:Rs(),type:Re.type,position:Cn,data:{label:Re.label,description:Re.description,type:Re.type,config:Re.defaultConfig,status:"idle"},selected:!0};v(Tn),g(Tn.id),k("properties"),setTimeout(()=>{t(pa=>pa.map(Ls=>({...Ls,selected:Ls.id===Tn.id})))},50);let Os=m.current==="source",wc={id:Rs(),source:Os?J:Tn.id,target:Os?Tn.id:J,type:"animated"};n([...o,wc]),y(!0),w({immediate:!0}),S.current=!0,setTimeout(()=>{S.current=!1},100)},[Ye,f,v,o,n,t,g,k,y,w]),St=bt(Q=>{if(!h.current)return;let{clientX:E,clientY:$}=qe(Q),J="changedTouches"in Q?document.elementFromPoint(E,$):Q.target;if(!J){h.current=null;return}let ce=J.closest(".react-flow__node"),Ee=J.closest(".react-flow__handle");if(ce&&!Ee&&m.current){He(ce),h.current=null,m.current=null;return}ce||Ee||qt(Q,E,$),h.current=null,m.current=null},[qe,He,qt]),ee=bt(()=>{S.current||(g(null),C(null),M())},[g,C,M]),ve=bt(({nodes:Q})=>{S.current&&Q.length===0||(Q.length===0?g(null):Q.length===1&&g(Q[0].id))},[g]);return uc("div",{className:"relative h-full bg-background","data-testid":"workflow-canvas",style:{opacity:le?1:0,width:l?`calc(100% - ${l})`:"100%",transition:i?"width 300ms ease-out, opacity 300ms":"opacity 300ms"},children:[Mo("div",{className:"pointer-events-auto",children:Mo(qd,{workflowId:s??void 0})}),uc(Ul,{className:"bg-background",connectionLineComponent:jl,connectionMode:Yy.Strict,edges:o,edgeTypes:ov,elementsSelectable:!r,isValidConnection:te,nodes:e,nodesConnectable:!r,nodesDraggable:!r,nodeTypes:D,onConnect:r?void 0:de,onConnectEnd:r?void 0:St,onConnectStart:r?void 0:xe,onEdgeContextMenu:r?void 0:V,onEdgesChange:r?void 0:p,onNodeClick:r?void 0:B,onNodeContextMenu:r?void 0:P,onNodesChange:r?void 0:u,onPaneClick:ee,onPaneContextMenu:r?void 0:Y,onSelectionChange:r?void 0:ve,children:[Mo(Xr,{className:"workflow-controls-panel border-none bg-transparent p-0",position:"bottom-right",children:Mo(ql,{})}),a&&Mo(Jy,{bgColor:"var(--sidebar)",nodeStrokeColor:"var(--border)"})]}),s&&Mo(Xl,{workflowId:s}),Mo(ic,{menuState:F,onClose:M})]})}import{jsx as pc}from"react/jsx-runtime";function fc(){let e=nv();return e==="/"||e.startsWith("/workflows/")?pc("div",{className:"fixed inset-0 z-0",children:pc(mc,{})}):null}import{AuthUIProvider as rv}from"@daveyplate/better-auth-ui";import av from"next/link";import{useRouter as sv}from"next/navigation";import{jsx as iv}from"react/jsx-runtime";var gc=e=>{let t=sv(),{children:o,...n}=e;return iv(rv,{...n,authClient:Eo,navigate:t.push,replace:t.replace,onSessionChange:()=>{t.refresh()},Link:av,children:o})};import{ThemeProvider as lv}from"next-themes";import{jsx as dv}from"react/jsx-runtime";var yc=({children:e,...t})=>dv(lv,{...t,children:e});import{jsx as yo,jsxs as vc}from"react/jsx-runtime";function mv(e){return Ci(),vc(Di,{children:[yo(hc.Suspense,{children:vc(cv,{children:[yo(fc,{}),e.children]})}),yo($l,{}),yo(_l,{})]})}var bc=e=>{let{children:t,...o}=e;return yo(yc,{attribute:"class",defaultTheme:"system",disableTransitionOnChange:!0,enableSystem:!0,children:yo(gc,{...o,children:yo(uv,{children:yo(mv,{children:t})})})})};import{jsx as fv}from"react/jsx-runtime";var pv=e=>{let{children:t,...o}=e;return fv(bc,{...o,children:t})};function gv(){return process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}function yv(){return typeof window>"u"?process.env.AI_GATEWAY_MANAGED_KEYS_ENABLED==="true":process.env.NEXT_PUBLIC_AI_GATEWAY_MANAGED_KEYS_ENABLED==="true"}export{pv as Layout,es as WorkflowEditor,Jp as WorkflowPage,gv as isAiGatewayManagedKeysEnabled,yv as isAiGatewayManagedKeysEnabledClient};
|