@w6w/ui 0.2.69 → 0.2.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/flow.cjs CHANGED
@@ -1,9 +1,9 @@
1
- "use client";"use strict";var bo=Object.defineProperty;var jo=(t,s,o)=>s in t?bo(t,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[s]=o;var lt=(t,s,o)=>jo(t,typeof s!="symbol"?s+"":s,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),le=require("@xyflow/react"),u=require("react"),i=require("./connection-app-meta-ChRGxZex.cjs"),be=require("./CodeBlock-85y9qvE3.cjs"),Re=require("@w6w/expr");function vo({x:t,y:s,items:o,onAction:n,onClose:r}){const l=u.useRef(null),[c,p]=u.useState({left:t,top:s});u.useLayoutEffect(()=>{const x=l.current,h=x==null?void 0:x.offsetParent;if(!x||!h)return;const m=x.offsetWidth,k=x.offsetHeight;p({left:t+m>h.clientWidth?Math.max(0,t-m):t,top:s+k>h.clientHeight?Math.max(0,s-k):s})},[t,s]),u.useEffect(()=>{var x,h;(h=(x=l.current)==null?void 0:x.querySelector("[role=menuitem]"))==null||h.focus({preventScroll:!0})},[]),u.useEffect(()=>{const x=k=>{var j;(j=l.current)!=null&&j.contains(k.target)||r(!1)},h=k=>{var j;(j=l.current)!=null&&j.contains(k.target)||r(!1)},m=()=>r(!1);return document.addEventListener("pointerdown",x,!0),document.addEventListener("scroll",h,!0),document.addEventListener("wheel",h,{capture:!0,passive:!0}),window.addEventListener("blur",m),window.addEventListener("resize",m),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("scroll",h,!0),document.removeEventListener("wheel",h,!0),window.removeEventListener("blur",m),window.removeEventListener("resize",m)}},[r]);const d=x=>{x.disabled||(r(!1),n(x.action))};return e.jsx("div",{ref:l,className:"w6w-note-menu w6w-canvas-menu",role:"menu","aria-label":"Canvas actions","data-testid":"canvas-context-menu",style:{left:c.left,top:c.top},onContextMenu:x=>x.preventDefault(),onKeyDown:x=>{var j;x.stopPropagation();const h=[...((j=l.current)==null?void 0:j.querySelectorAll("[role=menuitem]"))??[]],m=h.indexOf(document.activeElement),k=y=>{var C;return(C=h[(y+h.length)%h.length])==null?void 0:C.focus()};if(x.key==="ArrowDown")k(m+1);else if(x.key==="ArrowUp")k(m<0?-1:m-1);else if(x.key==="Home")k(0);else if(x.key==="End")k(-1);else if(x.key==="Escape"||x.key==="Tab")r(!0);else if(x.key==="Enter"||x.key===" ")m>=0&&d(o[m]);else return;x.preventDefault()},children:o.map(x=>e.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":x.disabled||void 0,className:`w6w-note-menu-item${x.danger?" danger":""}${x.separated?" separated":""}`,"data-action":x.action,onClick:()=>d(x),children:x.label},x.action))})}const rn=i.customCssTemplate();function yo({value:t,onChange:s,readOnly:o,stepId:n}){const r=u.useMemo(()=>Co(t),[t]),l=u.useMemo(()=>{var N;return r?((N=i.parseFormDefinition(r))==null?void 0:N.problems)??[]:[]},[r]),[c,p]=u.useState(null),[d,x]=u.useState(null),[h,m]=u.useState(null),[k,j]=u.useState(0);if(!r)return e.jsxs("div",{className:"w6w-result w6w-error",children:["This form is not a form definition (it may be set by an expression). Edit it in the Parameters code view, or reset it.",!o&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-sm",onClick:()=>s(i.defaultFormDefinition()),children:"Reset to a starter form"})})]});const y=r.fields,C=N=>s({...r,...N}),A=N=>C({fields:N}),w=N=>new Set(y.filter(g=>g.id!==N&&g.name).map(g=>g.name)),D=(N,g)=>{const P=y.find(ie=>ie.id===N);if(!P)return;let X=ko({...P,...g});if(g.label!==void 0&&i.isInputField(P.type)){const ie=w(N),te=i.uniqueName(i.slugName(P.label??""),ie);(!P.name||P.name===te)&&(X={...X,name:i.uniqueName(i.slugName(g.label||P.type),ie)})}const B=P.name&&X.name!==P.name?P.name:null;A(y.map(ie=>{var te;return ie.id===N?X:B&&((te=ie.showIf)==null?void 0:te.field)===B&&X.name?{...ie,showIf:{...ie.showIf,field:X.name}}:ie}))},$=(N,g=y.length)=>{const P=an(y),X=i.newField(N,P,w()),B=[...y];B.splice(g,0,X),A(B),p(P)},M=(N,g)=>{const P=y.findIndex(te=>te.id===N);if(P<0)return;const X=g>P?g-1:g;if(X===P||X<0||X>=y.length)return;const B=[...y],[ie]=B.splice(P,1);B.splice(X,0,ie),A(B)},R=N=>{const g=an(y),P={...structuredClone(N),id:g};P.name&&(P.name=i.uniqueName(P.name,w()));const X=y.findIndex(ie=>ie.id===N.id)+1,B=[...y];B.splice(X,0,P),A(B),p(g)},L=()=>{x(null),m(null)},E=(N,g)=>{if(N.preventDefault(),o)return L();d&&M(d,g),L()},z=(N,g)=>{if(o||!d)return;N.preventDefault(),N.dataTransfer.dropEffect="move";const P=N.currentTarget.getBoundingClientRect();m(N.clientY>P.top+P.height/2?g+1:g)},Y=y.filter(N=>i.isInputField(N.type)&&N.name);return e.jsxs("div",{className:"w6w-form-builder","data-testid":"form-builder",children:[l.length>0&&e.jsx("ul",{className:"w6w-form-problems","data-testid":"form-problems",children:l.map(N=>e.jsxs("li",{children:[e.jsx(be.Icon,{name:"warning",size:12})," ",N.fieldId?e.jsx("button",{type:"button",className:"w6w-form-problem-link",onClick:()=>p(N.fieldId??null),children:N.message}):N.message]},`${N.fieldId??"form"}:${N.message}`))}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Form title"}),e.jsx("input",{type:"text",value:r.title??"",disabled:o,"aria-label":"Form title",onChange:N=>C({title:N.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Description"}),e.jsx("textarea",{rows:2,value:r.description??"",disabled:o,"aria-label":"Form description",onChange:N=>C({description:N.target.value||void 0})})]}),e.jsxs("div",{className:"w6w-form-section-label",children:["Fields ",e.jsx("span",{className:"w6w-muted",children:"· drag to reorder"})]}),e.jsxs("div",{className:"w6w-form-fields","data-testid":"form-fields",onDragLeave:N=>{N.currentTarget.contains(N.relatedTarget)||m(null)},children:[y.length===0&&e.jsx("div",{className:`w6w-form-empty${h===0?" is-drop-target":""}`,onDragOver:N=>{o||!d||(N.preventDefault(),m(0))},onDrop:N=>E(N,0),children:"No fields yet. Add one below."}),y.map((N,g)=>{const P=c===N.id,X=["w6w-form-field",P?"is-open":"",d===N.id?"is-dragging":"",h===g?"is-drop-before":"",h===g+1&&g===y.length-1?"is-drop-after":"",N.type==="pageBreak"?"is-page-break":""].filter(Boolean).join(" ");return e.jsxs("div",{className:X,"data-field-id":N.id,onDragOver:B=>z(B,g),onDrop:B=>E(B,h??g),children:[e.jsxs("div",{className:"w6w-form-field-head",children:[e.jsx("button",{type:"button",className:"w6w-icon-btn w6w-router-grip",draggable:!o,disabled:o,"aria-label":`Reorder ${_t(N)}`,title:"Drag to reorder · arrow keys to move",onDragStart:B=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",N.id);const ie=B.currentTarget.closest(".w6w-form-field");ie&&B.dataTransfer.setDragImage(ie,16,16),x(N.id)},onDragEnd:L,onKeyDown:B=>{B.key!=="ArrowUp"&&B.key!=="ArrowDown"||(B.preventDefault(),M(N.id,B.key==="ArrowUp"?g-1:g+2))},children:e.jsx(be.Icon,{name:"grip",size:14})}),e.jsxs("button",{type:"button",className:"w6w-form-field-summary","aria-expanded":P,onClick:()=>p(P?null:N.id),children:[e.jsx("span",{className:"w6w-form-field-type",children:i.FIELD_TYPE_LABELS[N.type]}),e.jsxs("span",{className:"w6w-form-field-label",children:[_t(N),N.required?e.jsx("span",{className:"w6w-form-req",children:" *"}):null]}),N.name&&i.isInputField(N.type)&&e.jsx("code",{className:"w6w-form-field-name",children:N.name}),N.showIf&&e.jsx("span",{className:"w6w-form-field-badge",title:"Shown only when a condition holds",children:"if"}),e.jsx(be.Icon,{name:"chevron-down",size:12})]}),!o&&e.jsx(i.IconButton,{label:`Duplicate ${_t(N)}`,icon:"copy",onClick:()=>R(N)}),e.jsx(i.DeleteButton,{label:`Remove ${_t(N)}`,disabled:o,onClick:()=>A(y.filter(B=>B.id!==N.id))})]}),P&&e.jsx(Ao,{field:N,earlier:Y.filter(B=>y.indexOf(B)<g&&B.id!==N.id),readOnly:o,stepId:n,onPatch:B=>D(N.id,B)})]},N.id)})]}),!o&&e.jsx(i.Combobox,{className:"w6w-form-add",mode:"combobox","aria-label":"Add a field",placeholder:"+ Add a field…",options:No,value:"",onChange:N=>{$(N),j(g=>g+1)}},k),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Submit button label"}),e.jsx("input",{type:"text",value:r.submitLabel??"",placeholder:"Submit",disabled:o,"aria-label":"Submit button label",onChange:N=>C({submitLabel:N.target.value||void 0})})]}),e.jsx(Po,{form:r,save:C,readOnly:o}),e.jsx(Lo,{form:r,save:C,readOnly:o})]})}const So=[{title:"Text",types:["text","textarea","email","number","phone","url","password"]},{title:"Choice",types:["select","radio","checkboxes","checkbox","rating"]},{title:"Date & time",types:["date","time","datetime"]},{title:"Other",types:["file","hidden"]},{title:"Layout",types:["heading","paragraph","pageBreak"]}],No=So.flatMap(t=>t.types.map(s=>({value:s,label:i.FIELD_TYPE_LABELS[s],group:t.title,keywords:`${t.title} ${s}`})));function Co(t){if(t==null||t==="")return i.defaultFormDefinition();let s=t;if(typeof s=="string")try{s=JSON.parse(s)}catch{return null}if(!s||typeof s!="object"||Array.isArray(s))return null;const o=s;if(!Array.isArray(o.fields))return null;if(o.fields.every(r=>r&&typeof r.id=="string"&&r.id))return o;const n=new Set;return{...o,fields:o.fields.filter(r=>r&&typeof r=="object").map((r,l)=>{let c=typeof r.id=="string"&&r.id&&!n.has(r.id)?r.id:`f_${l+1}`;for(;n.has(c);)c=`${c}_`;return n.add(c),{...r,id:c}})}}function an(t){const s=new Set(t.map(o=>o.id));for(;;){const o=`f_${Math.random().toString(36).slice(2,8)}`;if(!s.has(o))return o}}function ko(t){const s={};for(const[o,n]of Object.entries(t))n===void 0||n===""||(s[o]=n);return s}function _t(t){return t.type==="pageBreak"?t.label?`New page: ${t.label}`:"New page":t.type==="paragraph"?Eo(t.help??"")||"Paragraph":t.label||t.name||i.FIELD_TYPE_LABELS[t.type]}function Eo(t,s=60){return t.length>s?`${t.slice(0,s-1)}…`:t}const To=t=>{if(t.trim()==="")return;const s=Number(t);return Number.isFinite(s)?s:void 0},Io={equals:"is",notEquals:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",greaterThan:"is greater than",lessThan:"is less than"};function Ao({field:t,earlier:s,readOnly:o,stepId:n,onPatch:r}){const l=t.type,c=i.isInputField(l),p=i.CHOICE_FIELD_TYPES.has(l),d=i.TEXT_FIELD_TYPES.has(l),x=l==="checkboxes"||l==="select"&&t.multiple,h=(j,y,C={})=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:j}),C.area?e.jsx("textarea",{rows:3,value:String(t[y]??""),placeholder:C.placeholder,disabled:o,"aria-label":j,onChange:A=>r({[y]:A.target.value||void 0})}):e.jsx("input",{type:"text",value:String(t[y]??""),placeholder:C.placeholder,disabled:o,"aria-label":j,onChange:A=>r({[y]:A.target.value||void 0})}),C.hint&&e.jsx("span",{className:"w6w-hint",children:C.hint})]},String(y)),m=(j,y,C)=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:j}),e.jsx("input",{type:"number",value:t[y]===void 0?"":String(t[y]),placeholder:C,disabled:o,"aria-label":j,onChange:A=>r({[y]:To(A.target.value)})})]},String(y)),k=(j,y)=>e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!t[y],disabled:o,onChange:C=>r({[y]:C.target.checked||void 0})}),j]},String(y));return l==="pageBreak"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Next page title","label",{placeholder:"Optional"}),e.jsx("span",{className:"w6w-hint",children:"Everything below this starts a new page with Back / Next."})]}):l==="heading"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Heading","label"),h("Text under the heading","help",{area:!0}),e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]}):l==="paragraph"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Text","help",{area:!0}),e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]}):e.jsxs("div",{className:"w6w-form-field-body",children:[e.jsxs("div",{className:"w6w-field-row",children:[h(l==="hidden"?"Description":"Label","label"),h("Answer key","name",{hint:t.name?e.jsxs(e.Fragment,{children:["Use as ",e.jsx("code",{children:`{{ nodes.${n??"<trigger>"}.output.data.${t.name} }}`})]}):"Letters, digits and _."})]}),l==="hidden"?h("Value","defaultValue",{hint:"Recorded with every response. A ?name=value in the form URL overrides it."}):e.jsxs(e.Fragment,{children:[h("Help text","help",{placeholder:"Shown under the label"}),(d||l==="number"||l==="select")&&h("Placeholder","placeholder"),e.jsxs("div",{className:"w6w-form-checks",children:[c&&k("Required","required"),l==="select"&&k("Allow several choices","multiple"),p&&k('Offer an "Other" answer',"allowOther"),l==="file"&&k("Allow several files","multiple"),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:t.width==="half",disabled:o,onChange:j=>r({width:j.target.checked?"half":void 0})}),"Half width"]})]})]}),p&&e.jsxs("div",{className:"w6w-form-options","data-testid":"form-choices",children:[e.jsx(ln,{label:"Choices",modes:[["fixed","Fixed list"],["data","From data"]],value:t.optionsFrom?"data":"fixed",readOnly:o,onChange:j=>r({optionsFrom:j==="data"?{items:""}:void 0})}),t.optionsFrom?e.jsx(cn,{source:t.optionsFrom,withValue:!0,readOnly:o,onChange:j=>r({optionsFrom:j})}):e.jsx(Ro,{options:t.options??[],readOnly:o,onChange:j=>r({options:j})})]}),l==="text"&&e.jsxs("div",{className:"w6w-form-options","data-testid":"form-suggestions",children:[e.jsx(ln,{label:"Suggestions as they type",modes:[["none","None"],["fixed","Fixed list"],["data","From data"]],value:t.suggestionsFrom?"data":t.suggestions?"fixed":"none",readOnly:o,onChange:j=>r({suggestions:j==="fixed"?[]:void 0,suggestionsFrom:j==="data"?{items:""}:void 0})}),t.suggestionsFrom?e.jsx(cn,{source:t.suggestionsFrom,readOnly:o,onChange:j=>r({suggestionsFrom:j})}):t.suggestions?e.jsx("textarea",{rows:3,value:t.suggestions.join(`
2
- `),placeholder:"One per line",disabled:o,"aria-label":"Suggestions",onChange:j=>r({suggestions:j.target.value.split(`
3
- `)})}):null,(t.suggestions||t.suggestionsFrom)&&e.jsx("span",{className:"w6w-hint",children:"Offered as they type; any other answer is accepted too."})]}),d&&e.jsxs("div",{className:"w6w-field-row",children:[m("Min length","minLength"),m("Max length","maxLength")]}),d&&l!=="email"&&l!=="url"&&e.jsxs("div",{className:"w6w-field-row",children:[h("Pattern (regular expression)","pattern",{placeholder:"e.g. [A-Z]{2}\\d{4}"}),t.pattern&&h("Message when it does not match","patternMessage")]}),l==="textarea"&&m("Rows","rows","4"),l==="number"&&e.jsxs("div",{className:"w6w-field-row",children:[m("Min","min"),m("Max","max"),m("Step","step","any")]}),l==="rating"&&m("Stars","max","5"),(l==="date"||l==="time"||l==="datetime")&&e.jsxs("div",{className:"w6w-field-row",children:[h("Earliest","minDate",{placeholder:dn(l)}),h("Latest","maxDate",{placeholder:dn(l)})]}),x&&e.jsxs("div",{className:"w6w-field-row",children:[m("Pick at least","minSelected"),m("Pick at most","maxSelected")]}),l==="file"&&e.jsxs("div",{className:"w6w-field-row",children:[h("Accepted types","accept",{placeholder:".pdf,image/*"}),m("Max size per file (MB)","maxFileSizeMb","10"),t.multiple&&m("Max files","maxFiles")]}),l!=="hidden"&&l!=="file"&&l!=="checkboxes"&&l!=="checkbox"&&!x&&h("Default answer","defaultValue",{hint:e.jsxs(e.Fragment,{children:["A ?name=value in the form URL overrides it. Can read a pre-form step, e.g."," ",e.jsx("code",{children:"{{ nodes.lookup.output.email }}"}),"."]})}),l==="checkbox"&&e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:t.defaultValue===!0,disabled:o,onChange:j=>r({defaultValue:j.target.checked||void 0})}),"Checked by default"]}),l!=="hidden"&&e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]})}function ln({label:t,modes:s,value:o,readOnly:n,onChange:r}){return e.jsxs("div",{className:"w6w-form-mode",children:[e.jsx("span",{className:"w6w-small w6w-muted",children:t}),e.jsx("div",{role:"group","aria-label":t,className:"w6w-form-mode-buttons",children:s.map(([l,c])=>e.jsx("button",{type:"button",className:`w6w-btn w6w-btn-sm w6w-btn-ghost${o===l?" active":""}`,"aria-pressed":o===l,disabled:n,onClick:()=>o!==l&&r(l),children:c},l))})]})}function cn({source:t,withValue:s,readOnly:o,onChange:n}){const r=(l,c,p)=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:c}),e.jsx("input",{type:"text",value:t[l]??"",placeholder:p,disabled:o,"aria-label":c,onChange:d=>n({...t,[l]:d.target.value||void 0})})]});return e.jsxs("div",{className:"w6w-stack","data-testid":"form-data-source",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"List"}),e.jsx(i.ExpressionInput,{value:typeof t.items=="string"?t.items:void 0,readOnly:o,placeholder:"{{ nodes.get_products.output.items }}","aria-label":"List",onChange:l=>n({...t,items:l})}),e.jsx("span",{className:"w6w-hint",children:"Wire a step into this form trigger: it runs each time the page opens, and this list is read from its output."})]}),e.jsxs("div",{className:"w6w-field-row",children:[r("label","Label key","label · name · title"),s&&r("value","Value key","value · id")]})]})}function dn(t){return t==="time"?"09:00":t==="datetime"?"2026-01-31T09:00":"2026-01-31"}function ss({field:t,earlier:s,readOnly:o,onPatch:n}){var p;const r=t.showIf;if(!r)return s.length===0||o?null:e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost w6w-btn-sm w6w-form-cond-add",onClick:()=>n({showIf:{field:s[s.length-1].name??"",op:"equals",value:""}}),children:"+ Show only when…"});const l=r.op!=="isEmpty"&&r.op!=="isNotEmpty",c=s.find(d=>d.name===r.field);return e.jsxs("div",{className:"w6w-form-cond","data-testid":"form-condition",children:[e.jsx("span",{className:"w6w-small",children:"Show only when"}),e.jsxs("select",{value:r.field,disabled:o,"aria-label":"Depends on",onChange:d=>n({showIf:{...r,field:d.target.value}}),children:[!c&&e.jsx("option",{value:r.field,children:r.field||"—"}),s.map(d=>e.jsx("option",{value:d.name,children:d.label||d.name},d.id))]}),e.jsx("select",{value:r.op,disabled:o,"aria-label":"Comparison",onChange:d=>n({showIf:{...r,op:d.target.value}}),children:i.CONDITION_OPS.map(d=>e.jsx("option",{value:d,children:Io[d]},d))}),l&&((p=c==null?void 0:c.options)!=null&&p.length?e.jsxs("select",{value:r.value??"",disabled:o,"aria-label":"Value",onChange:d=>n({showIf:{...r,value:d.target.value}}),children:[e.jsx("option",{value:"",children:"—"}),c.options.map(d=>e.jsx("option",{value:d.value||d.label,children:d.label},d.value??d.label))]}):e.jsx("input",{type:"text",value:r.value??"",disabled:o,"aria-label":"Value",placeholder:(c==null?void 0:c.type)==="checkbox"?"true":"value",onChange:d=>n({showIf:{...r,value:d.target.value}})})),e.jsx(i.DeleteButton,{label:"Remove condition",disabled:o,onClick:()=>n({showIf:void 0})})]})}function Ro({options:t,readOnly:s,onChange:o}){const[n,r]=u.useState(null),[l,c]=u.useState(null),p=(x,h)=>{if(h<0||h>=t.length||x===h)return;const m=[...t],[k]=m.splice(x,1);m.splice(h,0,k),o(m)},d=(x,h)=>o(t.map((m,k)=>{if(k!==x)return m;const{value:j,...y}={...m,...h};return j?{...y,value:j}:y}));return e.jsxs("div",{className:"w6w-form-options","data-testid":"form-options",children:[e.jsx("span",{className:"w6w-small w6w-muted",children:"Options · the value is recorded (defaults to the label)"}),t.map((x,h)=>e.jsxs("div",{className:`w6w-form-option${n===h?" is-dragging":""}${l===h?" is-drop-before":""}`,onDragOver:m=>{s||n===null||n===h||(m.preventDefault(),c(h))},onDrop:m=>{m.preventDefault(),n!==null&&p(n,h),r(null),c(null)},children:[e.jsx("button",{type:"button",className:"w6w-icon-btn w6w-router-grip",draggable:!s,disabled:s,"aria-label":`Reorder option ${x.label}`,title:"Drag to reorder · arrow keys to move",onDragStart:m=>{m.dataTransfer.effectAllowed="move",m.dataTransfer.setData("text/plain",String(h)),r(h)},onDragEnd:()=>{r(null),c(null)},onKeyDown:m=>{m.key!=="ArrowUp"&&m.key!=="ArrowDown"||(m.preventDefault(),p(h,h+(m.key==="ArrowUp"?-1:1)))},children:e.jsx(be.Icon,{name:"grip",size:12})}),e.jsx("input",{type:"text",value:x.label,disabled:s,"aria-label":`Option ${h+1} label`,onChange:m=>d(h,{label:m.target.value})}),e.jsx("input",{type:"text",value:x.value??"",placeholder:x.label,disabled:s,"aria-label":`Option ${h+1} value`,onChange:m=>d(h,{value:m.target.value})}),e.jsx(i.DeleteButton,{label:`Remove option ${x.label}`,disabled:s,onClick:()=>o(t.filter((m,k)=>k!==h))})]},h)),!s&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost w6w-btn-sm w6w-router-add",onClick:()=>{let x=t.length+1;for(;t.some(h=>h.label===`Option ${x}`);)x++;o([...t,{label:`Option ${x}`}])},children:"+ Add option"})]})}function Po({form:t,save:s,readOnly:o}){const n=t.completion??{},r=c=>{const p={...n,...c};for(const d of Object.keys(p))(p[d]===void 0||p[d]==="")&&delete p[d];s({completion:p})},l=n.type==="redirect";return e.jsxs("details",{className:"w6w-section w6w-form-group","data-testid":"form-completion",children:[e.jsxs("summary",{className:"w6w-section-summary",children:[e.jsx("span",{className:"w6w-section-title",children:"After submitting"}),e.jsx("span",{className:"w6w-section-subtitle",children:l?`Redirect to ${n.redirectUrl||"…"}`:n.title||"Thank-you message"})]}),e.jsxs("div",{className:"w6w-form-group-body",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Show"}),e.jsxs("select",{value:l?"redirect":"message",disabled:o,"aria-label":"Completion",onChange:c=>r({type:c.target.value}),children:[e.jsx("option",{value:"message",children:"A thank-you message"}),e.jsx("option",{value:"redirect",children:"Redirect to a URL"})]})]}),l?e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Redirect URL"}),e.jsx("input",{type:"text",value:n.redirectUrl??"",placeholder:"https://example.com/thanks?email={{email}}",disabled:o,"aria-label":"Redirect URL",onChange:c=>r({redirectUrl:c.target.value})}),e.jsxs("span",{className:"w6w-hint",children:[e.jsx("code",{children:"{{name}}"})," inserts that answer (URL-encoded)."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Title"}),e.jsx("input",{type:"text",value:n.title??"",placeholder:"Thank you!",disabled:o,"aria-label":"Completion title",onChange:c=>r({title:c.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Message"}),e.jsx("textarea",{rows:2,value:n.message??"",disabled:o,"aria-label":"Completion message",onChange:c=>r({message:c.target.value})}),e.jsxs("span",{className:"w6w-hint",children:[e.jsx("code",{children:"{{name}}"})," inserts that answer. With “Wait for the workflow to finish”, a Respond to Webhook step can replace this screen."]})]}),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.allowAnother,disabled:o,onChange:c=>r({allowAnother:c.target.checked||void 0})}),"Offer “Submit another response”"]})]})]})]})}function Lo({form:t,save:s,readOnly:o}){const n=t.settings??{},r=c=>{const p={...n,...c};for(const d of Object.keys(p))(p[d]===void 0||p[d]==="")&&delete p[d];s({settings:p})},l=(c,p,d)=>e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:n[p]??d,disabled:o,onChange:x=>r({[p]:x.target.checked})}),c]});return e.jsxs("details",{className:"w6w-section w6w-form-group","data-testid":"form-settings",children:[e.jsxs("summary",{className:"w6w-section-summary",children:[e.jsx("span",{className:"w6w-section-title",children:"Page settings"}),e.jsxs("span",{className:"w6w-section-subtitle",children:[n.closed?"Closed":"Open"," · ",n.theme??"auto"," theme"]})]}),e.jsxs("div",{className:"w6w-form-group-body",children:[e.jsxs("div",{className:"w6w-form-checks",children:[l("Pre-fill from ?name=value in the URL","allowPrefill",!0),l("Show page progress","showProgress",!0),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.hideBranding,disabled:o,onChange:c=>r({hideBranding:c.target.checked||void 0})}),"Hide “Powered by w6w”"]})]}),e.jsxs("div",{className:"w6w-field-row",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Theme"}),e.jsxs("select",{value:n.theme??"auto",disabled:o,"aria-label":"Theme",onChange:c=>r({theme:c.target.value}),children:[e.jsx("option",{value:"auto",children:"Follow the visitor's system"}),e.jsx("option",{value:"light",children:"Light"}),e.jsx("option",{value:"dark",children:"Dark"})]})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Accent colour"}),e.jsxs("span",{className:"w6w-form-color",children:[e.jsx("input",{type:"color",value:/^#[0-9a-f]{6}$/i.test(n.accentColor??"")?n.accentColor:"#3355e6",disabled:o,"aria-label":"Accent colour picker",onChange:c=>r({accentColor:c.target.value})}),e.jsx("input",{type:"text",value:n.accentColor??"",placeholder:"#3355e6",disabled:o,"aria-label":"Accent colour",onChange:c=>r({accentColor:c.target.value})})]})]})]}),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.closed,disabled:o,onChange:c=>r({closed:c.target.checked||void 0})}),"Closed — stop accepting responses"]}),n.closed&&e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Closed message"}),e.jsx("input",{type:"text",value:n.closedMessage??"",placeholder:"This form is no longer accepting responses.",disabled:o,"aria-label":"Closed message",onChange:c=>r({closedMessage:c.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Custom CSS"}),e.jsx("textarea",{rows:8,className:"w6w-form-css",value:n.customCss??rn,spellCheck:!1,wrap:"off",disabled:o,"aria-label":"Custom CSS",onChange:c=>r({customCss:c.target.value===rn?void 0:c.target.value})})]})]})]})}function Fo(t,s,o,n){return t.find(r=>r.nodeId===s&&r.appId===o&&r.triggerKey===n)??null}function Do(t){return(t??"").split(`
4
- `).map(s=>s.trim().replace(/^(\d+[.)]|[-•*])\s+/,"")).filter(s=>s!=="")}function Mo({workflowId:t,nodeId:s,appId:o,triggerKey:n,appName:r,setup:l,connectionId:c,params:p,readOnly:d}){const x=i.useW6WApi(),[h,m]=u.useState(void 0),[k,j]=u.useState(null),y=u.useRef(null),C=JSON.stringify({connectionId:c,params:p});u.useEffect(()=>{const M=x.listSubscriptionsForWorkflow,R=x.createSubscription;if(!M){m(null);return}let L=!1;return m(void 0),j(null),y.current=null,(async()=>{const E=Fo(await M.call(x,t),s,o,n);if(d||!R||E&&E.status!=="pending")return E;const z=await R.call(x,o,n,{workflowId:t,connectionId:c,params:p,nodeId:s});return y.current=C,z})().then(E=>!L&&m(E)).catch(E=>{L||(m(null),j(E instanceof Error?E.message:String(E)))}),()=>{L=!0}},[x,t,s,o,n,d]);const A=(h==null?void 0:h.status)==="pending"?h.id:null;u.useEffect(()=>{const M=x.createSubscription;if(!A||d||!M||y.current===null||y.current===C)return;const R=setTimeout(()=>{y.current=C,M.call(x,o,n,{workflowId:t,connectionId:c,params:p,nodeId:s}).then(L=>{j(null),m(L)}).catch(L=>j(L instanceof Error?L.message:String(L)))},600);return()=>clearTimeout(R)},[x,A,d,C,o,n,t,s]);const w=h==null?void 0:h.webhookUrl,D=Do(l.instructions),$=(h==null?void 0:h.lastFireAt)??null;return e.jsxs("div",{className:"w6w-stack w6w-url-panel","data-testid":"manual-webhook-panel",children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:[e.jsx("strong",{children:"Webhook URL"})," — ",r," sends its events here."]}),k&&e.jsx("div",{className:"w6w-result w6w-error",children:k}),w?e.jsx("div",{className:"w6w-listen-url",children:e.jsx(be.Copyable,{value:w,readOnly:!0,children:e.jsx("input",{type:"text",readOnly:!0,value:w,"aria-label":"Webhook URL"})})}):h===void 0?e.jsx("p",{className:"w6w-muted w6w-small",children:"Getting the webhook URL…"}):!k&&e.jsx("p",{className:"w6w-muted w6w-small",children:"The webhook URL appears once the workflow is saved."}),e.jsxs("div",{className:"w6w-manual-webhook-note",role:"note","data-testid":"manual-webhook-note",children:[e.jsxs("strong",{children:["Add this URL in ",r," before the trigger works."]})," W6W can't add it for you, and nothing reaches this trigger until it is there."]}),D.length>0&&e.jsxs("div",{className:"w6w-manual-webhook-steps",children:[e.jsxs("span",{className:"w6w-small",children:["How to add it in ",r]}),e.jsx("ol",{className:"w6w-small","data-testid":"manual-webhook-steps",children:D.map((M,R)=>e.jsx("li",{children:M},R))})]}),h&&e.jsx("p",{className:"w6w-muted w6w-small","data-testid":"manual-webhook-status",children:$?`Last event received ${new Date($).toLocaleString()}.`:h.status==="registered"?`Listening. No event from ${r} yet.`:"Starts the workflow once it is published."})]})}function _o(t,s){return s===void 0?[...t]:t.includes(s)?[...t]:[s]}function Oo(t,s,o={}){const n=[],r=t.length;if(r>0){const l=r>1?` ${r} nodes`:"";n.push({action:"duplicate",label:`Duplicate${l}`,disabled:s}),r===1&&o.replaceableTrigger&&n.push({action:"replace-trigger",label:"Replace trigger",disabled:s}),n.push({action:"delete",label:`Delete${l}`,disabled:s,danger:!0})}return n.push({action:"add-node",label:"Add node",disabled:s,separated:r>0}),n.push({action:"add-trigger",label:"Add trigger",disabled:s}),n}const Tn=200,In=200,An=10240;function as(t){const s={};for(const[o,n]of Object.entries(t))s[o]=Math.round(n);return s}const $o=t=>!!t&&Number.isFinite(t.x)&&Number.isFinite(t.y),Wo=t=>!!t&&Number.isFinite(t.width)&&Number.isFinite(t.height);function un(t,s,o){return t&&t.map(n=>{const r=s==null?void 0:s[n.id],l=$o(r==null?void 0:r.position)?r.position:n.position,c=Wo(r==null?void 0:r.size)?r.size:n.size;return{...n,position:as(l),size:as(c)}})}function Rn(t,s,o){if(!s)return t;const n={...t};return t.notes&&(n.notes=un(t.notes,o)),t.sections&&(n.sections=un(t.sections,o)),n}function ms(t,s){return t.sections?{...t,sections:t.sections.map(o=>({...o,nodes:o.nodes.filter(n=>n!==s)}))}:t}function ls(t,s,o){return t.sections?{...t,sections:t.sections.map(n=>({...n,nodes:n.nodes.map(r=>r===s?o:r)}))}:t}function cs(t,s,o){if(!t.sections)return t;const n=new Set(o);return{...t,sections:t.sections.map(r=>{const l=r.nodes.filter(c=>!n.has(c));return r.id===s?{...r,nodes:[...new Set([...l,...o])]}:{...r,nodes:l}})}}function Pn(t,s){return(t.sections??[]).filter(o=>o.nodes.includes(s)).map(o=>o.id)}function Bo(t,s){const o=new TextEncoder;if(o.encode(t).length<=s)return t;let n="",r=0;for(const l of t){const c=o.encode(l).length;if(r+c>s)break;n+=l,r+=c}return n}function ds(t){const s={...t};return t.notes&&(s.notes=t.notes.slice(0,Tn).map(o=>({...o,content:Bo(o.content,An)}))),t.sections&&(s.sections=t.sections.slice(0,In)),s}function Vo(t,s,o){const n={};for(const c of[...t.notes??[],...t.sections??[]])n[c.id]={position:c.position,size:c.size};const r=(c,p)=>c==null?void 0:c.map(d=>{const x=p==null?void 0:p.find(h=>h.id===d.id);return x?{...d,position:x.position,size:x.size}:d}),l=o?t:{...t,...t.notes?{notes:r(t.notes,s==null?void 0:s.notes)}:{},...t.sections?{sections:r(t.sections,s==null?void 0:s.sections)}:{}};return Rn(l,o,n)}const pn=220;function zo(t){return t.length<=pn?{text:t,clipped:!1,length:t.length}:{text:t.slice(0,pn).trimEnd(),clipped:!0,length:t.length}}function Uo({params:t,values:s,testStartState:o,view:n="props",literalKeys:r}){const{sampleValues:l,nodeConfig:c,nodeMeta:p}=i.useExpressionOptions(),d=u.useMemo(()=>i.buildResolveScope(l,o,c,p),[l,o,c,p]),x=i.flattenParams(t),h=j=>{var y;return s[j]!==void 0?s[j]:(y=x.find(C=>C.key===j))==null?void 0:y.default},m=x.filter(j=>j.type!=="section"&&i.isParamVisible(j,h)).map(j=>Re.effectiveParam(j,h));if(i.hasParamCustomization(s)){const j=i.previewCustomization(s.$merge,d,r),y=j!==null&&typeof j=="object"&&!Array.isArray(j),C=fn(m,s,d,r);for(const[w,D]of Object.entries(s))w!=="$merge"&&(C[w]=r!=null&&r.includes(w)?D:i.previewCustomization(D,d));const A=y?{...C,...j}:C;return e.jsxs("div",{className:"w6w-resolved-params",children:[e.jsx("p",{className:"w6w-muted w6w-small",children:y?"JSON customization applied after form values.":`JSON customization is not available as an object in this preview (${String(j)}). Test the step to validate it.`}),n==="code"?e.jsx(i.JsonEditor,{value:JSON.stringify(A,null,2),onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":"Resolved test values (JSON)"}):e.jsx("div",{className:"w6w-resolved-table",children:Object.entries(A).map(([w,D])=>{var $;return e.jsx(us,{label:(($=x.find(M=>M.key===w))==null?void 0:$.label)??w,segments:[{status:"resolved",value:D}]},w)})})]})}if(n==="code"){const j=fn(m,s,d,r);return e.jsx("div",{className:"w6w-resolved-params",children:e.jsx(i.JsonEditor,{value:JSON.stringify(j,null,2),onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":"Resolved test values (JSON)"})})}const k=m.filter(j=>!i.deepEqual(h(j.key),j.default));return m.length===0?e.jsx("div",{className:"w6w-resolved-params",children:e.jsx("p",{className:"w6w-muted w6w-small",children:"This action takes no parameters."})}):k.length===0?e.jsx("div",{className:"w6w-resolved-params",children:e.jsx("p",{className:"w6w-muted w6w-small",children:"Every configured value matches its default — nothing to show here. Switch to JSON to see the full set."})}):e.jsx("div",{className:"w6w-resolved-params w6w-resolved-table",children:k.map(j=>j.type==="vars"?e.jsx(Ho,{param:j,value:s[j.key],scope:d},j.key):e.jsx(us,{label:j.label??j.key,segments:r!=null&&r.includes(j.key)?[{status:"resolved",value:h(j.key)}]:i.resolveParamValue(h(j.key),d)},j.key))})}function fn(t,s,o,n){const r={};for(const l of t)if(n!=null&&n.includes(l.key))r[l.key]=s[l.key]!==void 0?s[l.key]:l.default;else if(l.type==="vars"){const c=s[l.key]??l.default??[],p=i.dataVarRows(c);r[l.key]=p?i.resolveVarsJson(p,o):i.resolveParamJson(c,o)}else r[l.key]=i.resolveParamJson(s[l.key]!==void 0?s[l.key]:l.default,o);return r}function us({label:t,segments:s}){return e.jsxs("div",{className:"w6w-resolved-row",children:[e.jsx("span",{className:"w6w-resolved-label",children:t}),e.jsx("div",{className:"w6w-resolved-value",children:e.jsx(Ln,{segments:s})})]})}function Ho({param:t,value:s,scope:o}){const n=s??t.default??[],r=i.dataVarRows(n);return r===null?e.jsx(us,{label:t.label??t.key,segments:i.resolveParamValue(n,o)}):e.jsxs("div",{className:"w6w-resolved-row",children:[e.jsx("span",{className:"w6w-resolved-label",children:t.label??t.key}),r.length===0?e.jsx("p",{className:"w6w-muted w6w-small",children:"None configured."}):e.jsx("div",{className:"w6w-stack",children:r.map((l,c)=>e.jsxs("div",{className:"w6w-resolved-value",children:[e.jsx("code",{children:l.key||"(no key)"})," → ",e.jsx(Ln,{segments:i.resolveParamValue(l.value,o)})]},c))})]})}function Ln({segments:t}){return e.jsx(e.Fragment,{children:t.map((s,o)=>e.jsx(Jo,{segment:s},o))})}function Jo({segment:t}){switch(t.status){case"resolved":return t.ref?e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx(hn,{value:t.value})]}):e.jsx(hn,{value:t.value});case"unresolved":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx("span",{className:"w6w-param-unresolved",children:"unresolved"})]});case"at-run":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx("span",{className:"w6w-param-unevaluated",children:"resolved at run"})]});case"not-evaluated":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"expr"}),e.jsx("span",{className:"w6w-param-unevaluated",children:"not evaluated"})]});case"masked":return e.jsx(gt,{kind:"secret",refName:t.ref})}}function hn({value:t}){const[s,o]=u.useState(!1),n=Go(t),r=zo(n);return r.clipped?e.jsxs(e.Fragment,{children:[s?e.jsx(be.Copyable,{value:n,label:"Copy resolved value",className:"w6w-resolved-copy",children:e.jsx("pre",{className:"w6w-resolved-text-full",children:n})}):e.jsxs("span",{children:[r.text,"…"]}),e.jsx("button",{type:"button",className:"w6w-resolved-more","aria-expanded":s,onClick:()=>o(l=>!l),children:s?"Show less":`Show all (${r.length.toLocaleString()} characters)`})]}):e.jsx("span",{children:n})}const qo={var:"◆",secret:"🔒",expr:"ƒ"};function gt({kind:t,refName:s}){const o=t==="expr"?"expr":i.varLabel(s??"");return e.jsxs("span",{className:`w6w-expr-chip w6w-expr-chip-${t}`,children:[e.jsx("span",{className:"w6w-expr-chip-sigil",children:qo[t]}),e.jsx("span",{className:"w6w-expr-chip-label",children:o})]})}function Go(t){if(t===null)return"null";if(t===void 0)return"(not set)";if(t==="")return'""';if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t)}catch{return String(t)}}function Fn(t){return t.language==="python"||t.language==="typescript"?t.language:"javascript"}function Ko({enabled:t,values:s,onChange:o}){const[n,r]=u.useState(null),l=u.useRef(!1),c=typeof s.code=="string"?s.code:"";return u.useEffect(()=>{if(!t||l.current)return;l.current=!0;const p=i.convertCodeBindingsToReads(c,Fn(s));p.converted!==0&&(r({original:c,converted:p.converted}),o({...s,code:p.code}))},[t,c,s,o]),n?{converted:n.converted,undo:()=>{o({...s,code:n.original}),r(null)}}:null}function Yo({values:t,conversion:s,readOnly:o}){const n=typeof t.code=="string"?t.code:"",r=s,l=i.findCodeBindings(n,Fn(t)).length;return!r&&l===0?null:e.jsxs("output",{className:"w6w-hint w6w-script-converted",children:[r&&e.jsxs(e.Fragment,{children:["Converted ",r.converted," reference",r.converted===1?"":"s"," to code reads",!o&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("button",{type:"button",className:"w6w-script-converted-undo",onClick:r.undo,children:"Undo"})]}),l>0&&" · "]}),l>0&&e.jsxs(e.Fragment,{children:[l," ",e.jsx("code",{children:"{{ }}"})," left in the code stay",l===1?"s":""," literal text — read ",l===1?"it":"them"," from"," ",e.jsx("code",{children:"state"}),", or bind under Custom input"]})]})}function mn(t,s){return{nodeIds:t.filter(o=>o.selected).map(o=>o.id),edgeIds:s.filter(o=>o.selected).map(o=>o.id)}}function Xo(t,s,o,n){const r=new Set(i.withLoopClosers(t.nodeIds,s,o)),l=new Set(t.edgeIds),c=s.filter(m=>r.has(m.id)),p=[...c.filter(m=>i.isLoopOpener(m.data.step)),...c.filter(m=>!i.isLoopOpener(m.data.step))];let d=s,x=o,h=n;for(const m of p)x=i.bridgeDeletedBodyStep(m.id,d,x),d=d.filter(k=>k.id!==m.id),h=ms(h,m.id);return{nodes:d,edges:x.filter(m=>!l.has(m.id)),canvas:h}}function Zo(t,s,o){var p;const n=new Set(t.nodeIds),r=new Set(t.edgeIds),l=o.filter(d=>r.has(d.id)&&!n.has(d.source)&&!n.has(d.target)),c=[];if(n.size===1)c.push(i.deleteStepMessage(t.nodeIds[0],s,o));else if(n.size>1){c.push(`Delete nodes ${[...n].map(h=>`"${h}"`).join(", ")}? Their connections are removed too.`);const d=new Set,x=new Set(i.withLoopClosers([...n],s,o));for(const h of n)if(i.isLoopOpener((p=s.find(m=>m.id===h))==null?void 0:p.data.step))for(const m of i.loopBody(h,s,o))x.has(m)||d.add(m);d.size&&c.push(`Loop body steps ${[...d].map(h=>`"${h}"`).join(", ")} stay as standalone steps.`)}return l.length&&c.push(`Delete ${l.length===1?"connection":"connections"} ${l.map(d=>`"${d.source} → ${d.target}"`).join(", ")}?`),c.join(" ")}function Ot(t,s,o,n,r){const l=i.flowToWorkflow({...t,connections:n},s,o);return{nodes:l.nodes.map(({with:c,...p})=>c&&Object.keys(c).length?{...p,with:c}:p),edges:l.edges??[],connections:l.connections??{},canvas:r,positions:Object.fromEntries(s.map(c=>[c.id,c.position]))}}function Qo(t,s){const o=i.workflowToFlow({...t,...s});return{...o,nodes:o.nodes.map(n=>({...n,position:s.positions[n.id]??n.position}))}}class ei{constructor(s,o=100){lt(this,"past",[]);lt(this,"future",[]);lt(this,"present");lt(this,"group");lt(this,"limit");this.limit=o,this.present=JSON.stringify(s)}reset(s){this.present=JSON.stringify(s),this.past=[],this.future=[],this.group=void 0}record(s,o){const n=JSON.stringify(s);n!==this.present&&((!o||o!==this.group)&&(this.past.push(this.present),this.past.length>this.limit&&this.past.shift()),this.present=n,this.group=o,this.future=[])}mark(){return this.present}rollbackTo(s){if(this.present===s)return;const o=this.past.lastIndexOf(s);return o>=0&&(this.past.length=o),this.present=s,this.future=[],this.group=void 0,JSON.parse(s)}undo(){const s=this.past.pop();if(s!==void 0)return this.future.push(this.present),this.present=s,this.group=void 0,JSON.parse(s)}redo(){const s=this.future.pop();if(s!==void 0)return this.past.push(this.present),this.present=s,this.group=void 0,JSON.parse(s)}}function ns(t){var o;const s=t;return!!(s!=null&&s.isContentEditable||(o=s==null?void 0:s.closest)!=null&&o.call(s,'input, textarea, select, [contenteditable="true"], [contenteditable=""], [role="textbox"], .cm-editor'))}const ti=64,xt=24,tt=32;function $t(t){var s,o;return{width:((s=t.measured)==null?void 0:s.width)??t.width??200,height:((o=t.measured)==null?void 0:o.height)??t.height??64}}function si(t,s){return t.x<s.x+s.width&&t.x+t.width>s.x&&t.y<s.y+s.height&&t.y+t.height>s.y}function ni(t){const s=(r,l)=>{const c=new Map;for(const x of t){const h=x.position[r];c.set(h,Math.max(c.get(h)??0,$t(x)[l]))}const p=new Map;let d=Number.NEGATIVE_INFINITY;for(const[x,h]of[...c].sort(([m],[k])=>m-k)){const m=Math.max(x,d);p.set(x,m),d=m+h+ti}return p},o=s("x","width"),n=s("y","height");return t.map(r=>({...r,position:{x:o.get(r.position.x)??r.position.x,y:n.get(r.position.y)??r.position.y}}))}function oi(t,s,o){var p;const n=ni(i.relayoutNodes(t,s));if(!((p=o.sections)!=null&&p.length))return{nodes:n,canvas:o};const r=new Map(n.map(d=>[d.id,d])),l=(o.notes??[]).map(d=>({...d.position,...d.size}));for(const d of o.sections)d.nodes.some(x=>r.has(x))||l.push({...d.position,...d.size,y:d.position.y-tt,height:d.size.height+tt});const c=o.sections.map(d=>{const x=new Set(d.nodes),h=n.filter(D=>x.has(D.id));if(!h.length)return d;const m=Math.min(...h.map(D=>D.position.x))-xt,k=Math.min(...h.map(D=>D.position.y))-xt,j=Math.max(...h.map(D=>D.position.x+$t(D).width)),y=Math.max(...h.map(D=>D.position.y+$t(D).height)),C={x:m,y:k,width:j+xt-m,height:y+xt-k},A=[...l,...[...r.values()].filter(D=>!x.has(D.id)).map(D=>({...D.position,...$t(D)}))].sort((D,$)=>D.y-$.y);for(const D of A){const $={...C,y:C.y-tt,height:C.height+tt};si($,D)&&(C.y=D.y+D.height+xt+tt)}const w=C.y-k;for(const D of h)r.set(D.id,{...D,position:{x:D.position.x,y:D.position.y+w}});return l.push({...C,y:C.y-tt,height:C.height+tt}),{...d,position:{x:C.x,y:C.y},size:{width:C.width,height:C.height}}});return{nodes:n.map(d=>r.get(d.id)??d),canvas:{...o,sections:c}}}const os=6;function ii(t){let s=2166136261;for(let o=0;o<t.length;o++)s^=t.charCodeAt(o),s=Math.imul(s,16777619);return s>>>0}function ri(t){const s=new Map;let o=new Set;for(const n of[...new Set(t)].sort()){o.size===os&&(o=new Set);let r=ii(n)%os;for(;o.has(r);)r=(r+1)%os;o.add(r),s.set(n,r+1)}return s}function Bt(t){return`var(--w6w-loop-${t})`}function Dn(t,s){const o=[],n=new Set([t]);for(let r=s.get(t);r&&!n.has(r);r=s.get(r))n.add(r),o.unshift(r);return o}function ai(t,s,o){return s.size===0?t:t.map(n=>{var c;if(((c=n.data)==null?void 0:c.when)!=="each")return n;const r=n.sourceHandle===i.EACH_SOURCE_HANDLE?n.source:o.get(n.source),l=r?s.get(r):void 0;return l===void 0?n:{...n,style:{...n.style,"--w6w-loop-color":Bt(l)}}})}function li(t,s){const o=s.get(t);return o===void 0?void 0:{"--w6w-loop-color":Bt(o)}}function ci(t){const s=[];for(const o of t){const n=i.isLoopOpener(o.data.step);(n||o.data.loopOf)&&s.push([o.id,n?1:0,o.data.loopOf])}return JSON.stringify(s)}function di(t){const s=JSON.parse(t);return{tones:ri(s.filter(o=>o[1]===1).map(o=>o[0])),loopOf:new Map(s.map(o=>[o[0],o[2]]))}}const wn="Paused — test runs stop before this node",gn="Disabled — skipped in every run";function st(t){var s;return((s=t.ui)==null?void 0:s.paused)===!0}function We(t){return t.disabled===!0}function Mn(t,s){const{ui:o,...n}=t,{paused:r,...l}=o??{},c=s?{...l,paused:!0}:l;return Object.keys(c).length>0?{...n,ui:c}:n}function _n(t,s){const{disabled:o,...n}=t;return s?{...n,disabled:!0}:n}function ps(t,s){return t.filter(o=>o.id!==s&&st(o)).map(o=>o.id)}const ui=["nodes","steps"];function xn(t,s){for(const o of ui){const n=`${o}.${s}.output`;if(!t.startsWith(n))continue;const r=t.slice(n.length);if(r===""||r[0]==="."||r[0]==="[")return`foreach.item${r}`}return null}function Wt(t,s,o){if(typeof t=="string"){if(!t.includes("{{"))return t;const n=i.parseRootAnchoredTemplate(t);let r=!1;const l=n.map(c=>{if(c.kind!=="var"||c.ref===void 0)return c;const p=xn(c.ref,s);return p===null?c:(r=!0,o.includes(c.ref)||o.push(c.ref),{...c,ref:p})});return r?Re.serializeTemplate(l):t}if(i.isDollarPath(t)){const n=t.$;if(typeof n!="string")return t;const r=xn(n,s);return r===null?t:(o.includes(n)||o.push(n),{$:r})}if(Array.isArray(t)){let n=!1;const r=t.map(l=>{const c=Wt(l,s,o);return c!==l&&(n=!0),c});return n?r:t}if(typeof t=="object"&&t!==null){let n=!1;const r={};for(const[l,c]of Object.entries(t)){const p=Wt(c,s,o);p!==c&&(n=!0),r[l]=p}return n?r:t}return t}function pi(t){if(typeof t=="string"){if(!t.includes("{{"))return!1;const s=i.parseRootAnchoredTemplate(t);return s.length===1&&s[0].kind==="var"}return i.isDollarPath(t)&&typeof t.$=="string"}function On(t){return Array.isArray(t)&&t.length===1&&pi(t[0])}function fi(t){var s;try{const o=i.normalizeInput(t);if(!Array.isArray(o.nodes))return{};const n={},r=(p,d)=>{const x=Object.hasOwn(n,p)?n[p]:[];x.push(d),n[p]=x},l=new Map(o.nodes.map(p=>[p.id,p])),c=new Set;for(const[p,d]of Object.entries(i.definitionLoops(o))){const x=l.get(p);if(x&&On((s=x.with)==null?void 0:s.items)&&r(p,{code:"foreach_wrapped_items",fix:{kind:"unwrap_items",label:"Unwrap Items"}}),"invalid"in d){r(p,{code:"loop_body_invalid",reason:{...d.invalid}});continue}const h=d.body[d.body.length-1];i.isTandemOpener(x)&&!i.closesOpener(x,h===void 0?void 0:l.get(h))&&r(p,{code:"loop_closer_missing"});for(const m of d.body)i.closesOpener(x,l.get(m))&&c.add(m);for(const m of d.body){const k=l.get(m);if(!(k!=null&&k.with))continue;const j=[];Wt(k.with,p,j),j.length>0&&r(m,{code:"foreach_body_refs_output",foreachId:p,refs:j,fix:{kind:"use_current_item",foreachId:p,label:"Use Current item"}})}}for(const p of o.nodes)i.isLoopCloser(p)&&!c.has(p.id)&&r(p.id,{code:"loop_closer_orphan"});return n}catch{return{}}}function hi(t){const s=new Set,o=n=>{if(typeof n=="string")s.add(n);else if(Array.isArray(n))for(const r of n)o(r)};return o(t),s}function mi(t){var s,o;try{const n=i.normalizeInput(t);if(!Array.isArray(n.nodes))return[];const r=n.nodes.filter(R=>typeof R=="object"&&R!==null&&typeof R.id=="string"),l=i.effectiveEdges({...n,nodes:r}).filter(R=>typeof(R==null?void 0:R.from)=="string"&&typeof(R==null?void 0:R.to)=="string"),c=[];for(const R of r)try{const L=Re.staticWritePaths(Re.effectiveStateConfig((s=R.uses)==null?void 0:s.app,(o=R.uses)==null?void 0:o.action,R.state));L.length>0&&c.push({id:R.id,paths:L})}catch{}if(c.length<2)return[];const p=new Map;for(const R of r)for(const L of i.controlOwnedIds(R))p.has(L)||p.set(L,R.id);const d=R=>{const L=[R];let E=R;for(;p.has(E)&&(E=p.get(E),!L.includes(E));)L.push(E);return L},x=R=>{const L=d(R);return L[L.length-1]},h=new Map;for(const R of l){const L=h.get(R.from)??[];L.push(R.to),h.set(R.from,L)}const m=new Map,k=R=>{const L=m.get(R);if(L)return L;const E=new Set,z=[...h.get(R)??[]];for(;z.length>0;){const Y=z.pop();if(!E.has(Y)){E.add(Y);for(const N of h.get(Y)??[])z.push(N)}}return m.set(R,E),E},j=(R,L)=>R===L||k(R).has(L),y=r.filter(R=>{var L;return((L=R.uses)==null?void 0:L.app)===i.CONTROL_APP&&R.uses.action==="parallel"}).map(R=>{var E;const L=(E=R.with)==null?void 0:E.branches;return Array.isArray(L)?L.map(hi):[]}),C=(R,L)=>{for(const E of d(L)){const z=R.findIndex(Y=>Y.has(E));if(z>=0)return z}return-1},A=[];for(const R of r){if(R.fanOut!=="parallel")continue;const L=new Map;for(const E of l){if(E.from!==R.id||i.isEachLink(E))continue;const z=E.when??"success",Y=L.get(z)??[];Y.push(E.to),L.set(z,Y)}for(const E of L.values())E.length>=2&&A.push(E)}const w=(R,L)=>{for(const Y of y){const N=C(Y,R),g=C(Y,L);if(N>=0&&g>=0&&N!==g)return!0}const E=x(R),z=x(L);return E===z||k(E).has(z)||k(z).has(E)?!1:A.some(Y=>Y.some((N,g)=>Y.some((P,X)=>g!==X&&j(N,E)&&j(P,z))))},D=new Set,$=[];for(let R=0;R<c.length;R++)for(let L=R+1;L<c.length;L++){const E=c[R],z=c[L];if(!(E.id===z.id||!w(E.id,z.id)))for(const Y of E.paths)for(const N of z.paths){if(!Re.statePathsOverlap(Y,N))continue;const g={code:"state_parallel_write",nodes:[E.id,z.id].sort(),path:[...Y.length<=N.length?Y:N]},P=JSON.stringify([g.nodes,g.path]);D.has(P)||(D.add(P),$.push(g))}}const M=(R,L)=>R<L?-1:R>L?1:0;return $.sort((R,L)=>M(R.code,L.code)||M(R.nodes.join(","),L.nodes.join(","))||M(R.path.join("."),L.path.join(".")))}catch{return[]}}function wi(t){try{const s={};for(const o of mi(t))for(const n of o.nodes){const r=Object.hasOwn(s,n)?s[n]:[];r.push({code:o.code,path:[...o.path],with:o.nodes.filter(l=>l!==n)}),s[n]=r}return s}catch{return{}}}function $n(t,s){var o;if(s.code==="foreach_wrapped_items"){const n=(o=t.with)==null?void 0:o.items;return!t.with||!On(n)?t:{...t,with:{...t.with,items:n[0]}}}if(s.code==="foreach_body_refs_output"){if(!t.with)return t;const n=Wt(t.with,s.foreachId,[]);return n===t.with?t:{...t,with:n}}return t}function bn(t,s,o){return t&&t.nodeId===s&&t.handleType===((o==null?void 0:o.type)??"source")?i.laneForSourceHandle(t.handleId):i.laneForSourceHandle(o==null?void 0:o.id)}function gi(t,s,o,n,r){var x;const l=(x=n.find(h=>h.id===t))==null?void 0:x.data.step,c=i.loopMembership(n,r)[t]!==void 0,p=o==="success"&&c?"each":o;if(p==="each"&&!c&&!i.isLoopOpener(l))return null;const d=o==="success"&&i.isLoopOpener(l)?i.FOREACH_DONE_ROUTE:void 0;return i.loopRefusal(t,s,p,n,r,d)}function Vt(t,s){var o;return(o=t.nodes??t.steps)==null?void 0:o[s]}function fs(t,s){const o=Vt(t,s);return(o==null?void 0:o.status)==="skipped"&&o.skipReason==="not_on_path"}const xi=new Set(["succeeded","failed","canceled"]);function bi(t,s,o=[]){var l,c;if(!t||[...o,s].some(p=>fs(t,p)))return"no-run";const n=Vt(t,s);if(n)return n.status;const r=new Set;for(const p of Object.values(t.nodes??t.steps??{}))if(Array.isArray(p==null?void 0:p.iterations))for(const d of p.iterations){const x=(c=(l=d==null?void 0:d.nodes)==null?void 0:l[s])==null?void 0:c.status;x&&r.add(x)}for(const p of["failed","running","succeeded","skipped"])if(r.has(p))return p;return"pending"}const jn={borderColor:"var(--w6w-border)",borderStyle:"solid",borderWidth:1,opacity:1};function Wn(t,s){const o=s!==void 0&&xi.has(s);switch(t){case"no-run":return jn;case"pending":return o?{borderColor:"var(--w6w-muted)",borderStyle:"dashed",borderWidth:1,opacity:.5}:{borderColor:"var(--w6w-border)",borderStyle:"dashed",borderWidth:1,opacity:1};case"running":return{borderColor:"var(--w6w-accent)",borderStyle:"solid",borderWidth:2,opacity:1};case"succeeded":return{borderColor:"var(--w6w-success)",borderStyle:"solid",borderWidth:2,opacity:1};case"failed":return{borderColor:"var(--w6w-danger)",borderStyle:"solid",borderWidth:2,opacity:1};case"skipped":return{borderColor:"var(--w6w-muted)",borderStyle:"dashed",borderWidth:1,opacity:.7};default:return jn}}function ji(t,s,o,n,r){var c;if(!t||fs(t,s)||r!==void 0&&fs(t,r))return;const l=vi(t,s,o,n);return l==="taken"&&r!==void 0&&((c=Vt(t,r))==null?void 0:c.status)==="skipped"?"skipped":l}function vi(t,s,o,n){const r=Vt(t,s);if(!r)return;if(o==="each")return r.status==="skipped"?"skipped":void 0;const l=o??"success",c=r.output,p=n===i.FOREACH_DONE_ROUTE&&!(c&&typeof c=="object"&&"route"in c);if(n!==void 0&&!p&&r.status==="succeeded")return c&&typeof c=="object"&&"matched"in c?n==="false"!=(c.matched===!0)?"taken":"skipped":c&&typeof c=="object"&&"route"in c&&c.route===n?"taken":"skipped";if(r.status==="succeeded")return l==="success"?"taken":"skipped";if(r.status==="failed")return l==="error"?"taken":"skipped";if(r.status==="skipped")return"skipped"}const vn={fields:[],sampleValues:{}};function ws(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yi(t,s){var x;const o=t.map(h=>h.id),n=new Set(o),r=new Map(o.map(h=>[h,0])),l=new Map(o.map(h=>[h,[]]));for(const h of s)!n.has(h.source)||!n.has(h.target)||((x=l.get(h.source))==null||x.push(h.target),r.set(h.target,(r.get(h.target)??0)+1));const c=[],p=o.filter(h=>r.get(h)===0);for(;p.length>0;){const h=p.shift();c.push(h);for(const m of l.get(h)??[]){const k=(r.get(m)??0)-1;r.set(m,k),k===0&&p.push(m)}}const d=new Set(c);for(const h of o)d.has(h)||c.push(h);return c}const Si=new Set(["string","number","boolean","object","array"]);function bt(t){if(!Array.isArray(t))return;const s={type:"object",fields:{}};let o=!1;for(const n of t){if(!ws(n)||typeof n.key!="string"||n.key==="")continue;const r=n.key.split(".");let l=s;for(const d of r.slice(0,-1)){const x=l.fields[d];(x==null?void 0:x.type)!=="object"&&(l.fields[d]={type:"object",fields:{}}),l=l.fields[d]}const c=typeof n.type=="string"&&Si.has(n.type)?n.type:"string";let p;if(c==="array"){const d=bt(n.items);p=d?{type:"array",items:d}:{type:"array"}}else c==="object"?p=bt(n.fields??n.properties)??{type:"object",fields:{}}:p={type:c};l.fields[r[r.length-1]]=p,o=!0}return o?s:void 0}function Ni(t,s){var x,h,m,k,j,y,C;const o=t.data.step,n=((x=s.testOutputs)==null?void 0:x[o.id])??((h=s.persistedOutputs)==null?void 0:h[o.id]);if(n!=null)return n;const{app:r,action:l}=o.uses;if(r===i.TRIGGER_APP&&((m=i.internalNodeDef(r,l))==null?void 0:m.group)==="trigger"){const A=i.fieldsToParams(i.asFieldDefs((k=o.with)==null?void 0:k.fields)).map(w=>({key:w.key}));return i.shapeToSkeleton(bt(A))}const c=(j=i.internalNodeDef(r,l))==null?void 0:j.output;if(c&&c.length>0)return i.shapeToSkeleton(bt(c));const p=o.uses.trigger===!0?(y=s.triggerDef)==null?void 0:y.call(s,r,l):(C=s.actionDef)==null?void 0:C.call(s,r,l),d=bt(p==null?void 0:p.output);return d?i.shapeToSkeleton(d):p==null?void 0:p.sample}function Ci(t,s){var p,d,x,h,m;const o=t.data.step,n=(p=s.previewOutputs)==null?void 0:p[o.id];if(n!=null)return n;const{app:r,action:l}=o.uses,c=o.uses.trigger===!0?(x=(d=s.shapes)==null?void 0:d.triggerDef)==null?void 0:x.call(d,r,l):(m=(h=s.shapes)==null?void 0:h.actionDef)==null?void 0:m.call(h,r,l);return c==null?void 0:c.sample}function ki(t){switch(t){case"number":case"integer":return 0;case"boolean":return!1;case"object":return{};case"array":return[];default:return""}}function yn(t,s){const o=ws(t.initialState)?{...t.initialState}:{};for(const n of t.variables??[])!n||typeof n.key!="string"||n.key===""||(n.default!==void 0?o[n.key]=n.default:s||(o[n.key]=ki(n.type)));return o}function is(t){return(i.inferOutputFields(t)??[]).map(s=>s.key)}function Ei(t){const{anchorId:s,nodes:o,edges:n}=t;if(!s)return vn;const r=t.shapes??{},l=t.floating?new Set(o.map(E=>E.id)):i.ancestorIds(s,n);l.delete(s);const c=new Map(o.map(E=>[E.id,E])),p=[],d=[],x=new Map;for(const E of yi(o,n)){if(!l.has(E))continue;const z=c.get(E);if(!z)continue;const{app:Y,action:N}=z.data.step.uses,g=Re.effectiveStateConfig(Y,N,z.data.step.state);if(g.mode==="off")continue;const P=Ni(z,r);if(P!==void 0){const{ops:B}=Re.computeStateWrites(g,P);p.push(...B);for(const ie of is(Re.foldState({},B))){const te=x.get(ie)??new Set;te.add(E),x.set(ie,te)}}const X=Ci(z,t);X!==void 0&&d.push(...Re.computeStateWrites(g,X).ops)}const h=yn(t,!1),m=Re.foldState(h,p),k=is(m);if(k.length===0)return vn;const j=new Set(is(h)),y=new Map,C=new Map;for(const E of n)l.has(E.source)&&(!l.has(E.target)&&E.target!==s||(y.set(E.target,[...y.get(E.target)??[],E.source]),C.set(E.source,[...C.get(E.source)??[],E.target])));const A=[...l].filter(E=>!(y.get(E)??[]).length),w=E=>{const z=new Set,Y=A.filter(N=>!E.has(N));for(;Y.length>0;){const N=Y.pop();if(N===s)return!1;if(!z.has(N)){z.add(N);for(const g of C.get(N)??[])E.has(g)||Y.push(g)}}return!0},D=Re.foldState(yn(t,!0),d),$=d.length>0?Re.foldState({},d):void 0,M=ws($)&&Object.keys($).length>0?$:void 0,R=[],L={};for(const E of k){const z=x.get(E)??new Set,Y=j.has(E)||z.size>0&&w(z);R.push({key:E,path:!0,paths:Y?"all":"some"});const N=i.valueAtPath(D,E);N!==void 0&&(L[`state.${E}`]=N)}return{fields:R,sampleValues:L,...M?{written:M}:{}}}const Ti={registered:{label:"Registered",tone:"ok"},pending:{label:"Registering",tone:"pending"},failed:{label:"Registration failed",tone:"danger"},paused:{label:"Paused",tone:"muted"},destroying:{label:"Removing",tone:"muted"}},Sn="Never fired";function Ii(t){if(!t)return Sn;const s=new Date(t);return Number.isNaN(s.getTime())?Sn:`Last fired ${s.toISOString().slice(0,16).replace("T"," ")} UTC`}function Ai(t,s){var r;if(!(t!=null&&t.status))return null;const o=Ti[t.status];if(!o)return null;const n=t.status==="failed";return{label:o.label,tone:o.tone,error:n?((r=t.lastError)==null?void 0:r.message)??null:null,lastFire:Ii(t.lastFireAt),retryVisible:n&&s}}function Ri(t){const s=new Map;for(const o of t)o.nodeId&&s.set(o.nodeId,o);return s}function Pi(t){return(t??[]).filter(s=>{var o;return((o=s.uses)==null?void 0:o.trigger)===!0})}function Li(t,s){const[o,n]=u.useState({}),r=u.useRef(new Set),l=JSON.stringify([...new Set(s.map(c=>c.data.step.uses.app))].filter(c=>c&&!i.isInternalApp(c)).sort());return u.useEffect(()=>{const c=JSON.parse(l).filter(p=>!r.current.has(p));if(c.length!==0){for(const p of c)r.current.add(p);Promise.all(c.map(async p=>{try{return[p,await t.getAppActions(p)]}catch{return r.current.delete(p),null}})).then(p=>{const d=p.filter(x=>x!==null);d.length!==0&&n(x=>({...x,...Object.fromEntries(d)}))})}},[t,l]),o}function Fi(t,s){const[o,n]=u.useState({}),r=u.useRef(new Set),l=JSON.stringify([...new Set(s.filter(c=>c.data.step.uses.trigger===!0).map(c=>c.data.step.uses.app))].filter(c=>c&&!i.isInternalApp(c)).sort());return u.useEffect(()=>{const c=t.getAppTriggers;if(typeof c!="function")return;const p=JSON.parse(l).filter(d=>!r.current.has(d));if(p.length!==0){for(const d of p)r.current.add(d);Promise.all(p.map(async d=>{try{return[d,await c.call(t,d)]}catch{return r.current.delete(d),null}})).then(d=>{const x=d.filter(h=>h!==null);x.length!==0&&n(h=>({...h,...Object.fromEntries(x)}))})}},[t,l]),o}function Di(t){return(s,o)=>{var n,r;return(r=(n=t[s])==null?void 0:n.find(l=>l.key===o))==null?void 0:r.ports}}const Mi="Which outcome of the source node this edge carries. An error edge is drawn by dragging from the node's error exit port; use this control to re-lane an edge already drawn. An error edge overrides the node’s “On error” policy.";function Nn(t,s,o,n){const r=t.find(l=>l.id===s);return[o,n,r==null?void 0:r.source,r==null?void 0:r.target]}const gs=u.createContext(void 0),xs=u.createContext(new Map),zt=u.createContext({tones:new Map,loopOf:new Map});function Cn(t){return`Can’t draw that edge: this node allows at most ${t} outgoing edge${t===1?"":"s"} per lane.`}const bs=u.createContext(new Map),Bn=u.createContext({byNode:new Map,subs:[]});function _i({apps:t,registration:s,children:o}){return e.jsx(bs.Provider,{value:t,children:e.jsx(Bn.Provider,{value:s,children:o})})}const js=u.createContext(null);function Oi(t){return e.jsx(le.ReactFlowProvider,{children:e.jsx($i,{...t})})}function kn(t,s){let o=s.length+1;for(;s.includes(`${t}-${o}`);)o++;return`${t}-${o}`}function rs(t){var s,o;return{x:t.position.x,y:t.position.y,w:((s=t.measured)==null?void 0:s.width)??t.width??200,h:((o=t.measured)==null?void 0:o.height)??t.height??64}}function $i({onConnectionResourcesChange:t,value:s,onChange:o,readOnly:n,height:r=480,apps:l,exprOptions:c,project:p,runState:d,stepProblems:x,onTestRun:h,fitViewKey:m,onRunFromNode:k}){var Zs,Qs,en,tn,sn,nn,on;const j=i.useW6WApi(),y=u.useMemo(()=>new Map((l??[]).map(a=>[a.id,a])),[l]),C=Ji(s),[A,w]=u.useState(null),D=u.useMemo(()=>i.centralizeConnections(s),[s.id]),$=u.useMemo(()=>i.workflowToFlow(D),[D]),[M,R]=u.useState(D.connections??{}),L=u.useRef(M),E=u.useCallback(a=>{L.current=a,R(a)},[]),z=u.useCallback(a=>{const f=i.centralizeConnections({nodes:[a],connections:L.current});return f.connections!==L.current&&E(f.connections),f.nodes[0]},[E]),Y=u.useMemo(()=>i.storedViewport(s),[s.id]),N=((Zs=s.settings)==null?void 0:Zs.savePosition)!==!1,[g,P,X]=le.useNodesState($.nodes),B=Li(j,g),ie=Fi(j,g),te=u.useMemo(()=>Di(B),[B]),[T,Z,F]=le.useEdgesState($.edges),[U,J]=u.useState(null),ae=u.useMemo(()=>s.canvas??{},[s.id]),[G,q]=u.useState(ae),[K]=u.useState(()=>new ei(Ot(D,$.nodes,$.edges,M,ae))),se=u.useRef(),[ge,qe]=u.useState(0),[_e,ct]=u.useState(!1),[ke,Ge]=u.useState(null),[Pe,je]=u.useState(null),[ce,Ie]=u.useState(null),[Be,re]=u.useState(!1),jt=u.useRef({});u.useEffect(()=>{Be||(jt.current={})},[Be]);const[de,Le]=u.useState(null),[Oe,Ae]=u.useState("props"),[ve,Ke]=u.useState(null),[Se,Ve]=u.useState(null),[Fe,ze]=u.useState(null),dt=u.useRef(!1),Ee=u.useRef(null),[xe,$e]=u.useState(null),{screenToFlowPosition:De,fitView:Me}=le.useReactFlow(),ut=i.useEffectiveTheme();u.useEffect(()=>{P($.nodes),Z($.edges),J(null),Ie(null),ze(null),Le(null),Ke(null),q(ae),E(D.connections??{}),K.reset(Ot(D,$.nodes,$.edges,D.connections??{},ae)),se.current=void 0},[$,ae,D,P,Z,E,K]),u.useEffect(()=>{P(a=>{const f=new Map(i.stampLoopOf(a,T).map(b=>[b.id,b.data.loopOf]));return a.map(b=>{const v=bi(d,b.id,Dn(b.id,f));return b.data.stepStatus===v&&b.data.runStatus===(d==null?void 0:d.status)?b:{...b,data:{...b.data,stepStatus:v,runStatus:d==null?void 0:d.status}}})}),Z(a=>a.map(f=>{var O;const b=i.edgeLane(f),v=ji(d,f.source,b,typeof((O=f.data)==null?void 0:O.route)=="string"?f.data.route:void 0,f.target),S=i.edgeVisuals(b,v);return f.className===S.className&&f.label===S.label?f:{...f,className:S.className,label:S.label}}))},[d,$,ge,P,Z]),u.useEffect(()=>{P(a=>i.applyStepProblems(a,x))},[x,$,ge,P]);const nt=u.useCallback((a,f)=>{var S,O;const{canvas:b,...v}=a;return!((S=f.notes)!=null&&S.length)&&!((O=f.sections)!=null&&O.length)?v:{...v,canvas:Vo(f,s.canvas,N)}},[s.canvas,N]),ne=u.useCallback((a,f,b)=>{K.record(Ot(s,a,f,L.current,b??G),Be?jt.current:se.current),o(nt(i.flowToWorkflow({...s,connections:L.current},a,f),b??G))},[s,o,G,nt,K,Be]),ot=u.useRef(()=>{});ot.current=a=>{if(n)return;const f=i.editConnectionResources(g.map(v=>v.data.step),L.current,a),b=g.map((v,S)=>({...v,data:{...v.data,step:f.nodes[S]}}));E(f.connections),P(b),ne(b,T)};const Ye=u.useCallback(a=>ot.current(a),[]),vt=u.useCallback(a=>{J(a),Ie(null),P(f=>f.map(b=>({...b,selected:b.id===a}))),Z(f=>f.map(b=>({...b,selected:!1}))),Me({nodes:[{id:a}],duration:300,maxZoom:1})},[P,Z,Me]),[pt,we]=u.useState(null),yt=u.useMemo(()=>pt?g.map(a=>a.id===pt?{...a,className:`${a.className??""} w6w-connection-highlight`.trim()}:a):g,[g,pt]),ft=g.map(a=>({id:a.data.step.id,uses:a.data.step.uses})),Ht=JSON.stringify(ft),St=JSON.stringify([...y]);u.useEffect(()=>{t==null||t({workflowId:s.id,nodes:ft,apps:y,connections:M,readOnly:n,edit:Ye,focusNode:vt,highlightNode:we})},[t,s.id,Ht,St,M,n,Ye,vt]),u.useEffect(()=>()=>t==null?void 0:t(null),[t]);const Nt=u.useCallback(a=>i.canConnect(a.source,a.target,g,T,te,i.routeFromHandle(a.sourceHandle)),[g,T,te]),[it,Ne]=u.useState(null),I=u.useRef(null),ee=u.useRef(null);u.useEffect(()=>{P(a=>i.stampLoopOf(a,T))},[T,P]);const fe=u.useCallback(a=>{if(n)return;const f=i.applyConnect(a.source,a.target,g,T,i.laneForSourceHandle(a.sourceHandle),te,i.routeFromHandle(a.sourceHandle));if(!f){const b=i.laneForSourceHandle(a.sourceHandle),v=i.connectRefusal(a.source,a.target,g,T,b,te,i.routeFromHandle(a.sourceHandle));if(v&&v.refused==="loop"){Ne({nodeId:a.source,reason:v.reason});return}if(v){const O=T.find(W=>W.source===a.source&&i.edgeLane(W)===b);O&&(Z(T.map(W=>({...W,selected:W.id===O.id}))),Ie(O.id),Ze({edgeId:O.id,message:Cn(v.cap)}));return}const S=i.connectConflict(a.source,a.target,g,T,i.laneForSourceHandle(a.sourceHandle));if(!S)return;Z(T.map(O=>({...O,selected:O.id===S}))),Ie(S),Ze({edgeId:S,message:i.idClashMessage("Can’t draw that edge",S,Nn(T,S,a.source,a.target))});return}Ze(null),Ne(null),Z(f),ne(g,f)},[T,g,Z,ne,n,te]),ue=u.useCallback((a,f)=>{var H,Q,pe;if(n||f.isValid)return;const b=f.fromNode;if(!b)return;const v=((H=f.fromHandle)==null?void 0:H.type)==="target"?"target":"source",S=f.toNode;if(S&&v==="source"){const he=gi(b.id,S.id,bn(ee.current,b.id,f.fromHandle),g,T);if(he){Ne({nodeId:b.id,reason:he});return}}const O=(Q=g.find(he=>he.id===b.id))==null?void 0:Q.data.step;if(O){const he=i.nodePortsForStep(O,te);if((v==="source"?he.out:he.in)<1)return}const W="changedTouches"in a?a.changedTouches[0]:a,_=De({x:W.clientX,y:W.clientY});$e({nodeId:b.id,handleType:v,position:_,lane:bn(ee.current,b.id,f.fromHandle),route:i.routeFromHandle((pe=f.fromHandle)==null?void 0:pe.id)}),re(!0)},[n,De,g,T,te]),Xe=u.useCallback((a,f,b)=>{if(n)return;const v=g.find(H=>H.id===a);if(!v)return;const S=rs(v),O=i.laneForSourceHandle(b),W=120,_=f==="target"?{x:S.x-S.w-W,y:S.y}:O==="error"?{x:S.x,y:S.y+S.h+W}:O==="each"?{x:S.x+S.w+W,y:S.y-S.h-W/2}:{x:S.x+S.w+W,y:S.y};$e({nodeId:a,handleType:f,position:_,lane:O,route:i.routeFromHandle(b)}),re(!0)},[n,g]),Ct=u.useCallback(a=>{if(n)return;const f=i.closerDeleteRefusal(a.nodeIds,g,T);if(f!==void 0){Ne({nodeId:f,reason:"closer_delete"});return}if(a.nodeIds.length===0){const b=new Set(a.edgeIds),v=T.filter(O=>!b.has(O.id)),S=i.strandedClosers(g,T,v);if(S.length>0){Ne({nodeId:S[0],reason:"closer_detached"});return}}ze(a)},[n,g,T]),ys=u.useCallback(a=>Ct({nodeIds:[a],edgeIds:[]}),[Ct]),Zn=u.useCallback(a=>{if(n)return;const f=Xo(a,g,T,G);P(f.nodes),Z(f.edges),q(f.canvas),f.nodes.some(b=>b.id===U)||J(null),f.nodes.some(b=>b.id===de)||Le(null),f.edges.some(b=>b.id===ce)||Ie(null),ne(f.nodes,f.edges,f.canvas)},[g,T,G,P,Z,ne,n,U,de,ce]),Ss=u.useCallback(()=>{if(n)return;const a=oi(g,T,G);P(a.nodes),q(a.canvas),dt.current=!0,ne(a.nodes,T,a.canvas)},[g,T,G,P,ne,n]),Qn=u.useCallback(()=>{n||Ss()},[n,Ss]);u.useEffect(()=>{dt.current&&(dt.current=!1,Me({duration:300}))},[g,Me]);const Ns=u.useRef(m);u.useEffect(()=>{Object.is(Ns.current,m)||(Ns.current=m,Me({duration:300}))},[m,Me]);const[kt,Ze]=u.useState(null),rt=u.useMemo(()=>T.find(a=>a.id===ce)??null,[T,ce]),eo=u.useCallback(a=>{if(n||!ce)return;const f=T.find(W=>W.id===ce);if(!f||i.edgeLane(f)===a)return;const b=i.edgeWhenConflict(T,ce,a,g),v=i.relaneRefusal(T,ce,a,g,te),S=b||v?null:i.setEdgeWhen(T,ce,a,g,te);if(!S){if(v){Ze({edgeId:ce,message:Cn(v.cap)});return}Ze({edgeId:ce,message:b?i.idClashMessage("Can’t switch this edge",b,Nn(T,b,f.source,f.target)):"This edge can’t be switched right now."});return}Ze(null),Z(S);const O=S.find(W=>W.source===f.source&&W.target===f.target&&i.edgeLane(W)===a);Ie((O==null?void 0:O.id)??null),ne(g,S)},[T,g,Z,ne,n,ce,te]),to=u.useCallback(a=>{if(n)return;const f=T.filter(v=>v.id!==a);if(f.length===T.length)return;const b=i.strandedClosers(g,T,f);if(b.length>0){Ne({nodeId:b[0],reason:"closer_detached"});return}Z(f),ce===a&&Ie(null),ne(g,f)},[g,T,Z,ne,n,ce]),Jt=u.useCallback(a=>{if(n)return;const f=new Map;for(const V of a){const oe=i.loopCloserOf(V,g,T);oe!==void 0&&f.set(V,oe)}const b=new Set(f.values()),v=V=>{var oe;return i.isLoopCloser((oe=g.find(me=>me.id===V))==null?void 0:oe.data.step)&&!b.has(V)},S=a.find(v),O=[...a.filter(V=>!v(V)),...[...b].filter(V=>!a.includes(V))];if(S!==void 0&&O.length===0){Ne({nodeId:S,reason:"closer_duplicate"});return}const W=O.map(V=>g.find(oe=>oe.id===V)).filter(V=>V!==void 0);if(W.length===0)return;const _=g.map(V=>V.id),H=W.map(V=>{const oe=i.suggestStepId(_,`${V.data.step.id}_copy`);_.push(oe);const me={...i.stripBody(structuredClone(V.data.step)),id:oe};return{id:oe,type:V.type,position:{x:V.position.x+40,y:V.position.y+60},data:{step:me,isInternal:V.data.isInternal},...W.length>1?{selected:!0}:{}}}),Q=[...W.length>1?g.map(V=>V.selected?{...V,selected:!1}:V):g,...H],pe=new Map(W.map((V,oe)=>[V.id,H[oe].id]));let he=T;for(const[V,oe]of f){const me=pe.get(V),Ce=pe.get(oe);me&&Ce&&(he=[...he,i.eachLaneEdge(me,Ce,!0)])}P(Q),he!==T&&Z(he),J(H[0].id),ne(Q,he)},[g,T,P,Z,ne,n]),Cs=u.useCallback(a=>Jt([a]),[Jt]),so=u.useCallback(a=>{if(n)return;const f=i.isInternalApp(a.uses.app),b=g.map(V=>V.id),v=a.id&&!i.stepNameError(a.id,b)?a.id:i.suggestStepId(b,i.slugifyLabel(i.internalNodeLabel(a.uses.app,a.uses.action))),S=z({id:v,uses:a.uses,...a.with&&Object.keys(a.with).length>0?{with:a.with}:{}}),O={id:v,type:f?"control":"step",position:(xe==null?void 0:xe.position)??(Se==null?void 0:Se.position)??{x:80,y:80+g.length*24},data:{step:S,isInternal:f}},W=Se!=null&&Se.replaces?g.find(V=>V.id===Se.replaces):void 0;if(W&&i.isTriggerStep(a.uses)){const V={...O,position:W.position},oe=[...g.filter(wt=>wt.id!==W.id),V],me=i.renameStepInEdges(T,W.id,v),Ce=ls(G,W.id,v);return P(oe),Z(me),q(Ce),Ne(null),J(v),ne(oe,me,Ce),v}let _=[...g,O],H=T,Q=null;const pe=(V,oe,me,Ce)=>{const wt=i.connectRefusal(V,oe,_,T,me,te);wt&&wt.refused==="loop"&&(Q={nodeId:Ce,reason:wt.reason})};if(xe){const[V,oe]=xe.handleType==="target"?[v,xe.nodeId]:[xe.nodeId,v],Ce=(xe.handleType==="source"?i.insertIntoTandem(V,v,_,T,xe.lane,xe.route):null)??i.applyConnect(V,oe,_,T,xe.lane,te,xe.route);Ce||pe(V,oe,xe.lane,xe.nodeId),H=Ce??T}else{const V=g.find(oe=>i.isTriggerStep(oe.data.step.uses));if(i.isTriggerStep(a.uses)){if(!V){const oe=i.findChainRoot(g,T);if(oe){const me=i.applyConnect(v,oe.id,_,T,"success",te);me||pe(v,oe.id,"success",oe.id),H=me??T}}}else{const me=(V&&!T.some(Ce=>Ce.source===V.id)?V:void 0)??i.findChainTail(g,T);if(me){const Ce=i.applyConnect(me.id,v,_,T,"success",te);Ce||pe(me.id,v,"success",me.id),H=Ce??T}}}const he=i.addTandemCloser(v,_,H);return he&&(_=he.nodes,H=he.edges),P(_),H!==T&&Z(H),Ne(Q),J(v),ne(_,H),v},[g,T,P,Z,ne,n,xe,Se,te,z,G]),ks=u.useCallback((a,f)=>{var H;let b=f;const v=(H=g.find(Q=>Q.id===a))==null?void 0:H.data.step;if(f.uses.connection&&!f.uses.connectionRef&&(v!=null&&v.uses.connectionRef)&&v.uses.app===f.uses.app){const Q=i.selectNodeConnection(i.withConnectionRef(f,v.uses.connectionRef),f.uses.connection,g.map(pe=>pe.data.step),L.current);E(Q.connections),b=Q.step}else b=z(f);const S=b.id!==a;if(S&&g.some(Q=>Q.id===b.id))return;const O=g.map(Q=>Q.id===a?{...Q,id:b.id,data:{step:b,isInternal:i.isInternalApp(b.uses.app)}}:Q);if(S){const Q=i.renameStepInEdges(T,a,b.id),pe=ls(G,a,b.id);P(O),Z(Q),q(pe),U===a&&J(b.id),de===a&&Le(b.id),ne(O,Q,pe);return}P(O);const W=new Set(i.routesForStep(b).map(Q=>Q.id)),_=T.filter(Q=>{var pe;return Q.source!==b.id||((pe=Q.data)==null?void 0:pe.route)===void 0||W.has(String(Q.data.route))});_.length!==T.length&&Z(_),ne(O,_)},[g,T,G,P,Z,U,de,ne,z,E]),Qe=u.useCallback(a=>{n||(q(a),ne(g,T,a))},[n,g,T,ne]),no=u.useCallback(()=>{var S;if(n)return;const a=(S=Ee.current)==null?void 0:S.getBoundingClientRect(),f=a?De({x:a.left+a.width/2,y:a.top+a.height/2}):{x:0,y:0},b=G.notes??[],v={id:kn("note",b.map(O=>O.id)),color:"#facc15",position:{x:Math.round(f.x-100),y:Math.round(f.y-60)},size:{width:200,height:120},content:""};Qe(ds({...G,notes:[...b,v]}))},[n,G,De,Qe]),oo=u.useCallback((a,f)=>{if(n)return;const b=f?Math.min(a.x,f.x):a.x,v=f?Math.min(a.y,f.y):a.y,S=f?Math.abs(f.x-a.x):360,O=f?Math.abs(f.y-a.y):240,W=g.filter(he=>{const V=rs(he),oe=V.x+V.w/2,me=V.y+V.h/2;return oe>=b&&oe<=b+S&&me>=v&&me<=v+O}).map(he=>he.id),_=G.sections??[],H=kn("section",_.map(he=>he.id)),Q={id:H,title:"Section",color:"#6366f1",position:{x:Math.round(b),y:Math.round(v)},size:{width:Math.round(S),height:Math.round(O)},nodes:[]},pe={...G,sections:[..._,Q]};Qe(ds(cs(pe,H,W)))},[n,g,G,Qe]);u.useEffect(()=>{if(!_e)return;const a=f=>{f.key==="Escape"&&(ct(!1),Ge(null))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[_e]);const io=u.useCallback((a,f)=>{var W;if(n)return;const b=(W=G.sections)==null?void 0:W.find(_=>_.id===a);if(!b)return;const v=new Set(b.nodes),S=g.map(_=>v.has(_.id)?{..._,position:{x:_.position.x+f.dx,y:_.position.y+f.dy}}:_),O={...G,sections:(G.sections??[]).map(_=>_.id===a?{..._,position:{x:_.position.x+f.dx,y:_.position.y+f.dy}}:_)};P(S),q(O),ne(S,T,O)},[n,G,g,T,P,ne]),ro=u.useCallback((a,f)=>{if(n)return;const b=a==="note"?{...G,notes:(G.notes??[]).filter(v=>v.id!==f)}:{...G,sections:(G.sections??[]).filter(v=>v.id!==f)};Qe(b)},[n,G,Qe]),ao=a=>{let f=G;for(const b of a){const v=rs(b),S=v.x+v.w/2,O=v.y+v.h/2,W=(f.sections??[]).find(H=>S>=H.position.x&&S<=H.position.x+H.size.width&&O>=H.position.y&&O<=H.position.y+H.size.height),_=Pn(f,b.id);W?(_.length!==1||_[0]!==W.id)&&(f=cs(f,W.id,[b.id])):_.length>0&&(f=ms(f,b.id))}return f},qt=u.useCallback((a,f,b)=>{(async()=>{const v=await j.saveStepTest(s.id,a,f).catch(S=>(console.error("step run fixture save failed",S),null));await j.recordStepTestRun(s.id,a,{stepTestId:(v==null?void 0:v.id)??null,status:b.status,input:f.input,output:b.output,error:b.error,...b.meta?{meta:b.meta}:{}})})().catch(v=>{console.error("step run persist failed",v)})},[j,s.id]),Es=u.useCallback(a=>{const f=g.find(b=>b.id===a);!f||!k&&i.isControlApp(f.data.step.uses.app)||w({stepId:a,status:"collect"})},[g,k]),lo=u.useCallback(async(a,f,b)=>{if(!k)return;const v=g.find(W=>W.id===a);if(!v)return;const S=i.isTriggerStep(v.data.step.uses),O={stopAt:ps(g.map(W=>W.data.step),a),...b?{state:b}:{},...S?{input:f}:{}};w({stepId:a,status:"running"});try{await k(a,O),w(null)}catch(W){const _=W;w({stepId:a,status:"error",error:_.message??String(W),errorCode:_.code})}},[g,k]),Et=u.useCallback((a,f)=>{if(n)return;const b=g.map(v=>v.id===a?{...v,data:{...v.data,step:f(v.data.step)}}:v);P(b),ne(b,T)},[g,T,P,ne,n]),Ts=u.useCallback(a=>Et(a,f=>Mn(f,!st(f))),[Et]),Is=u.useCallback(a=>Et(a,f=>_n(f,!We(f))),[Et]),co=u.useCallback(async(a,f,b)=>{h==null||h();const v=g.find(H=>H.id===a);if(!v)return;const S=v.data.step,O=i.isTriggerStep(S.uses),W=O?{input:f}:{...S.with??{},...f},_=O?{input:f,with:f}:{input:f,with:W};w({stepId:a,status:"running"});try{const H=await j.invokeAction(S.uses.app,S.uses.action,W,{connectionId:i.connectionIdFor(S,L.current),project:p,...b?{state:b}:{},workflowId:s.id,...S.timeoutMs?{timeoutMs:S.timeoutMs}:{}}),Q=H.logs,pe=H.meta;w({stepId:a,status:"done",value:H.value,logs:Q,...pe?{meta:pe}:{}}),qt(a,_,{status:"succeeded",output:H.value,...pe?{meta:pe}:{}})}catch(H){const Q=H;w({stepId:a,status:"error",error:Q.message??String(H),errorCode:Q.code}),qt(a,_,{status:"failed",error:Q.message??String(H)})}},[g,j,qt,p,h,s.id]),Gt=u.useMemo(()=>({onEdit:a=>{Ae("props"),Le(a)},onEditJson:a=>{Ae("json"),Le(a)},onRun:Es,onDuplicate:Cs,onDelete:ys,onTogglePause:Ts,onToggleDisable:Is,runsFromNode:!!k,onAddFromPort:Xe,readOnly:n}),[Es,Cs,ys,Ts,Is,k,Xe,n]);u.useEffect(()=>{const a=Ee.current;if(!a)return;const f=b=>{const v=b.target.closest(".react-flow__node");if(!v)return;const S=v.getAttribute("data-id");S&&(b.stopPropagation(),Gt.onEdit(S))};return a.addEventListener("dblclick",f,!0),()=>a.removeEventListener("dblclick",f,!0)},[Gt]);const at=g.find(a=>a.id===de),Tt=(at==null?void 0:at.data.step)??null,Kt=A?((Qs=g.find(a=>a.id===A.stepId))==null?void 0:Qs.data.step)??null:null,Yt=(A==null?void 0:A.status)==="collect"&&!!Kt,As=u.useMemo(()=>{const a=new Map;for(const f of g)a.set(f.id,i.fanOutState(f.id,T).count);return a},[g,T]),Rs=ci(g),It=u.useMemo(()=>di(Rs),[Rs]),uo=u.useMemo(()=>ai(T,It.tones,It.loopOf),[T,It]),po=u.useMemo(()=>({step:Gi,control:Ki}),[]),[At,Ps]=u.useState({}),[Rt,Ls]=u.useState({}),[Fs,Ds]=u.useState({}),[Pt,Ms]=u.useState({}),[Ue,Lt]=u.useState(null),[_s,Os]=u.useState([]),fo=de??Ue??"";u.useEffect(()=>{const a=j.loadNodeSamples;if(typeof a!="function"||!s.id){Os([]);return}let f=!1;return a(s.id).then(b=>{f||Os(Array.isArray(b)?b:[])},()=>{}),()=>{f=!0}},[j,s.id,fo]);const Ft=u.useMemo(()=>i.indexNodeSamples(_s),[_s]),Xt=u.useMemo(()=>i.splitNodeOutputs(At,Ft,Pt),[At,Ft,Pt]),He=u.useMemo(()=>i.splitPreviewOutputs(At,Ft,Pt),[At,Ft,Pt]),Te=u.useMemo(()=>({actionDef:(a,f)=>{var b;return(b=B[a])==null?void 0:b.find(v=>v.key===f)},triggerDef:(a,f)=>{var b;return(b=ie[a])==null?void 0:b.find(v=>v.key===f)},testOutputs:Xt.fresh,persistedOutputs:Xt.persisted,loopSamples:Fs}),[B,ie,Xt,Fs]),et=u.useMemo(()=>A?i.upstreamStateSources(A.stepId,g,T,Te):void 0,[A,g,T,Te]),ho=u.useMemo(()=>(et==null?void 0:et.steps)??[],[et]),ye=u.useMemo(()=>{const a=i.upstreamStateSources(de,g,T,Te,Ue);return{...a,steps:i.excludeSelfStep(a.steps,de??Ue)}},[de,Ue,g,T,Te]),ht=u.useMemo(()=>Ei({anchorId:de??Ue,nodes:g,edges:T,floating:i.isFloatingDraft(de,Ue,g,T),initialState:s.initialState,variables:s.variables,shapes:Te,previewOutputs:{...He.persisted,...He.fresh}}),[de,Ue,g,T,s.initialState,s.variables,Te,He]),$s=JSON.stringify([...ye.steps.map(a=>a.id),...ye.extraSampleIds??[]]);u.useEffect(()=>{const a=JSON.parse($s);if(!de&&!Ue||a.length===0){Ps({}),Ls({}),Ds({}),Ms({});return}let f=!1;return Promise.all(a.map(async b=>{try{const v=await j.listStepTests(s.id,b),S=v.length?v[v.length-1]:null;return S?{id:b,output:S.lastRunOutput,runAt:S.lastRunAt,meta:S.lastRunMeta,loopSample:i.foreachTestSample(S)}:null}catch{return null}})).then(b=>{if(f)return;const v={},S={},O={},W={};for(const _ of b)_!=null&&_.meta&&(S[_.id]=_.meta),_!=null&&_.loopSample&&(O[_.id]=_.loopSample),!(!_||_.output===void 0||_.output===null)&&(v[_.id]=_.output,W[_.id]=_.runAt);Ps(v),Ms(W),Ls(S),Ds(O)}),()=>{f=!0}},[j,s.id,de,Ue,$s]);const Zt=u.useMemo(()=>i.declaredSamples(g,Te),[g,Te]),Dt=u.useMemo(()=>({persisted:He.persisted,samples:Zt.samples,event:Zt.event}),[He.persisted,Zt]),Ws=u.useMemo(()=>i.upstreamSampleValues(ye.steps,He.fresh,Rt,ye.loop,Dt),[ye.steps,ye.loop,He.fresh,Rt,Dt]),Bs=u.useMemo(()=>i.upstreamSampleValueSources(ye.steps,He.fresh,Rt,ye.loop,Dt),[ye.steps,ye.loop,He.fresh,Rt,Dt]),Vs=i.useExpressionOptions(),zs=u.useMemo(()=>i.nodeConfigSources(g),[g]),Us=u.useMemo(()=>i.nodeConfigValues(g,C.subs),[g,C.subs]),Qt=u.useMemo(()=>i.nodeMetaValues(g,C.subs,y,M),[g,C.subs,y,M]),Hs=u.useMemo(()=>[...new Set(Object.values(M).flatMap(a=>a.connection?[a.connection]:[]))].sort().join(","),[M]),[Js,mo]=u.useState(()=>new Map);u.useEffect(()=>{if(!Hs)return;let a=!0;return j.listConnections().then(f=>{a&&mo(new Map(f.map(b=>[b.id,b])))}).catch(()=>{}),()=>{a=!1}},[j,Hs]);const es=u.useMemo(()=>i.connectionExpressionSources(M,Js,y),[M,Js,y]),ts=u.useMemo(()=>({...c??{},connections:es.sources,steps:ye.steps,hasTrigger:ye.hasTrigger,eventOutputs:ye.eventOutputs,eventOutputsFrom:ye.eventOutputsFrom,loop:ye.loop,stateShape:{fields:ht.fields,...ht.written?{written:ht.written}:{}},nodeConfigs:zs,nodeConfig:Us,nodeMeta:Qt,valueSources:Bs,sampleValues:{...Vs.sampleValues??{},...(c==null?void 0:c.sampleValues)??{},...es.sampleValues,...i.nodeMetaSampleValues(Qt),...Ws,...ht.sampleValues}}),[c,Vs.sampleValues,ye,ht,Ws,Bs,zs,Us,Qt,es]),mt=u.useRef(null);Be||de?mt.current===null&&(mt.current=K.mark()):mt.current=null;const qs=()=>{re(!1),$e(null),Ve(null),Lt(null)},Gs=()=>{const a=mt.current;if(mt.current=null,n||a===null)return;const f=K.rollbackTo(a);f&&Ys(f)},Ks=a=>{if(n)return;const f=K[a]();f&&Ys(f)},Ys=a=>{var v;const f=Qo(s,a);P(f.nodes.map(S=>({...S,selected:S.id===U}))),Z(f.edges.map(S=>({...S,selected:S.id===ce}))),q(a.canvas),E(a.connections),f.nodes.some(S=>S.id===U)||J(null),f.edges.some(S=>S.id===ce)||Ie(null);const b=f.nodes.some(S=>S.id===de);b||Le(null),re(!1),Lt(null),$e(null),ze(null),je(null),Ve(null),Ke(null),Ne(null),Ze(null),se.current=void 0,qe(S=>S+1),o(nt(i.flowToWorkflow({...s,nodes:a.nodes,connections:a.connections},f.nodes,f.edges),a.canvas)),!b&&!A&&((v=Ee.current)==null||v.focus({preventScroll:!0}))},Xs=u.useRef(Ks);Xs.current=Ks,u.useEffect(()=>{const a=Ee.current;if(!a)return;let f=a.contains(document.activeElement);const b=S=>{S.type==="focusin"&&S.target===document.body||(f=a.contains(S.target))},v=S=>{if(n||S.defaultPrevented||ns(S.target)||!a.contains(S.target)&&!(f&&S.target===document.body))return;const O=S.key.toLowerCase();!(S.ctrlKey||S.metaKey)||S.altKey||O!=="z"&&!(O==="y"&&!S.shiftKey)||(S.preventDefault(),Xs.current(O==="y"||S.shiftKey?"redo":"undo"))};return document.addEventListener("pointerdown",b),document.addEventListener("focusin",b),document.addEventListener("keydown",v),()=>{document.removeEventListener("pointerdown",b),document.removeEventListener("focusin",b),document.removeEventListener("keydown",v)}},[n]);const Mt=u.useCallback((a,f)=>{var _;if(ns(a.target))return;const b=(_=Ee.current)==null?void 0:_.getBoundingClientRect();if(!b)return;a.preventDefault();const v=mn(g,T),S=v.nodeIds,O=_o(S,f),W=f!==void 0&&!S.includes(f);W&&P(g.map(H=>H.selected!==(H.id===f)?{...H,selected:H.id===f}:H)),Ke({x:a.clientX-b.left,y:a.clientY-b.top,flow:De({x:a.clientX,y:a.clientY}),nodeIds:O,edgeIds:W?[]:v.edgeIds})},[g,T,P,De]),wo=u.useCallback(a=>{var f;Ke(null),a&&((f=Ee.current)==null||f.focus({preventScroll:!0}))},[]),go=a=>{const f=ve;if(!(!f||n))if(a==="duplicate")Jt(f.nodeIds);else if(a==="delete")Ct({nodeIds:f.nodeIds,edgeIds:f.edgeIds});else if(a==="replace-trigger"){const b=g.find(v=>v.id===f.nodeIds[0]);if(!b)return;$e(null),Ve({position:b.position,tab:"triggers",replaces:b.id}),re(!0)}else $e(null),Ve({position:f.flow,...a==="add-trigger"?{tab:"triggers"}:{}}),re(!0)},xo=e.jsx(js.Provider,{value:Gt,children:e.jsx(gs.Provider,{value:te,children:e.jsx(xs.Provider,{value:As,children:e.jsx(zt.Provider,{value:It,children:e.jsx(_i,{apps:y,registration:C,children:e.jsx(i.WorkflowProjectProvider,{project:p,workflowId:s.id,children:e.jsx(i.ExpressionOptionsProvider,{value:ts,children:e.jsxs("section",{ref:Ee,className:"w6w-flow",tabIndex:-1,"aria-label":"Workflow editor",style:{width:"100%",height:r,position:"relative"},onFocusCapture:a=>{se.current=ns(a.target)?{}:void 0},onBlurCapture:()=>{se.current=void 0},onKeyDown:a=>{if(a.defaultPrevented||a.key!=="Backspace"&&a.key!=="Delete"||n||de||Be||Fe)return;const f=a.target;if(f.isContentEditable||f.tagName==="INPUT"||f.tagName==="TEXTAREA"||f.tagName==="SELECT"||f.closest("dialog, .w6w-modal")!==null)return;const b=mn(g,T);!b.nodeIds.length&&!b.edgeIds.length||(a.preventDefault(),!b.nodeIds.length&&b.edgeIds.length===1?to(b.edgeIds[0]):Ct(b))},children:[e.jsxs(le.ReactFlow,{nodes:yt,edges:uo,minZoom:.05,defaultEdgeOptions:{type:"smoothstep"},connectionLineType:le.ConnectionLineType.SmoothStep,onNodesChange:X,onEdgesChange:F,onConnect:fe,onConnectStart:(a,f)=>{ee.current=f},onConnectEnd:ue,onPaneClick:()=>Ne(null),onPaneContextMenu:a=>Mt(a),onNodeContextMenu:(a,f)=>Mt(a,f.id),onEdgeContextMenu:a=>Mt(a),onSelectionContextMenu:a=>Mt(a),onMoveStart:()=>Ke(null),isValidConnection:Nt,onNodeDragStop:(a,f,b)=>{const v=ao(b),S=v!==G;if(S&&q(v),!N&&!S){K.record(Ot(s,g,T,L.current,v));return}ne(g,T,v)},onMoveEnd:(a,f)=>{if(!a||n)return;const b=i.flowToWorkflow(s,g,T),v=i.withViewport(b,f);v!==b&&o(v,{viewportOnly:!0})},onSelectionChange:({nodes:a,edges:f})=>{var b,v,S,O;J(((b=a[0])==null?void 0:b.id)??null),Ie(((v=f[0])==null?void 0:v.id)??null),I.current!==(((S=a[0])==null?void 0:S.id)??null)&&(I.current=((O=a[0])==null?void 0:O.id)??null,Ne(null))},nodeTypes:po,nodesDraggable:!n,nodesConnectable:!n,connectOnClick:!1,elementsSelectable:!0,...Y?{defaultViewport:Y}:{fitView:!0,fitViewOptions:{maxZoom:1}},deleteKeyCode:null,colorMode:ut,proOptions:{hideAttribution:!0},children:[e.jsx(le.Background,{gap:16}),e.jsx(le.Controls,{showInteractive:!1,children:!n&&e.jsx(le.ControlButton,{onClick:Qn,title:"Auto-layout — re-flow the graph into columns","aria-label":"Auto-layout the graph",children:e.jsx(be.Icon,{name:"layout"})})}),e.jsx(le.MiniMap,{pannable:!0,zoomable:!0,style:{background:"var(--w6w-panel-2)"}}),!n&&e.jsxs(le.Panel,{position:"top-left",className:"w6w-flow-tools",children:[e.jsx("button",{type:"button",className:"w6w-btn",onClick:()=>re(!0),children:"+ Node"}),e.jsx(i.IconButton,{label:"Add note",icon:"sticky-note",className:"w6w-flow-tool","data-testid":"add-note",onClick:no}),e.jsx(i.IconButton,{label:"Draw section",title:"Draw section — drag a frame on the canvas (Esc cancels)",icon:"frame",className:`w6w-flow-tool${_e?" active":""}`,"aria-pressed":_e,"data-testid":"draw-section",onClick:()=>{ct(!_e),Ge(null)}})]}),!n&&_e&&e.jsx("div",{className:"w6w-section-draw nopan nodrag nowheel","data-testid":"section-draw-surface",onPointerDown:a=>{if(a.button!==0)return;a.currentTarget.setPointerCapture(a.pointerId);const{clientX:f,clientY:b}=a;Ge({sx:f,sy:b,ex:f,ey:b})},onPointerMove:a=>{const{clientX:f,clientY:b}=a;Ge(v=>v&&{...v,ex:f,ey:b})},onPointerUp:()=>{const a=ke;if(Ge(null),ct(!1),!a)return;const f=De({x:a.sx,y:a.sy}),b=Math.abs(a.ex-a.sx)>6||Math.abs(a.ey-a.sy)>6;oo(f,b?De({x:a.ex,y:a.ey}):null)},children:ke&&(()=>{var v;const a=(v=Ee.current)==null?void 0:v.getBoundingClientRect(),f=(a==null?void 0:a.left)??0,b=(a==null?void 0:a.top)??0;return e.jsx("div",{className:"w6w-section-draw-rect",style:{left:Math.min(ke.sx,ke.ex)-f,top:Math.min(ke.sy,ke.ey)-b,width:Math.abs(ke.ex-ke.sx),height:Math.abs(ke.ey-ke.sy)}})})()}),!n&&rt&&i.edgeLane(rt)!=="each"&&((en=g.find(a=>a.id===rt.source))==null?void 0:en.data.step.uses.app)!==i.ROUTER_APP&&e.jsx(le.Panel,{position:"top-right",children:e.jsxs("div",{className:"w6w-edge-lane",children:[e.jsx("span",{className:"w6w-muted w6w-small",children:"Run on"}),["success","error"].map(a=>e.jsx("button",{type:"button",className:`w6w-btn w6w-btn-sm w6w-btn-ghost${i.edgeLane(rt)===a?" active":""}`,"aria-pressed":i.edgeLane(rt)===a,title:Mi,onClick:()=>eo(a),children:a==="success"?"Success":"Error"},a)),(kt==null?void 0:kt.edgeId)===rt.id&&e.jsx("span",{className:"w6w-edge-lane-err w6w-small",role:"alert",children:kt.message})]})}),it&&e.jsx(le.NodeToolbar,{nodeId:it.nodeId,position:le.Position.Bottom,isVisible:!0,children:e.jsx("div",{className:"w6w-loop-notice w6w-small",role:"alert",children:i.loopRefusalMessage(it.reason)})}),e.jsx(i.CanvasLayer,{canvas:G,readOnly:n,savePosition:N,onChange:Qe,onSectionDrop:io,onRequestDelete:(a,f)=>!n&&je({kind:a,id:f})})]}),Pe&&e.jsx(i.ConfirmModal,{title:Pe.kind==="note"?"Delete note":"Delete section",message:Pe.kind==="note"?"Delete this note?":"Delete this section? Its nodes are kept.",confirmLabel:"Delete",onConfirm:()=>{ro(Pe.kind,Pe.id),je(null)},onClose:()=>je(null)}),Be&&e.jsx(i.StepBuilderModal,{initialTab:Se==null?void 0:Se.tab,onClose:()=>{Gs(),qs()},onDone:qs,onAdd:a=>{const f=so(a);return f&&Lt(f),f},onDraftChange:(a,f)=>ks(a,{id:a,...f}),stepIds:g.map(a=>a.id),onOpenStep:a=>{re(!1),$e(null),Ve(null),Lt(null),Ae("props"),Le(a)},workflowId:s.id,upstreamSteps:i.stepBuilderUpstreamSteps(xe,g,T),loop:i.stepBuilderLoop(xe,g,T,Te)}),Tt&&de&&e.jsx(Xi,{workflowId:s.id,step:Tt,restoreVersion:ge,upstreamSteps:ts.steps??[],loop:ts.loop,readOnly:n,fanOutCount:As.get(de)??0,stateOutputFields:(on=i.resolveOutputShape((tn=Te.actionDef)==null?void 0:tn.call(Te,Tt.uses.app,Tt.uses.action),(sn=Te.testOutputs)==null?void 0:sn[de],(nn=Te.persistedOutputs)==null?void 0:nn[de]))==null?void 0:on.fields.map(a=>a.key),initialView:Oe,stepProblems:at==null?void 0:at.data.stepProblems,otherStepIds:g.filter(a=>a.id!==de).map(a=>a.id),onChange:a=>ks(de,a),onClose:()=>Le(null),onCancel:()=>{Gs(),Le(null)},onTestRun:h}),A&&e.jsxs(i.Modal,{title:`${Yt?"Run node":"Test run"}: ${A.stepId}`,onClose:()=>w(null),children:[Yt&&Kt&&e.jsx(zi,{workflowId:s.id,step:Kt,upstreamSteps:ho,loop:et==null?void 0:et.loop,continues:k?{stopAt:ps(g.map(a=>a.data.step),A.stepId)}:void 0,onCancel:()=>w(null),onRun:(a,f)=>k?lo(A.stepId,a,f):co(A.stepId,a,f)},A.stepId),!Yt&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w6w-modal-body",children:[A.status==="running"&&e.jsx("p",{className:"w6w-muted w6w-small",children:"Running…"}),A.status==="error"&&e.jsxs("div",{className:"w6w-result w6w-error",children:[A.errorCode&&e.jsx("div",{className:"w6w-small",style:{opacity:.75,marginBottom:4},children:e.jsx("code",{children:A.errorCode})}),A.error||"The node failed with no error message."]}),A.status==="done"&&e.jsxs("div",{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{marginBottom:6},children:"Result"}),e.jsx(i.ResultViewer,{value:A.value,maxHeight:360}),A.meta&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{margin:"10px 0 6px"},children:"Metadata"}),e.jsx(i.ResultViewer,{value:A.meta,maxHeight:360})]})]}),A.logs&&A.logs.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{margin:"10px 0 6px"},children:"Console output"}),e.jsx(be.Copyable,{value:A.logs.join(`
1
+ "use client";"use strict";var bo=Object.defineProperty;var vo=(t,s,o)=>s in t?bo(t,s,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[s]=o;var lt=(t,s,o)=>vo(t,typeof s!="symbol"?s+"":s,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),le=require("@xyflow/react"),u=require("react"),i=require("./connection-app-meta-CQ85y_6M.cjs"),be=require("./CodeBlock-85y9qvE3.cjs"),Re=require("@w6w/expr");function jo({x:t,y:s,items:o,onAction:n,onClose:r}){const l=u.useRef(null),[c,p]=u.useState({left:t,top:s});u.useLayoutEffect(()=>{const x=l.current,h=x==null?void 0:x.offsetParent;if(!x||!h)return;const m=x.offsetWidth,k=x.offsetHeight;p({left:t+m>h.clientWidth?Math.max(0,t-m):t,top:s+k>h.clientHeight?Math.max(0,s-k):s})},[t,s]),u.useEffect(()=>{var x,h;(h=(x=l.current)==null?void 0:x.querySelector("[role=menuitem]"))==null||h.focus({preventScroll:!0})},[]),u.useEffect(()=>{const x=k=>{var v;(v=l.current)!=null&&v.contains(k.target)||r(!1)},h=k=>{var v;(v=l.current)!=null&&v.contains(k.target)||r(!1)},m=()=>r(!1);return document.addEventListener("pointerdown",x,!0),document.addEventListener("scroll",h,!0),document.addEventListener("wheel",h,{capture:!0,passive:!0}),window.addEventListener("blur",m),window.addEventListener("resize",m),()=>{document.removeEventListener("pointerdown",x,!0),document.removeEventListener("scroll",h,!0),document.removeEventListener("wheel",h,!0),window.removeEventListener("blur",m),window.removeEventListener("resize",m)}},[r]);const d=x=>{x.disabled||(r(!1),n(x.action))};return e.jsx("div",{ref:l,className:"w6w-note-menu w6w-canvas-menu",role:"menu","aria-label":"Canvas actions","data-testid":"canvas-context-menu",style:{left:c.left,top:c.top},onContextMenu:x=>x.preventDefault(),onKeyDown:x=>{var v;x.stopPropagation();const h=[...((v=l.current)==null?void 0:v.querySelectorAll("[role=menuitem]"))??[]],m=h.indexOf(document.activeElement),k=y=>{var C;return(C=h[(y+h.length)%h.length])==null?void 0:C.focus()};if(x.key==="ArrowDown")k(m+1);else if(x.key==="ArrowUp")k(m<0?-1:m-1);else if(x.key==="Home")k(0);else if(x.key==="End")k(-1);else if(x.key==="Escape"||x.key==="Tab")r(!0);else if(x.key==="Enter"||x.key===" ")m>=0&&d(o[m]);else return;x.preventDefault()},children:o.map(x=>e.jsx("button",{type:"button",role:"menuitem",tabIndex:-1,"aria-disabled":x.disabled||void 0,className:`w6w-note-menu-item${x.danger?" danger":""}${x.separated?" separated":""}`,"data-action":x.action,onClick:()=>d(x),children:x.label},x.action))})}const rn=i.customCssTemplate();function yo({value:t,onChange:s,readOnly:o,stepId:n}){const r=u.useMemo(()=>Co(t),[t]),l=u.useMemo(()=>{var N;return r?((N=i.parseFormDefinition(r))==null?void 0:N.problems)??[]:[]},[r]),[c,p]=u.useState(null),[d,x]=u.useState(null),[h,m]=u.useState(null),[k,v]=u.useState(0);if(!r)return e.jsxs("div",{className:"w6w-result w6w-error",children:["This form is not a form definition (it may be set by an expression). Edit it in the Parameters code view, or reset it.",!o&&e.jsx("div",{children:e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-sm",onClick:()=>s(i.defaultFormDefinition()),children:"Reset to a starter form"})})]});const y=r.fields,C=N=>s({...r,...N}),A=N=>C({fields:N}),w=N=>new Set(y.filter(g=>g.id!==N&&g.name).map(g=>g.name)),D=(N,g)=>{const P=y.find(ie=>ie.id===N);if(!P)return;let X=ko({...P,...g});if(g.label!==void 0&&i.isInputField(P.type)){const ie=w(N),te=i.uniqueName(i.slugName(P.label??""),ie);(!P.name||P.name===te)&&(X={...X,name:i.uniqueName(i.slugName(g.label||P.type),ie)})}const B=P.name&&X.name!==P.name?P.name:null;A(y.map(ie=>{var te;return ie.id===N?X:B&&((te=ie.showIf)==null?void 0:te.field)===B&&X.name?{...ie,showIf:{...ie.showIf,field:X.name}}:ie}))},$=(N,g=y.length)=>{const P=an(y),X=i.newField(N,P,w()),B=[...y];B.splice(g,0,X),A(B),p(P)},M=(N,g)=>{const P=y.findIndex(te=>te.id===N);if(P<0)return;const X=g>P?g-1:g;if(X===P||X<0||X>=y.length)return;const B=[...y],[ie]=B.splice(P,1);B.splice(X,0,ie),A(B)},R=N=>{const g=an(y),P={...structuredClone(N),id:g};P.name&&(P.name=i.uniqueName(P.name,w()));const X=y.findIndex(ie=>ie.id===N.id)+1,B=[...y];B.splice(X,0,P),A(B),p(g)},L=()=>{x(null),m(null)},E=(N,g)=>{if(N.preventDefault(),o)return L();d&&M(d,g),L()},z=(N,g)=>{if(o||!d)return;N.preventDefault(),N.dataTransfer.dropEffect="move";const P=N.currentTarget.getBoundingClientRect();m(N.clientY>P.top+P.height/2?g+1:g)},Y=y.filter(N=>i.isInputField(N.type)&&N.name);return e.jsxs("div",{className:"w6w-form-builder","data-testid":"form-builder",children:[l.length>0&&e.jsx("ul",{className:"w6w-form-problems","data-testid":"form-problems",children:l.map(N=>e.jsxs("li",{children:[e.jsx(be.Icon,{name:"warning",size:12})," ",N.fieldId?e.jsx("button",{type:"button",className:"w6w-form-problem-link",onClick:()=>p(N.fieldId??null),children:N.message}):N.message]},`${N.fieldId??"form"}:${N.message}`))}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Form title"}),e.jsx("input",{type:"text",value:r.title??"",disabled:o,"aria-label":"Form title",onChange:N=>C({title:N.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Description"}),e.jsx("textarea",{rows:2,value:r.description??"",disabled:o,"aria-label":"Form description",onChange:N=>C({description:N.target.value||void 0})})]}),e.jsxs("div",{className:"w6w-form-section-label",children:["Fields ",e.jsx("span",{className:"w6w-muted",children:"· drag to reorder"})]}),e.jsxs("div",{className:"w6w-form-fields","data-testid":"form-fields",onDragLeave:N=>{N.currentTarget.contains(N.relatedTarget)||m(null)},children:[y.length===0&&e.jsx("div",{className:`w6w-form-empty${h===0?" is-drop-target":""}`,onDragOver:N=>{o||!d||(N.preventDefault(),m(0))},onDrop:N=>E(N,0),children:"No fields yet. Add one below."}),y.map((N,g)=>{const P=c===N.id,X=["w6w-form-field",P?"is-open":"",d===N.id?"is-dragging":"",h===g?"is-drop-before":"",h===g+1&&g===y.length-1?"is-drop-after":"",N.type==="pageBreak"?"is-page-break":""].filter(Boolean).join(" ");return e.jsxs("div",{className:X,"data-field-id":N.id,onDragOver:B=>z(B,g),onDrop:B=>E(B,h??g),children:[e.jsxs("div",{className:"w6w-form-field-head",children:[e.jsx("button",{type:"button",className:"w6w-icon-btn w6w-router-grip",draggable:!o,disabled:o,"aria-label":`Reorder ${_t(N)}`,title:"Drag to reorder · arrow keys to move",onDragStart:B=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",N.id);const ie=B.currentTarget.closest(".w6w-form-field");ie&&B.dataTransfer.setDragImage(ie,16,16),x(N.id)},onDragEnd:L,onKeyDown:B=>{B.key!=="ArrowUp"&&B.key!=="ArrowDown"||(B.preventDefault(),M(N.id,B.key==="ArrowUp"?g-1:g+2))},children:e.jsx(be.Icon,{name:"grip",size:14})}),e.jsxs("button",{type:"button",className:"w6w-form-field-summary","aria-expanded":P,onClick:()=>p(P?null:N.id),children:[e.jsx("span",{className:"w6w-form-field-type",children:i.FIELD_TYPE_LABELS[N.type]}),e.jsxs("span",{className:"w6w-form-field-label",children:[_t(N),N.required?e.jsx("span",{className:"w6w-form-req",children:" *"}):null]}),N.name&&i.isInputField(N.type)&&e.jsx("code",{className:"w6w-form-field-name",children:N.name}),N.showIf&&e.jsx("span",{className:"w6w-form-field-badge",title:"Shown only when a condition holds",children:"if"}),e.jsx(be.Icon,{name:"chevron-down",size:12})]}),!o&&e.jsx(i.IconButton,{label:`Duplicate ${_t(N)}`,icon:"copy",onClick:()=>R(N)}),e.jsx(i.DeleteButton,{label:`Remove ${_t(N)}`,disabled:o,onClick:()=>A(y.filter(B=>B.id!==N.id))})]}),P&&e.jsx(Ao,{field:N,earlier:Y.filter(B=>y.indexOf(B)<g&&B.id!==N.id),readOnly:o,stepId:n,onPatch:B=>D(N.id,B)})]},N.id)})]}),!o&&e.jsx(i.Combobox,{className:"w6w-form-add",mode:"combobox","aria-label":"Add a field",placeholder:"+ Add a field…",options:No,value:"",onChange:N=>{$(N),v(g=>g+1)}},k),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Submit button label"}),e.jsx("input",{type:"text",value:r.submitLabel??"",placeholder:"Submit",disabled:o,"aria-label":"Submit button label",onChange:N=>C({submitLabel:N.target.value||void 0})})]}),e.jsx(Po,{form:r,save:C,readOnly:o}),e.jsx(Lo,{form:r,save:C,readOnly:o})]})}const So=[{title:"Text",types:["text","textarea","email","number","phone","url","password"]},{title:"Choice",types:["select","radio","checkboxes","checkbox","rating"]},{title:"Date & time",types:["date","time","datetime"]},{title:"Other",types:["file","hidden"]},{title:"Layout",types:["heading","paragraph","pageBreak"]}],No=So.flatMap(t=>t.types.map(s=>({value:s,label:i.FIELD_TYPE_LABELS[s],group:t.title,keywords:`${t.title} ${s}`})));function Co(t){if(t==null||t==="")return i.defaultFormDefinition();let s=t;if(typeof s=="string")try{s=JSON.parse(s)}catch{return null}if(!s||typeof s!="object"||Array.isArray(s))return null;const o=s;if(!Array.isArray(o.fields))return null;if(o.fields.every(r=>r&&typeof r.id=="string"&&r.id))return o;const n=new Set;return{...o,fields:o.fields.filter(r=>r&&typeof r=="object").map((r,l)=>{let c=typeof r.id=="string"&&r.id&&!n.has(r.id)?r.id:`f_${l+1}`;for(;n.has(c);)c=`${c}_`;return n.add(c),{...r,id:c}})}}function an(t){const s=new Set(t.map(o=>o.id));for(;;){const o=`f_${Math.random().toString(36).slice(2,8)}`;if(!s.has(o))return o}}function ko(t){const s={};for(const[o,n]of Object.entries(t))n===void 0||n===""||(s[o]=n);return s}function _t(t){return t.type==="pageBreak"?t.label?`New page: ${t.label}`:"New page":t.type==="paragraph"?Eo(t.help??"")||"Paragraph":t.label||t.name||i.FIELD_TYPE_LABELS[t.type]}function Eo(t,s=60){return t.length>s?`${t.slice(0,s-1)}…`:t}const To=t=>{if(t.trim()==="")return;const s=Number(t);return Number.isFinite(s)?s:void 0},Io={equals:"is",notEquals:"is not",contains:"contains",notContains:"does not contain",isEmpty:"is empty",isNotEmpty:"is not empty",greaterThan:"is greater than",lessThan:"is less than"};function Ao({field:t,earlier:s,readOnly:o,stepId:n,onPatch:r}){const l=t.type,c=i.isInputField(l),p=i.CHOICE_FIELD_TYPES.has(l),d=i.TEXT_FIELD_TYPES.has(l),x=l==="checkboxes"||l==="select"&&t.multiple,h=(v,y,C={})=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:v}),C.area?e.jsx("textarea",{rows:3,value:String(t[y]??""),placeholder:C.placeholder,disabled:o,"aria-label":v,onChange:A=>r({[y]:A.target.value||void 0})}):e.jsx("input",{type:"text",value:String(t[y]??""),placeholder:C.placeholder,disabled:o,"aria-label":v,onChange:A=>r({[y]:A.target.value||void 0})}),C.hint&&e.jsx("span",{className:"w6w-hint",children:C.hint})]},String(y)),m=(v,y,C)=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:v}),e.jsx("input",{type:"number",value:t[y]===void 0?"":String(t[y]),placeholder:C,disabled:o,"aria-label":v,onChange:A=>r({[y]:To(A.target.value)})})]},String(y)),k=(v,y)=>e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!t[y],disabled:o,onChange:C=>r({[y]:C.target.checked||void 0})}),v]},String(y));return l==="pageBreak"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Next page title","label",{placeholder:"Optional"}),e.jsx("span",{className:"w6w-hint",children:"Everything below this starts a new page with Back / Next."})]}):l==="heading"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Heading","label"),h("Text under the heading","help",{area:!0}),e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]}):l==="paragraph"?e.jsxs("div",{className:"w6w-form-field-body",children:[h("Text","help",{area:!0}),e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]}):e.jsxs("div",{className:"w6w-form-field-body",children:[e.jsxs("div",{className:"w6w-field-row",children:[h(l==="hidden"?"Description":"Label","label"),h("Answer key","name",{hint:t.name?e.jsxs(e.Fragment,{children:["Use as ",e.jsx("code",{children:`{{ nodes.${n??"<trigger>"}.output.data.${t.name} }}`})]}):"Letters, digits and _."})]}),l==="hidden"?h("Value","defaultValue",{hint:"Recorded with every response. A ?name=value in the form URL overrides it."}):e.jsxs(e.Fragment,{children:[h("Help text","help",{placeholder:"Shown under the label"}),(d||l==="number"||l==="select")&&h("Placeholder","placeholder"),e.jsxs("div",{className:"w6w-form-checks",children:[c&&k("Required","required"),l==="select"&&k("Allow several choices","multiple"),p&&k('Offer an "Other" answer',"allowOther"),l==="file"&&k("Allow several files","multiple"),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:t.width==="half",disabled:o,onChange:v=>r({width:v.target.checked?"half":void 0})}),"Half width"]})]})]}),p&&e.jsxs("div",{className:"w6w-form-options","data-testid":"form-choices",children:[e.jsx(ln,{label:"Choices",modes:[["fixed","Fixed list"],["data","From data"]],value:t.optionsFrom?"data":"fixed",readOnly:o,onChange:v=>r({optionsFrom:v==="data"?{items:""}:void 0})}),t.optionsFrom?e.jsx(cn,{source:t.optionsFrom,withValue:!0,readOnly:o,onChange:v=>r({optionsFrom:v})}):e.jsx(Ro,{options:t.options??[],readOnly:o,onChange:v=>r({options:v})})]}),l==="text"&&e.jsxs("div",{className:"w6w-form-options","data-testid":"form-suggestions",children:[e.jsx(ln,{label:"Suggestions as they type",modes:[["none","None"],["fixed","Fixed list"],["data","From data"]],value:t.suggestionsFrom?"data":t.suggestions?"fixed":"none",readOnly:o,onChange:v=>r({suggestions:v==="fixed"?[]:void 0,suggestionsFrom:v==="data"?{items:""}:void 0})}),t.suggestionsFrom?e.jsx(cn,{source:t.suggestionsFrom,readOnly:o,onChange:v=>r({suggestionsFrom:v})}):t.suggestions?e.jsx("textarea",{rows:3,value:t.suggestions.join(`
2
+ `),placeholder:"One per line",disabled:o,"aria-label":"Suggestions",onChange:v=>r({suggestions:v.target.value.split(`
3
+ `)})}):null,(t.suggestions||t.suggestionsFrom)&&e.jsx("span",{className:"w6w-hint",children:"Offered as they type; any other answer is accepted too."})]}),d&&e.jsxs("div",{className:"w6w-field-row",children:[m("Min length","minLength"),m("Max length","maxLength")]}),d&&l!=="email"&&l!=="url"&&e.jsxs("div",{className:"w6w-field-row",children:[h("Pattern (regular expression)","pattern",{placeholder:"e.g. [A-Z]{2}\\d{4}"}),t.pattern&&h("Message when it does not match","patternMessage")]}),l==="textarea"&&m("Rows","rows","4"),l==="number"&&e.jsxs("div",{className:"w6w-field-row",children:[m("Min","min"),m("Max","max"),m("Step","step","any")]}),l==="rating"&&m("Stars","max","5"),(l==="date"||l==="time"||l==="datetime")&&e.jsxs("div",{className:"w6w-field-row",children:[h("Earliest","minDate",{placeholder:dn(l)}),h("Latest","maxDate",{placeholder:dn(l)})]}),x&&e.jsxs("div",{className:"w6w-field-row",children:[m("Pick at least","minSelected"),m("Pick at most","maxSelected")]}),l==="file"&&e.jsxs("div",{className:"w6w-field-row",children:[h("Accepted types","accept",{placeholder:".pdf,image/*"}),m("Max size per file (MB)","maxFileSizeMb","10"),t.multiple&&m("Max files","maxFiles")]}),l!=="hidden"&&l!=="file"&&l!=="checkboxes"&&l!=="checkbox"&&!x&&h("Default answer","defaultValue",{hint:e.jsxs(e.Fragment,{children:["A ?name=value in the form URL overrides it. Can read a pre-form step, e.g."," ",e.jsx("code",{children:"{{ nodes.lookup.output.email }}"}),"."]})}),l==="checkbox"&&e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:t.defaultValue===!0,disabled:o,onChange:v=>r({defaultValue:v.target.checked||void 0})}),"Checked by default"]}),l!=="hidden"&&e.jsx(ss,{field:t,earlier:s,readOnly:o,onPatch:r})]})}function ln({label:t,modes:s,value:o,readOnly:n,onChange:r}){return e.jsxs("div",{className:"w6w-form-mode",children:[e.jsx("span",{className:"w6w-small w6w-muted",children:t}),e.jsx("div",{role:"group","aria-label":t,className:"w6w-form-mode-buttons",children:s.map(([l,c])=>e.jsx("button",{type:"button",className:`w6w-btn w6w-btn-sm w6w-btn-ghost${o===l?" active":""}`,"aria-pressed":o===l,disabled:n,onClick:()=>o!==l&&r(l),children:c},l))})]})}function cn({source:t,withValue:s,readOnly:o,onChange:n}){const r=(l,c,p)=>e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:c}),e.jsx("input",{type:"text",value:t[l]??"",placeholder:p,disabled:o,"aria-label":c,onChange:d=>n({...t,[l]:d.target.value||void 0})})]});return e.jsxs("div",{className:"w6w-stack","data-testid":"form-data-source",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"List"}),e.jsx(i.ExpressionInput,{value:typeof t.items=="string"?t.items:void 0,readOnly:o,placeholder:"{{ nodes.get_products.output.items }}","aria-label":"List",onChange:l=>n({...t,items:l})}),e.jsx("span",{className:"w6w-hint",children:"Wire a step into this form trigger: it runs each time the page opens, and this list is read from its output."})]}),e.jsxs("div",{className:"w6w-field-row",children:[r("label","Label key","label · name · title"),s&&r("value","Value key","value · id")]})]})}function dn(t){return t==="time"?"09:00":t==="datetime"?"2026-01-31T09:00":"2026-01-31"}function ss({field:t,earlier:s,readOnly:o,onPatch:n}){var p;const r=t.showIf;if(!r)return s.length===0||o?null:e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost w6w-btn-sm w6w-form-cond-add",onClick:()=>n({showIf:{field:s[s.length-1].name??"",op:"equals",value:""}}),children:"+ Show only when…"});const l=r.op!=="isEmpty"&&r.op!=="isNotEmpty",c=s.find(d=>d.name===r.field);return e.jsxs("div",{className:"w6w-form-cond","data-testid":"form-condition",children:[e.jsx("span",{className:"w6w-small",children:"Show only when"}),e.jsxs("select",{value:r.field,disabled:o,"aria-label":"Depends on",onChange:d=>n({showIf:{...r,field:d.target.value}}),children:[!c&&e.jsx("option",{value:r.field,children:r.field||"—"}),s.map(d=>e.jsx("option",{value:d.name,children:d.label||d.name},d.id))]}),e.jsx("select",{value:r.op,disabled:o,"aria-label":"Comparison",onChange:d=>n({showIf:{...r,op:d.target.value}}),children:i.CONDITION_OPS.map(d=>e.jsx("option",{value:d,children:Io[d]},d))}),l&&((p=c==null?void 0:c.options)!=null&&p.length?e.jsxs("select",{value:r.value??"",disabled:o,"aria-label":"Value",onChange:d=>n({showIf:{...r,value:d.target.value}}),children:[e.jsx("option",{value:"",children:"—"}),c.options.map(d=>e.jsx("option",{value:d.value||d.label,children:d.label},d.value??d.label))]}):e.jsx("input",{type:"text",value:r.value??"",disabled:o,"aria-label":"Value",placeholder:(c==null?void 0:c.type)==="checkbox"?"true":"value",onChange:d=>n({showIf:{...r,value:d.target.value}})})),e.jsx(i.DeleteButton,{label:"Remove condition",disabled:o,onClick:()=>n({showIf:void 0})})]})}function Ro({options:t,readOnly:s,onChange:o}){const[n,r]=u.useState(null),[l,c]=u.useState(null),p=(x,h)=>{if(h<0||h>=t.length||x===h)return;const m=[...t],[k]=m.splice(x,1);m.splice(h,0,k),o(m)},d=(x,h)=>o(t.map((m,k)=>{if(k!==x)return m;const{value:v,...y}={...m,...h};return v?{...y,value:v}:y}));return e.jsxs("div",{className:"w6w-form-options","data-testid":"form-options",children:[e.jsx("span",{className:"w6w-small w6w-muted",children:"Options · the value is recorded (defaults to the label)"}),t.map((x,h)=>e.jsxs("div",{className:`w6w-form-option${n===h?" is-dragging":""}${l===h?" is-drop-before":""}`,onDragOver:m=>{s||n===null||n===h||(m.preventDefault(),c(h))},onDrop:m=>{m.preventDefault(),n!==null&&p(n,h),r(null),c(null)},children:[e.jsx("button",{type:"button",className:"w6w-icon-btn w6w-router-grip",draggable:!s,disabled:s,"aria-label":`Reorder option ${x.label}`,title:"Drag to reorder · arrow keys to move",onDragStart:m=>{m.dataTransfer.effectAllowed="move",m.dataTransfer.setData("text/plain",String(h)),r(h)},onDragEnd:()=>{r(null),c(null)},onKeyDown:m=>{m.key!=="ArrowUp"&&m.key!=="ArrowDown"||(m.preventDefault(),p(h,h+(m.key==="ArrowUp"?-1:1)))},children:e.jsx(be.Icon,{name:"grip",size:12})}),e.jsx("input",{type:"text",value:x.label,disabled:s,"aria-label":`Option ${h+1} label`,onChange:m=>d(h,{label:m.target.value})}),e.jsx("input",{type:"text",value:x.value??"",placeholder:x.label,disabled:s,"aria-label":`Option ${h+1} value`,onChange:m=>d(h,{value:m.target.value})}),e.jsx(i.DeleteButton,{label:`Remove option ${x.label}`,disabled:s,onClick:()=>o(t.filter((m,k)=>k!==h))})]},h)),!s&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost w6w-btn-sm w6w-router-add",onClick:()=>{let x=t.length+1;for(;t.some(h=>h.label===`Option ${x}`);)x++;o([...t,{label:`Option ${x}`}])},children:"+ Add option"})]})}function Po({form:t,save:s,readOnly:o}){const n=t.completion??{},r=c=>{const p={...n,...c};for(const d of Object.keys(p))(p[d]===void 0||p[d]==="")&&delete p[d];s({completion:p})},l=n.type==="redirect";return e.jsxs("details",{className:"w6w-section w6w-form-group","data-testid":"form-completion",children:[e.jsxs("summary",{className:"w6w-section-summary",children:[e.jsx("span",{className:"w6w-section-title",children:"After submitting"}),e.jsx("span",{className:"w6w-section-subtitle",children:l?`Redirect to ${n.redirectUrl||"…"}`:n.title||"Thank-you message"})]}),e.jsxs("div",{className:"w6w-form-group-body",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Show"}),e.jsxs("select",{value:l?"redirect":"message",disabled:o,"aria-label":"Completion",onChange:c=>r({type:c.target.value}),children:[e.jsx("option",{value:"message",children:"A thank-you message"}),e.jsx("option",{value:"redirect",children:"Redirect to a URL"})]})]}),l?e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Redirect URL"}),e.jsx("input",{type:"text",value:n.redirectUrl??"",placeholder:"https://example.com/thanks?email={{email}}",disabled:o,"aria-label":"Redirect URL",onChange:c=>r({redirectUrl:c.target.value})}),e.jsxs("span",{className:"w6w-hint",children:[e.jsx("code",{children:"{{name}}"})," inserts that answer (URL-encoded)."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Title"}),e.jsx("input",{type:"text",value:n.title??"",placeholder:"Thank you!",disabled:o,"aria-label":"Completion title",onChange:c=>r({title:c.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Message"}),e.jsx("textarea",{rows:2,value:n.message??"",disabled:o,"aria-label":"Completion message",onChange:c=>r({message:c.target.value})}),e.jsxs("span",{className:"w6w-hint",children:[e.jsx("code",{children:"{{name}}"})," inserts that answer. With “Wait for the workflow to finish”, a Respond to Webhook step can replace this screen."]})]}),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.allowAnother,disabled:o,onChange:c=>r({allowAnother:c.target.checked||void 0})}),"Offer “Submit another response”"]})]})]})]})}function Lo({form:t,save:s,readOnly:o}){const n=t.settings??{},r=c=>{const p={...n,...c};for(const d of Object.keys(p))(p[d]===void 0||p[d]==="")&&delete p[d];s({settings:p})},l=(c,p,d)=>e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:n[p]??d,disabled:o,onChange:x=>r({[p]:x.target.checked})}),c]});return e.jsxs("details",{className:"w6w-section w6w-form-group","data-testid":"form-settings",children:[e.jsxs("summary",{className:"w6w-section-summary",children:[e.jsx("span",{className:"w6w-section-title",children:"Page settings"}),e.jsxs("span",{className:"w6w-section-subtitle",children:[n.closed?"Closed":"Open"," · ",n.theme??"auto"," theme"]})]}),e.jsxs("div",{className:"w6w-form-group-body",children:[e.jsxs("div",{className:"w6w-form-checks",children:[l("Pre-fill from ?name=value in the URL","allowPrefill",!0),l("Show page progress","showProgress",!0),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.hideBranding,disabled:o,onChange:c=>r({hideBranding:c.target.checked||void 0})}),"Hide “Powered by w6w”"]})]}),e.jsxs("div",{className:"w6w-field-row",children:[e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Theme"}),e.jsxs("select",{value:n.theme??"auto",disabled:o,"aria-label":"Theme",onChange:c=>r({theme:c.target.value}),children:[e.jsx("option",{value:"auto",children:"Follow the visitor's system"}),e.jsx("option",{value:"light",children:"Light"}),e.jsx("option",{value:"dark",children:"Dark"})]})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Accent colour"}),e.jsxs("span",{className:"w6w-form-color",children:[e.jsx("input",{type:"color",value:/^#[0-9a-f]{6}$/i.test(n.accentColor??"")?n.accentColor:"#3355e6",disabled:o,"aria-label":"Accent colour picker",onChange:c=>r({accentColor:c.target.value})}),e.jsx("input",{type:"text",value:n.accentColor??"",placeholder:"#3355e6",disabled:o,"aria-label":"Accent colour",onChange:c=>r({accentColor:c.target.value})})]})]})]}),e.jsxs("label",{className:"w6w-form-check",children:[e.jsx("input",{type:"checkbox",checked:!!n.closed,disabled:o,onChange:c=>r({closed:c.target.checked||void 0})}),"Closed — stop accepting responses"]}),n.closed&&e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Closed message"}),e.jsx("input",{type:"text",value:n.closedMessage??"",placeholder:"This form is no longer accepting responses.",disabled:o,"aria-label":"Closed message",onChange:c=>r({closedMessage:c.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Custom CSS"}),e.jsx("textarea",{rows:8,className:"w6w-form-css",value:n.customCss??rn,spellCheck:!1,wrap:"off",disabled:o,"aria-label":"Custom CSS",onChange:c=>r({customCss:c.target.value===rn?void 0:c.target.value})})]})]})]})}function Fo(t,s,o,n){return t.find(r=>r.nodeId===s&&r.appId===o&&r.triggerKey===n)??null}function Do(t){return(t??"").split(`
4
+ `).map(s=>s.trim().replace(/^(\d+[.)]|[-•*])\s+/,"")).filter(s=>s!=="")}function Mo({workflowId:t,nodeId:s,appId:o,triggerKey:n,appName:r,setup:l,connectionId:c,params:p,readOnly:d}){const x=i.useW6WApi(),[h,m]=u.useState(void 0),[k,v]=u.useState(null),y=u.useRef(null),C=JSON.stringify({connectionId:c,params:p});u.useEffect(()=>{const M=x.listSubscriptionsForWorkflow,R=x.createSubscription;if(!M){m(null);return}let L=!1;return m(void 0),v(null),y.current=null,(async()=>{const E=Fo(await M.call(x,t),s,o,n);if(d||!R||E&&E.status!=="pending")return E;const z=await R.call(x,o,n,{workflowId:t,connectionId:c,params:p,nodeId:s});return y.current=C,z})().then(E=>!L&&m(E)).catch(E=>{L||(m(null),v(E instanceof Error?E.message:String(E)))}),()=>{L=!0}},[x,t,s,o,n,d]);const A=(h==null?void 0:h.status)==="pending"?h.id:null;u.useEffect(()=>{const M=x.createSubscription;if(!A||d||!M||y.current===null||y.current===C)return;const R=setTimeout(()=>{y.current=C,M.call(x,o,n,{workflowId:t,connectionId:c,params:p,nodeId:s}).then(L=>{v(null),m(L)}).catch(L=>v(L instanceof Error?L.message:String(L)))},600);return()=>clearTimeout(R)},[x,A,d,C,o,n,t,s]);const w=h==null?void 0:h.webhookUrl,D=Do(l.instructions),$=(h==null?void 0:h.lastFireAt)??null;return e.jsxs("div",{className:"w6w-stack w6w-url-panel","data-testid":"manual-webhook-panel",children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:[e.jsx("strong",{children:"Webhook URL"})," — ",r," sends its events here."]}),k&&e.jsx("div",{className:"w6w-result w6w-error",children:k}),w?e.jsx("div",{className:"w6w-listen-url",children:e.jsx(be.Copyable,{value:w,readOnly:!0,children:e.jsx("input",{type:"text",readOnly:!0,value:w,"aria-label":"Webhook URL"})})}):h===void 0?e.jsx("p",{className:"w6w-muted w6w-small",children:"Getting the webhook URL…"}):!k&&e.jsx("p",{className:"w6w-muted w6w-small",children:"The webhook URL appears once the workflow is saved."}),e.jsxs("div",{className:"w6w-manual-webhook-note",role:"note","data-testid":"manual-webhook-note",children:[e.jsxs("strong",{children:["Add this URL in ",r," before the trigger works."]})," W6W can't add it for you, and nothing reaches this trigger until it is there."]}),D.length>0&&e.jsxs("div",{className:"w6w-manual-webhook-steps",children:[e.jsxs("span",{className:"w6w-small",children:["How to add it in ",r]}),e.jsx("ol",{className:"w6w-small","data-testid":"manual-webhook-steps",children:D.map((M,R)=>e.jsx("li",{children:M},R))})]}),h&&e.jsx("p",{className:"w6w-muted w6w-small","data-testid":"manual-webhook-status",children:$?`Last event received ${new Date($).toLocaleString()}.`:h.status==="registered"?`Listening. No event from ${r} yet.`:"Starts the workflow once it is published."})]})}function _o(t,s){return s===void 0?[...t]:t.includes(s)?[...t]:[s]}function Oo(t,s,o={}){const n=[],r=t.length;if(r>0){const l=r>1?` ${r} nodes`:"";n.push({action:"duplicate",label:`Duplicate${l}`,disabled:s}),r===1&&o.replaceableTrigger&&n.push({action:"replace-trigger",label:"Replace trigger",disabled:s}),n.push({action:"delete",label:`Delete${l}`,disabled:s,danger:!0})}return n.push({action:"add-node",label:"Add node",disabled:s,separated:r>0}),n.push({action:"add-trigger",label:"Add trigger",disabled:s}),n}const Tn=200,In=200,An=10240;function as(t){const s={};for(const[o,n]of Object.entries(t))s[o]=Math.round(n);return s}const $o=t=>!!t&&Number.isFinite(t.x)&&Number.isFinite(t.y),Wo=t=>!!t&&Number.isFinite(t.width)&&Number.isFinite(t.height);function un(t,s,o){return t&&t.map(n=>{const r=s==null?void 0:s[n.id],l=$o(r==null?void 0:r.position)?r.position:n.position,c=Wo(r==null?void 0:r.size)?r.size:n.size;return{...n,position:as(l),size:as(c)}})}function Rn(t,s,o){if(!s)return t;const n={...t};return t.notes&&(n.notes=un(t.notes,o)),t.sections&&(n.sections=un(t.sections,o)),n}function ms(t,s){return t.sections?{...t,sections:t.sections.map(o=>({...o,nodes:o.nodes.filter(n=>n!==s)}))}:t}function ls(t,s,o){return t.sections?{...t,sections:t.sections.map(n=>({...n,nodes:n.nodes.map(r=>r===s?o:r)}))}:t}function cs(t,s,o){if(!t.sections)return t;const n=new Set(o);return{...t,sections:t.sections.map(r=>{const l=r.nodes.filter(c=>!n.has(c));return r.id===s?{...r,nodes:[...new Set([...l,...o])]}:{...r,nodes:l}})}}function Pn(t,s){return(t.sections??[]).filter(o=>o.nodes.includes(s)).map(o=>o.id)}function Bo(t,s){const o=new TextEncoder;if(o.encode(t).length<=s)return t;let n="",r=0;for(const l of t){const c=o.encode(l).length;if(r+c>s)break;n+=l,r+=c}return n}function ds(t){const s={...t};return t.notes&&(s.notes=t.notes.slice(0,Tn).map(o=>({...o,content:Bo(o.content,An)}))),t.sections&&(s.sections=t.sections.slice(0,In)),s}function Vo(t,s,o){const n={};for(const c of[...t.notes??[],...t.sections??[]])n[c.id]={position:c.position,size:c.size};const r=(c,p)=>c==null?void 0:c.map(d=>{const x=p==null?void 0:p.find(h=>h.id===d.id);return x?{...d,position:x.position,size:x.size}:d}),l=o?t:{...t,...t.notes?{notes:r(t.notes,s==null?void 0:s.notes)}:{},...t.sections?{sections:r(t.sections,s==null?void 0:s.sections)}:{}};return Rn(l,o,n)}const pn=220;function zo(t){return t.length<=pn?{text:t,clipped:!1,length:t.length}:{text:t.slice(0,pn).trimEnd(),clipped:!0,length:t.length}}function Uo({params:t,values:s,testStartState:o,view:n="props",literalKeys:r}){const{sampleValues:l,nodeConfig:c,nodeMeta:p}=i.useExpressionOptions(),d=u.useMemo(()=>i.buildResolveScope(l,o,c,p),[l,o,c,p]),x=i.flattenParams(t),h=v=>{var y;return s[v]!==void 0?s[v]:(y=x.find(C=>C.key===v))==null?void 0:y.default},m=x.filter(v=>v.type!=="section"&&i.isParamVisible(v,h)).map(v=>Re.effectiveParam(v,h));if(i.hasParamCustomization(s)){const v=i.previewCustomization(s.$merge,d,r),y=v!==null&&typeof v=="object"&&!Array.isArray(v),C=fn(m,s,d,r);for(const[w,D]of Object.entries(s))w!=="$merge"&&(C[w]=r!=null&&r.includes(w)?D:i.previewCustomization(D,d));const A=y?{...C,...v}:C;return e.jsxs("div",{className:"w6w-resolved-params",children:[e.jsx("p",{className:"w6w-muted w6w-small",children:y?"JSON customization applied after form values.":`JSON customization is not available as an object in this preview (${String(v)}). Test the step to validate it.`}),n==="code"?e.jsx(i.JsonEditor,{value:JSON.stringify(A,null,2),onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":"Resolved test values (JSON)"}):e.jsx("div",{className:"w6w-resolved-table",children:Object.entries(A).map(([w,D])=>{var $;return e.jsx(us,{label:(($=x.find(M=>M.key===w))==null?void 0:$.label)??w,segments:[{status:"resolved",value:D}]},w)})})]})}if(n==="code"){const v=fn(m,s,d,r);return e.jsx("div",{className:"w6w-resolved-params",children:e.jsx(i.JsonEditor,{value:JSON.stringify(v,null,2),onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":"Resolved test values (JSON)"})})}const k=m.filter(v=>!i.deepEqual(h(v.key),v.default));return m.length===0?e.jsx("div",{className:"w6w-resolved-params",children:e.jsx("p",{className:"w6w-muted w6w-small",children:"This action takes no parameters."})}):k.length===0?e.jsx("div",{className:"w6w-resolved-params",children:e.jsx("p",{className:"w6w-muted w6w-small",children:"Every configured value matches its default — nothing to show here. Switch to JSON to see the full set."})}):e.jsx("div",{className:"w6w-resolved-params w6w-resolved-table",children:k.map(v=>v.type==="vars"?e.jsx(Ho,{param:v,value:s[v.key],scope:d},v.key):e.jsx(us,{label:v.label??v.key,segments:r!=null&&r.includes(v.key)?[{status:"resolved",value:h(v.key)}]:i.resolveParamValue(h(v.key),d)},v.key))})}function fn(t,s,o,n){const r={};for(const l of t)if(n!=null&&n.includes(l.key))r[l.key]=s[l.key]!==void 0?s[l.key]:l.default;else if(l.type==="vars"){const c=s[l.key]??l.default??[],p=i.dataVarRows(c);r[l.key]=p?i.resolveVarsJson(p,o):i.resolveParamJson(c,o)}else r[l.key]=i.resolveParamJson(s[l.key]!==void 0?s[l.key]:l.default,o);return r}function us({label:t,segments:s}){return e.jsxs("div",{className:"w6w-resolved-row",children:[e.jsx("span",{className:"w6w-resolved-label",children:t}),e.jsx("div",{className:"w6w-resolved-value",children:e.jsx(Ln,{segments:s})})]})}function Ho({param:t,value:s,scope:o}){const n=s??t.default??[],r=i.dataVarRows(n);return r===null?e.jsx(us,{label:t.label??t.key,segments:i.resolveParamValue(n,o)}):e.jsxs("div",{className:"w6w-resolved-row",children:[e.jsx("span",{className:"w6w-resolved-label",children:t.label??t.key}),r.length===0?e.jsx("p",{className:"w6w-muted w6w-small",children:"None configured."}):e.jsx("div",{className:"w6w-stack",children:r.map((l,c)=>e.jsxs("div",{className:"w6w-resolved-value",children:[e.jsx("code",{children:l.key||"(no key)"})," → ",e.jsx(Ln,{segments:i.resolveParamValue(l.value,o)})]},c))})]})}function Ln({segments:t}){return e.jsx(e.Fragment,{children:t.map((s,o)=>e.jsx(Jo,{segment:s},o))})}function Jo({segment:t}){switch(t.status){case"resolved":return t.ref?e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx(hn,{value:t.value})]}):e.jsx(hn,{value:t.value});case"unresolved":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx("span",{className:"w6w-param-unresolved",children:"unresolved"})]});case"at-run":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"var",refName:t.ref}),e.jsx("span",{className:"w6w-param-unevaluated",children:"resolved at run"})]});case"not-evaluated":return e.jsxs(e.Fragment,{children:[e.jsx(gt,{kind:"expr"}),e.jsx("span",{className:"w6w-param-unevaluated",children:"not evaluated"})]});case"masked":return e.jsx(gt,{kind:"secret",refName:t.ref})}}function hn({value:t}){const[s,o]=u.useState(!1),n=Go(t),r=zo(n);return r.clipped?e.jsxs(e.Fragment,{children:[s?e.jsx(be.Copyable,{value:n,label:"Copy resolved value",className:"w6w-resolved-copy",children:e.jsx("pre",{className:"w6w-resolved-text-full",children:n})}):e.jsxs("span",{children:[r.text,"…"]}),e.jsx("button",{type:"button",className:"w6w-resolved-more","aria-expanded":s,onClick:()=>o(l=>!l),children:s?"Show less":`Show all (${r.length.toLocaleString()} characters)`})]}):e.jsx("span",{children:n})}const qo={var:"◆",secret:"🔒",expr:"ƒ"};function gt({kind:t,refName:s}){const o=t==="expr"?"expr":i.varLabel(s??"");return e.jsxs("span",{className:`w6w-expr-chip w6w-expr-chip-${t}`,children:[e.jsx("span",{className:"w6w-expr-chip-sigil",children:qo[t]}),e.jsx("span",{className:"w6w-expr-chip-label",children:o})]})}function Go(t){if(t===null)return"null";if(t===void 0)return"(not set)";if(t==="")return'""';if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t)}catch{return String(t)}}function Fn(t){return t.language==="python"||t.language==="typescript"?t.language:"javascript"}function Ko({enabled:t,values:s,onChange:o}){const[n,r]=u.useState(null),l=u.useRef(!1),c=typeof s.code=="string"?s.code:"";return u.useEffect(()=>{if(!t||l.current)return;l.current=!0;const p=i.convertCodeBindingsToReads(c,Fn(s));p.converted!==0&&(r({original:c,converted:p.converted}),o({...s,code:p.code}))},[t,c,s,o]),n?{converted:n.converted,undo:()=>{o({...s,code:n.original}),r(null)}}:null}function Yo({values:t,conversion:s,readOnly:o}){const n=typeof t.code=="string"?t.code:"",r=s,l=i.findCodeBindings(n,Fn(t)).length;return!r&&l===0?null:e.jsxs("output",{className:"w6w-hint w6w-script-converted",children:[r&&e.jsxs(e.Fragment,{children:["Converted ",r.converted," reference",r.converted===1?"":"s"," to code reads",!o&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("button",{type:"button",className:"w6w-script-converted-undo",onClick:r.undo,children:"Undo"})]}),l>0&&" · "]}),l>0&&e.jsxs(e.Fragment,{children:[l," ",e.jsx("code",{children:"{{ }}"})," left in the code stay",l===1?"s":""," literal text — read ",l===1?"it":"them"," from"," ",e.jsx("code",{children:"state"}),", or bind under Custom input"]})]})}function mn(t,s){return{nodeIds:t.filter(o=>o.selected).map(o=>o.id),edgeIds:s.filter(o=>o.selected).map(o=>o.id)}}function Xo(t,s,o,n){const r=new Set(i.withLoopClosers(t.nodeIds,s,o)),l=new Set(t.edgeIds),c=s.filter(m=>r.has(m.id)),p=[...c.filter(m=>i.isLoopOpener(m.data.step)),...c.filter(m=>!i.isLoopOpener(m.data.step))];let d=s,x=o,h=n;for(const m of p)x=i.bridgeDeletedBodyStep(m.id,d,x),d=d.filter(k=>k.id!==m.id),h=ms(h,m.id);return{nodes:d,edges:x.filter(m=>!l.has(m.id)),canvas:h}}function Zo(t,s,o){var p;const n=new Set(t.nodeIds),r=new Set(t.edgeIds),l=o.filter(d=>r.has(d.id)&&!n.has(d.source)&&!n.has(d.target)),c=[];if(n.size===1)c.push(i.deleteStepMessage(t.nodeIds[0],s,o));else if(n.size>1){c.push(`Delete nodes ${[...n].map(h=>`"${h}"`).join(", ")}? Their connections are removed too.`);const d=new Set,x=new Set(i.withLoopClosers([...n],s,o));for(const h of n)if(i.isLoopOpener((p=s.find(m=>m.id===h))==null?void 0:p.data.step))for(const m of i.loopBody(h,s,o))x.has(m)||d.add(m);d.size&&c.push(`Loop body steps ${[...d].map(h=>`"${h}"`).join(", ")} stay as standalone steps.`)}return l.length&&c.push(`Delete ${l.length===1?"connection":"connections"} ${l.map(d=>`"${d.source} → ${d.target}"`).join(", ")}?`),c.join(" ")}function Ot(t,s,o,n,r){const l=i.flowToWorkflow({...t,connections:n},s,o);return{nodes:l.nodes.map(({with:c,...p})=>c&&Object.keys(c).length?{...p,with:c}:p),edges:l.edges??[],connections:l.connections??{},canvas:r,positions:Object.fromEntries(s.map(c=>[c.id,c.position]))}}function Qo(t,s){const o=i.workflowToFlow({...t,...s});return{...o,nodes:o.nodes.map(n=>({...n,position:s.positions[n.id]??n.position}))}}class ei{constructor(s,o=100){lt(this,"past",[]);lt(this,"future",[]);lt(this,"present");lt(this,"group");lt(this,"limit");this.limit=o,this.present=JSON.stringify(s)}reset(s){this.present=JSON.stringify(s),this.past=[],this.future=[],this.group=void 0}record(s,o){const n=JSON.stringify(s);n!==this.present&&((!o||o!==this.group)&&(this.past.push(this.present),this.past.length>this.limit&&this.past.shift()),this.present=n,this.group=o,this.future=[])}mark(){return this.present}rollbackTo(s){if(this.present===s)return;const o=this.past.lastIndexOf(s);return o>=0&&(this.past.length=o),this.present=s,this.future=[],this.group=void 0,JSON.parse(s)}undo(){const s=this.past.pop();if(s!==void 0)return this.future.push(this.present),this.present=s,this.group=void 0,JSON.parse(s)}redo(){const s=this.future.pop();if(s!==void 0)return this.past.push(this.present),this.present=s,this.group=void 0,JSON.parse(s)}}function ns(t){var o;const s=t;return!!(s!=null&&s.isContentEditable||(o=s==null?void 0:s.closest)!=null&&o.call(s,'input, textarea, select, [contenteditable="true"], [contenteditable=""], [role="textbox"], .cm-editor'))}const ti=64,xt=24,tt=32;function $t(t){var s,o;return{width:((s=t.measured)==null?void 0:s.width)??t.width??200,height:((o=t.measured)==null?void 0:o.height)??t.height??64}}function si(t,s){return t.x<s.x+s.width&&t.x+t.width>s.x&&t.y<s.y+s.height&&t.y+t.height>s.y}function ni(t){const s=(r,l)=>{const c=new Map;for(const x of t){const h=x.position[r];c.set(h,Math.max(c.get(h)??0,$t(x)[l]))}const p=new Map;let d=Number.NEGATIVE_INFINITY;for(const[x,h]of[...c].sort(([m],[k])=>m-k)){const m=Math.max(x,d);p.set(x,m),d=m+h+ti}return p},o=s("x","width"),n=s("y","height");return t.map(r=>({...r,position:{x:o.get(r.position.x)??r.position.x,y:n.get(r.position.y)??r.position.y}}))}function oi(t,s,o){var p;const n=ni(i.relayoutNodes(t,s));if(!((p=o.sections)!=null&&p.length))return{nodes:n,canvas:o};const r=new Map(n.map(d=>[d.id,d])),l=(o.notes??[]).map(d=>({...d.position,...d.size}));for(const d of o.sections)d.nodes.some(x=>r.has(x))||l.push({...d.position,...d.size,y:d.position.y-tt,height:d.size.height+tt});const c=o.sections.map(d=>{const x=new Set(d.nodes),h=n.filter(D=>x.has(D.id));if(!h.length)return d;const m=Math.min(...h.map(D=>D.position.x))-xt,k=Math.min(...h.map(D=>D.position.y))-xt,v=Math.max(...h.map(D=>D.position.x+$t(D).width)),y=Math.max(...h.map(D=>D.position.y+$t(D).height)),C={x:m,y:k,width:v+xt-m,height:y+xt-k},A=[...l,...[...r.values()].filter(D=>!x.has(D.id)).map(D=>({...D.position,...$t(D)}))].sort((D,$)=>D.y-$.y);for(const D of A){const $={...C,y:C.y-tt,height:C.height+tt};si($,D)&&(C.y=D.y+D.height+xt+tt)}const w=C.y-k;for(const D of h)r.set(D.id,{...D,position:{x:D.position.x,y:D.position.y+w}});return l.push({...C,y:C.y-tt,height:C.height+tt}),{...d,position:{x:C.x,y:C.y},size:{width:C.width,height:C.height}}});return{nodes:n.map(d=>r.get(d.id)??d),canvas:{...o,sections:c}}}const os=6;function ii(t){let s=2166136261;for(let o=0;o<t.length;o++)s^=t.charCodeAt(o),s=Math.imul(s,16777619);return s>>>0}function ri(t){const s=new Map;let o=new Set;for(const n of[...new Set(t)].sort()){o.size===os&&(o=new Set);let r=ii(n)%os;for(;o.has(r);)r=(r+1)%os;o.add(r),s.set(n,r+1)}return s}function Bt(t){return`var(--w6w-loop-${t})`}function Dn(t,s){const o=[],n=new Set([t]);for(let r=s.get(t);r&&!n.has(r);r=s.get(r))n.add(r),o.unshift(r);return o}function ai(t,s,o){return s.size===0?t:t.map(n=>{var c;if(((c=n.data)==null?void 0:c.when)!=="each")return n;const r=n.sourceHandle===i.EACH_SOURCE_HANDLE?n.source:o.get(n.source),l=r?s.get(r):void 0;return l===void 0?n:{...n,style:{...n.style,"--w6w-loop-color":Bt(l)}}})}function li(t,s){const o=s.get(t);return o===void 0?void 0:{"--w6w-loop-color":Bt(o)}}function ci(t){const s=[];for(const o of t){const n=i.isLoopOpener(o.data.step);(n||o.data.loopOf)&&s.push([o.id,n?1:0,o.data.loopOf])}return JSON.stringify(s)}function di(t){const s=JSON.parse(t);return{tones:ri(s.filter(o=>o[1]===1).map(o=>o[0])),loopOf:new Map(s.map(o=>[o[0],o[2]]))}}const wn="Paused — test runs stop before this node",gn="Disabled — skipped in every run";function st(t){var s;return((s=t.ui)==null?void 0:s.paused)===!0}function We(t){return t.disabled===!0}function Mn(t,s){const{ui:o,...n}=t,{paused:r,...l}=o??{},c=s?{...l,paused:!0}:l;return Object.keys(c).length>0?{...n,ui:c}:n}function _n(t,s){const{disabled:o,...n}=t;return s?{...n,disabled:!0}:n}function ps(t,s){return t.filter(o=>o.id!==s&&st(o)).map(o=>o.id)}const ui=["nodes","steps"];function xn(t,s){for(const o of ui){const n=`${o}.${s}.output`;if(!t.startsWith(n))continue;const r=t.slice(n.length);if(r===""||r[0]==="."||r[0]==="[")return`foreach.item${r}`}return null}function Wt(t,s,o){if(typeof t=="string"){if(!t.includes("{{"))return t;const n=i.parseRootAnchoredTemplate(t);let r=!1;const l=n.map(c=>{if(c.kind!=="var"||c.ref===void 0)return c;const p=xn(c.ref,s);return p===null?c:(r=!0,o.includes(c.ref)||o.push(c.ref),{...c,ref:p})});return r?Re.serializeTemplate(l):t}if(i.isDollarPath(t)){const n=t.$;if(typeof n!="string")return t;const r=xn(n,s);return r===null?t:(o.includes(n)||o.push(n),{$:r})}if(Array.isArray(t)){let n=!1;const r=t.map(l=>{const c=Wt(l,s,o);return c!==l&&(n=!0),c});return n?r:t}if(typeof t=="object"&&t!==null){let n=!1;const r={};for(const[l,c]of Object.entries(t)){const p=Wt(c,s,o);p!==c&&(n=!0),r[l]=p}return n?r:t}return t}function pi(t){if(typeof t=="string"){if(!t.includes("{{"))return!1;const s=i.parseRootAnchoredTemplate(t);return s.length===1&&s[0].kind==="var"}return i.isDollarPath(t)&&typeof t.$=="string"}function On(t){return Array.isArray(t)&&t.length===1&&pi(t[0])}function fi(t){var s;try{const o=i.normalizeInput(t);if(!Array.isArray(o.nodes))return{};const n={},r=(p,d)=>{const x=Object.hasOwn(n,p)?n[p]:[];x.push(d),n[p]=x},l=new Map(o.nodes.map(p=>[p.id,p])),c=new Set;for(const[p,d]of Object.entries(i.definitionLoops(o))){const x=l.get(p);if(x&&On((s=x.with)==null?void 0:s.items)&&r(p,{code:"foreach_wrapped_items",fix:{kind:"unwrap_items",label:"Unwrap Items"}}),"invalid"in d){r(p,{code:"loop_body_invalid",reason:{...d.invalid}});continue}const h=d.body[d.body.length-1];i.isTandemOpener(x)&&!i.closesOpener(x,h===void 0?void 0:l.get(h))&&r(p,{code:"loop_closer_missing"});for(const m of d.body)i.closesOpener(x,l.get(m))&&c.add(m);for(const m of d.body){const k=l.get(m);if(!(k!=null&&k.with))continue;const v=[];Wt(k.with,p,v),v.length>0&&r(m,{code:"foreach_body_refs_output",foreachId:p,refs:v,fix:{kind:"use_current_item",foreachId:p,label:"Use Current item"}})}}for(const p of o.nodes)i.isLoopCloser(p)&&!c.has(p.id)&&r(p.id,{code:"loop_closer_orphan"});return n}catch{return{}}}function hi(t){const s=new Set,o=n=>{if(typeof n=="string")s.add(n);else if(Array.isArray(n))for(const r of n)o(r)};return o(t),s}function mi(t){var s,o;try{const n=i.normalizeInput(t);if(!Array.isArray(n.nodes))return[];const r=n.nodes.filter(R=>typeof R=="object"&&R!==null&&typeof R.id=="string"),l=i.effectiveEdges({...n,nodes:r}).filter(R=>typeof(R==null?void 0:R.from)=="string"&&typeof(R==null?void 0:R.to)=="string"),c=[];for(const R of r)try{const L=Re.staticWritePaths(Re.effectiveStateConfig((s=R.uses)==null?void 0:s.app,(o=R.uses)==null?void 0:o.action,R.state));L.length>0&&c.push({id:R.id,paths:L})}catch{}if(c.length<2)return[];const p=new Map;for(const R of r)for(const L of i.controlOwnedIds(R))p.has(L)||p.set(L,R.id);const d=R=>{const L=[R];let E=R;for(;p.has(E)&&(E=p.get(E),!L.includes(E));)L.push(E);return L},x=R=>{const L=d(R);return L[L.length-1]},h=new Map;for(const R of l){const L=h.get(R.from)??[];L.push(R.to),h.set(R.from,L)}const m=new Map,k=R=>{const L=m.get(R);if(L)return L;const E=new Set,z=[...h.get(R)??[]];for(;z.length>0;){const Y=z.pop();if(!E.has(Y)){E.add(Y);for(const N of h.get(Y)??[])z.push(N)}}return m.set(R,E),E},v=(R,L)=>R===L||k(R).has(L),y=r.filter(R=>{var L;return((L=R.uses)==null?void 0:L.app)===i.CONTROL_APP&&R.uses.action==="parallel"}).map(R=>{var E;const L=(E=R.with)==null?void 0:E.branches;return Array.isArray(L)?L.map(hi):[]}),C=(R,L)=>{for(const E of d(L)){const z=R.findIndex(Y=>Y.has(E));if(z>=0)return z}return-1},A=[];for(const R of r){if(R.fanOut!=="parallel")continue;const L=new Map;for(const E of l){if(E.from!==R.id||i.isEachLink(E))continue;const z=E.when??"success",Y=L.get(z)??[];Y.push(E.to),L.set(z,Y)}for(const E of L.values())E.length>=2&&A.push(E)}const w=(R,L)=>{for(const Y of y){const N=C(Y,R),g=C(Y,L);if(N>=0&&g>=0&&N!==g)return!0}const E=x(R),z=x(L);return E===z||k(E).has(z)||k(z).has(E)?!1:A.some(Y=>Y.some((N,g)=>Y.some((P,X)=>g!==X&&v(N,E)&&v(P,z))))},D=new Set,$=[];for(let R=0;R<c.length;R++)for(let L=R+1;L<c.length;L++){const E=c[R],z=c[L];if(!(E.id===z.id||!w(E.id,z.id)))for(const Y of E.paths)for(const N of z.paths){if(!Re.statePathsOverlap(Y,N))continue;const g={code:"state_parallel_write",nodes:[E.id,z.id].sort(),path:[...Y.length<=N.length?Y:N]},P=JSON.stringify([g.nodes,g.path]);D.has(P)||(D.add(P),$.push(g))}}const M=(R,L)=>R<L?-1:R>L?1:0;return $.sort((R,L)=>M(R.code,L.code)||M(R.nodes.join(","),L.nodes.join(","))||M(R.path.join("."),L.path.join(".")))}catch{return[]}}function wi(t){try{const s={};for(const o of mi(t))for(const n of o.nodes){const r=Object.hasOwn(s,n)?s[n]:[];r.push({code:o.code,path:[...o.path],with:o.nodes.filter(l=>l!==n)}),s[n]=r}return s}catch{return{}}}function $n(t,s){var o;if(s.code==="foreach_wrapped_items"){const n=(o=t.with)==null?void 0:o.items;return!t.with||!On(n)?t:{...t,with:{...t.with,items:n[0]}}}if(s.code==="foreach_body_refs_output"){if(!t.with)return t;const n=Wt(t.with,s.foreachId,[]);return n===t.with?t:{...t,with:n}}return t}function bn(t,s,o){return t&&t.nodeId===s&&t.handleType===((o==null?void 0:o.type)??"source")?i.laneForSourceHandle(t.handleId):i.laneForSourceHandle(o==null?void 0:o.id)}function gi(t,s,o,n,r){var x;const l=(x=n.find(h=>h.id===t))==null?void 0:x.data.step,c=i.loopMembership(n,r)[t]!==void 0,p=o==="success"&&c?"each":o;if(p==="each"&&!c&&!i.isLoopOpener(l))return null;const d=o==="success"&&i.isLoopOpener(l)?i.FOREACH_DONE_ROUTE:void 0;return i.loopRefusal(t,s,p,n,r,d)}function Vt(t,s){var o;return(o=t.nodes??t.steps)==null?void 0:o[s]}function fs(t,s){const o=Vt(t,s);return(o==null?void 0:o.status)==="skipped"&&o.skipReason==="not_on_path"}const xi=new Set(["succeeded","failed","canceled"]);function bi(t,s,o=[]){var l,c;if(!t||[...o,s].some(p=>fs(t,p)))return"no-run";const n=Vt(t,s);if(n)return n.status;const r=new Set;for(const p of Object.values(t.nodes??t.steps??{}))if(Array.isArray(p==null?void 0:p.iterations))for(const d of p.iterations){const x=(c=(l=d==null?void 0:d.nodes)==null?void 0:l[s])==null?void 0:c.status;x&&r.add(x)}for(const p of["failed","running","succeeded","skipped"])if(r.has(p))return p;return"pending"}const vn={borderColor:"var(--w6w-border)",borderStyle:"solid",borderWidth:1,opacity:1};function Wn(t,s){const o=s!==void 0&&xi.has(s);switch(t){case"no-run":return vn;case"pending":return o?{borderColor:"var(--w6w-muted)",borderStyle:"dashed",borderWidth:1,opacity:.5}:{borderColor:"var(--w6w-border)",borderStyle:"dashed",borderWidth:1,opacity:1};case"running":return{borderColor:"var(--w6w-accent)",borderStyle:"solid",borderWidth:2,opacity:1};case"succeeded":return{borderColor:"var(--w6w-success)",borderStyle:"solid",borderWidth:2,opacity:1};case"failed":return{borderColor:"var(--w6w-danger)",borderStyle:"solid",borderWidth:2,opacity:1};case"skipped":return{borderColor:"var(--w6w-muted)",borderStyle:"dashed",borderWidth:1,opacity:.7};default:return vn}}function vi(t,s,o,n,r){var c;if(!t||fs(t,s)||r!==void 0&&fs(t,r))return;const l=ji(t,s,o,n);return l==="taken"&&r!==void 0&&((c=Vt(t,r))==null?void 0:c.status)==="skipped"?"skipped":l}function ji(t,s,o,n){const r=Vt(t,s);if(!r)return;if(o==="each")return r.status==="skipped"?"skipped":void 0;const l=o??"success",c=r.output,p=n===i.FOREACH_DONE_ROUTE&&!(c&&typeof c=="object"&&"route"in c);if(n!==void 0&&!p&&r.status==="succeeded")return c&&typeof c=="object"&&"matched"in c?n==="false"!=(c.matched===!0)?"taken":"skipped":c&&typeof c=="object"&&"route"in c&&c.route===n?"taken":"skipped";if(r.status==="succeeded")return l==="success"?"taken":"skipped";if(r.status==="failed")return l==="error"?"taken":"skipped";if(r.status==="skipped")return"skipped"}const jn={fields:[],sampleValues:{}};function ws(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function yi(t,s){var x;const o=t.map(h=>h.id),n=new Set(o),r=new Map(o.map(h=>[h,0])),l=new Map(o.map(h=>[h,[]]));for(const h of s)!n.has(h.source)||!n.has(h.target)||((x=l.get(h.source))==null||x.push(h.target),r.set(h.target,(r.get(h.target)??0)+1));const c=[],p=o.filter(h=>r.get(h)===0);for(;p.length>0;){const h=p.shift();c.push(h);for(const m of l.get(h)??[]){const k=(r.get(m)??0)-1;r.set(m,k),k===0&&p.push(m)}}const d=new Set(c);for(const h of o)d.has(h)||c.push(h);return c}const Si=new Set(["string","number","boolean","object","array"]);function bt(t){if(!Array.isArray(t))return;const s={type:"object",fields:{}};let o=!1;for(const n of t){if(!ws(n)||typeof n.key!="string"||n.key==="")continue;const r=n.key.split(".");let l=s;for(const d of r.slice(0,-1)){const x=l.fields[d];(x==null?void 0:x.type)!=="object"&&(l.fields[d]={type:"object",fields:{}}),l=l.fields[d]}const c=typeof n.type=="string"&&Si.has(n.type)?n.type:"string";let p;if(c==="array"){const d=bt(n.items);p=d?{type:"array",items:d}:{type:"array"}}else c==="object"?p=bt(n.fields??n.properties)??{type:"object",fields:{}}:p={type:c};l.fields[r[r.length-1]]=p,o=!0}return o?s:void 0}function Ni(t,s){var x,h,m,k,v,y,C;const o=t.data.step,n=((x=s.testOutputs)==null?void 0:x[o.id])??((h=s.persistedOutputs)==null?void 0:h[o.id]);if(n!=null)return n;const{app:r,action:l}=o.uses;if(r===i.TRIGGER_APP&&((m=i.internalNodeDef(r,l))==null?void 0:m.group)==="trigger"){const A=i.fieldsToParams(i.asFieldDefs((k=o.with)==null?void 0:k.fields)).map(w=>({key:w.key}));return i.shapeToSkeleton(bt(A))}const c=(v=i.internalNodeDef(r,l))==null?void 0:v.output;if(c&&c.length>0)return i.shapeToSkeleton(bt(c));const p=o.uses.trigger===!0?(y=s.triggerDef)==null?void 0:y.call(s,r,l):(C=s.actionDef)==null?void 0:C.call(s,r,l),d=bt(p==null?void 0:p.output);return d?i.shapeToSkeleton(d):p==null?void 0:p.sample}function Ci(t,s){var p,d,x,h,m;const o=t.data.step,n=(p=s.previewOutputs)==null?void 0:p[o.id];if(n!=null)return n;const{app:r,action:l}=o.uses,c=o.uses.trigger===!0?(x=(d=s.shapes)==null?void 0:d.triggerDef)==null?void 0:x.call(d,r,l):(m=(h=s.shapes)==null?void 0:h.actionDef)==null?void 0:m.call(h,r,l);return c==null?void 0:c.sample}function ki(t){switch(t){case"number":case"integer":return 0;case"boolean":return!1;case"object":return{};case"array":return[];default:return""}}function yn(t,s){const o=ws(t.initialState)?{...t.initialState}:{};for(const n of t.variables??[])!n||typeof n.key!="string"||n.key===""||(n.default!==void 0?o[n.key]=n.default:s||(o[n.key]=ki(n.type)));return o}function is(t){return(i.inferOutputFields(t)??[]).map(s=>s.key)}function Ei(t){const{anchorId:s,nodes:o,edges:n}=t;if(!s)return jn;const r=t.shapes??{},l=t.floating?new Set(o.map(E=>E.id)):i.ancestorIds(s,n);l.delete(s);const c=new Map(o.map(E=>[E.id,E])),p=[],d=[],x=new Map;for(const E of yi(o,n)){if(!l.has(E))continue;const z=c.get(E);if(!z)continue;const{app:Y,action:N}=z.data.step.uses,g=Re.effectiveStateConfig(Y,N,z.data.step.state);if(g.mode==="off")continue;const P=Ni(z,r);if(P!==void 0){const{ops:B}=Re.computeStateWrites(g,P);p.push(...B);for(const ie of is(Re.foldState({},B))){const te=x.get(ie)??new Set;te.add(E),x.set(ie,te)}}const X=Ci(z,t);X!==void 0&&d.push(...Re.computeStateWrites(g,X).ops)}const h=yn(t,!1),m=Re.foldState(h,p),k=is(m);if(k.length===0)return jn;const v=new Set(is(h)),y=new Map,C=new Map;for(const E of n)l.has(E.source)&&(!l.has(E.target)&&E.target!==s||(y.set(E.target,[...y.get(E.target)??[],E.source]),C.set(E.source,[...C.get(E.source)??[],E.target])));const A=[...l].filter(E=>!(y.get(E)??[]).length),w=E=>{const z=new Set,Y=A.filter(N=>!E.has(N));for(;Y.length>0;){const N=Y.pop();if(N===s)return!1;if(!z.has(N)){z.add(N);for(const g of C.get(N)??[])E.has(g)||Y.push(g)}}return!0},D=Re.foldState(yn(t,!0),d),$=d.length>0?Re.foldState({},d):void 0,M=ws($)&&Object.keys($).length>0?$:void 0,R=[],L={};for(const E of k){const z=x.get(E)??new Set,Y=v.has(E)||z.size>0&&w(z);R.push({key:E,path:!0,paths:Y?"all":"some"});const N=i.valueAtPath(D,E);N!==void 0&&(L[`state.${E}`]=N)}return{fields:R,sampleValues:L,...M?{written:M}:{}}}const Ti={registered:{label:"Registered",tone:"ok"},pending:{label:"Registering",tone:"pending"},failed:{label:"Registration failed",tone:"danger"},paused:{label:"Paused",tone:"muted"},destroying:{label:"Removing",tone:"muted"}},Sn="Never fired";function Ii(t){if(!t)return Sn;const s=new Date(t);return Number.isNaN(s.getTime())?Sn:`Last fired ${s.toISOString().slice(0,16).replace("T"," ")} UTC`}function Ai(t,s){var r;if(!(t!=null&&t.status))return null;const o=Ti[t.status];if(!o)return null;const n=t.status==="failed";return{label:o.label,tone:o.tone,error:n?((r=t.lastError)==null?void 0:r.message)??null:null,lastFire:Ii(t.lastFireAt),retryVisible:n&&s}}function Ri(t){const s=new Map;for(const o of t)o.nodeId&&s.set(o.nodeId,o);return s}function Pi(t){return(t??[]).filter(s=>{var o;return((o=s.uses)==null?void 0:o.trigger)===!0})}function Li(t,s){const[o,n]=u.useState({}),r=u.useRef(new Set),l=JSON.stringify([...new Set(s.map(c=>c.data.step.uses.app))].filter(c=>c&&!i.isInternalApp(c)).sort());return u.useEffect(()=>{const c=JSON.parse(l).filter(p=>!r.current.has(p));if(c.length!==0){for(const p of c)r.current.add(p);Promise.all(c.map(async p=>{try{return[p,await t.getAppActions(p)]}catch{return r.current.delete(p),null}})).then(p=>{const d=p.filter(x=>x!==null);d.length!==0&&n(x=>({...x,...Object.fromEntries(d)}))})}},[t,l]),o}function Fi(t,s){const[o,n]=u.useState({}),r=u.useRef(new Set),l=JSON.stringify([...new Set(s.filter(c=>c.data.step.uses.trigger===!0).map(c=>c.data.step.uses.app))].filter(c=>c&&!i.isInternalApp(c)).sort());return u.useEffect(()=>{const c=t.getAppTriggers;if(typeof c!="function")return;const p=JSON.parse(l).filter(d=>!r.current.has(d));if(p.length!==0){for(const d of p)r.current.add(d);Promise.all(p.map(async d=>{try{return[d,await c.call(t,d)]}catch{return r.current.delete(d),null}})).then(d=>{const x=d.filter(h=>h!==null);x.length!==0&&n(h=>({...h,...Object.fromEntries(x)}))})}},[t,l]),o}function Di(t){return(s,o)=>{var n,r;return(r=(n=t[s])==null?void 0:n.find(l=>l.key===o))==null?void 0:r.ports}}const Mi="Which outcome of the source node this edge carries. An error edge is drawn by dragging from the node's error exit port; use this control to re-lane an edge already drawn. An error edge overrides the node’s “On error” policy.";function Nn(t,s,o,n){const r=t.find(l=>l.id===s);return[o,n,r==null?void 0:r.source,r==null?void 0:r.target]}const gs=u.createContext(void 0),xs=u.createContext(new Map),zt=u.createContext({tones:new Map,loopOf:new Map});function Cn(t){return`Can’t draw that edge: this node allows at most ${t} outgoing edge${t===1?"":"s"} per lane.`}const bs=u.createContext(new Map),Bn=u.createContext({byNode:new Map,subs:[]});function _i({apps:t,registration:s,children:o}){return e.jsx(bs.Provider,{value:t,children:e.jsx(Bn.Provider,{value:s,children:o})})}const vs=u.createContext(null);function Oi(t){return e.jsx(le.ReactFlowProvider,{children:e.jsx($i,{...t})})}function kn(t,s){let o=s.length+1;for(;s.includes(`${t}-${o}`);)o++;return`${t}-${o}`}function rs(t){var s,o;return{x:t.position.x,y:t.position.y,w:((s=t.measured)==null?void 0:s.width)??t.width??200,h:((o=t.measured)==null?void 0:o.height)??t.height??64}}function $i({onConnectionResourcesChange:t,value:s,onChange:o,readOnly:n,height:r=480,apps:l,exprOptions:c,project:p,runState:d,stepProblems:x,onTestRun:h,fitViewKey:m,onRunFromNode:k}){var Zs,Qs,en,tn,sn,nn,on;const v=i.useW6WApi(),y=u.useMemo(()=>new Map((l??[]).map(a=>[a.id,a])),[l]),C=Ji(s),[A,w]=u.useState(null),D=u.useMemo(()=>i.centralizeConnections(s),[s.id]),$=u.useMemo(()=>i.workflowToFlow(D),[D]),[M,R]=u.useState(D.connections??{}),L=u.useRef(M),E=u.useCallback(a=>{L.current=a,R(a)},[]),z=u.useCallback(a=>{const f=i.centralizeConnections({nodes:[a],connections:L.current});return f.connections!==L.current&&E(f.connections),f.nodes[0]},[E]),Y=u.useMemo(()=>i.storedViewport(s),[s.id]),N=((Zs=s.settings)==null?void 0:Zs.savePosition)!==!1,[g,P,X]=le.useNodesState($.nodes),B=Li(v,g),ie=Fi(v,g),te=u.useMemo(()=>Di(B),[B]),[T,Z,F]=le.useEdgesState($.edges),[U,J]=u.useState(null),ae=u.useMemo(()=>s.canvas??{},[s.id]),[G,q]=u.useState(ae),[K]=u.useState(()=>new ei(Ot(D,$.nodes,$.edges,M,ae))),se=u.useRef(),[ge,qe]=u.useState(0),[_e,ct]=u.useState(!1),[ke,Ge]=u.useState(null),[Pe,ve]=u.useState(null),[ce,Ie]=u.useState(null),[Be,re]=u.useState(!1),vt=u.useRef({});u.useEffect(()=>{Be||(vt.current={})},[Be]);const[de,Le]=u.useState(null),[Oe,Ae]=u.useState("props"),[je,Ke]=u.useState(null),[Se,Ve]=u.useState(null),[Fe,ze]=u.useState(null),dt=u.useRef(!1),Ee=u.useRef(null),[xe,$e]=u.useState(null),{screenToFlowPosition:De,fitView:Me}=le.useReactFlow(),ut=i.useEffectiveTheme();u.useEffect(()=>{P($.nodes),Z($.edges),J(null),Ie(null),ze(null),Le(null),Ke(null),q(ae),E(D.connections??{}),K.reset(Ot(D,$.nodes,$.edges,D.connections??{},ae)),se.current=void 0},[$,ae,D,P,Z,E,K]),u.useEffect(()=>{P(a=>{const f=new Map(i.stampLoopOf(a,T).map(b=>[b.id,b.data.loopOf]));return a.map(b=>{const j=bi(d,b.id,Dn(b.id,f));return b.data.stepStatus===j&&b.data.runStatus===(d==null?void 0:d.status)?b:{...b,data:{...b.data,stepStatus:j,runStatus:d==null?void 0:d.status}}})}),Z(a=>a.map(f=>{var O;const b=i.edgeLane(f),j=vi(d,f.source,b,typeof((O=f.data)==null?void 0:O.route)=="string"?f.data.route:void 0,f.target),S=i.edgeVisuals(b,j);return f.className===S.className&&f.label===S.label?f:{...f,className:S.className,label:S.label}}))},[d,$,ge,P,Z]),u.useEffect(()=>{P(a=>i.applyStepProblems(a,x))},[x,$,ge,P]);const nt=u.useCallback((a,f)=>{var S,O;const{canvas:b,...j}=a;return!((S=f.notes)!=null&&S.length)&&!((O=f.sections)!=null&&O.length)?j:{...j,canvas:Vo(f,s.canvas,N)}},[s.canvas,N]),ne=u.useCallback((a,f,b)=>{K.record(Ot(s,a,f,L.current,b??G),Be?vt.current:se.current),o(nt(i.flowToWorkflow({...s,connections:L.current},a,f),b??G))},[s,o,G,nt,K,Be]),ot=u.useRef(()=>{});ot.current=a=>{if(n)return;const f=i.editConnectionResources(g.map(j=>j.data.step),L.current,a),b=g.map((j,S)=>({...j,data:{...j.data,step:f.nodes[S]}}));E(f.connections),P(b),ne(b,T)};const Ye=u.useCallback(a=>ot.current(a),[]),jt=u.useCallback(a=>{J(a),Ie(null),P(f=>f.map(b=>({...b,selected:b.id===a}))),Z(f=>f.map(b=>({...b,selected:!1}))),Me({nodes:[{id:a}],duration:300,maxZoom:1})},[P,Z,Me]),[pt,we]=u.useState(null),yt=u.useMemo(()=>pt?g.map(a=>a.id===pt?{...a,className:`${a.className??""} w6w-connection-highlight`.trim()}:a):g,[g,pt]),ft=g.map(a=>({id:a.data.step.id,uses:a.data.step.uses})),Ht=JSON.stringify(ft),St=JSON.stringify([...y]);u.useEffect(()=>{t==null||t({workflowId:s.id,nodes:ft,apps:y,connections:M,readOnly:n,edit:Ye,focusNode:jt,highlightNode:we})},[t,s.id,Ht,St,M,n,Ye,jt]),u.useEffect(()=>()=>t==null?void 0:t(null),[t]);const Nt=u.useCallback(a=>i.canConnect(a.source,a.target,g,T,te,i.routeFromHandle(a.sourceHandle)),[g,T,te]),[it,Ne]=u.useState(null),I=u.useRef(null),ee=u.useRef(null);u.useEffect(()=>{P(a=>i.stampLoopOf(a,T))},[T,P]);const fe=u.useCallback(a=>{if(n)return;const f=i.applyConnect(a.source,a.target,g,T,i.laneForSourceHandle(a.sourceHandle),te,i.routeFromHandle(a.sourceHandle));if(!f){const b=i.laneForSourceHandle(a.sourceHandle),j=i.connectRefusal(a.source,a.target,g,T,b,te,i.routeFromHandle(a.sourceHandle));if(j&&j.refused==="loop"){Ne({nodeId:a.source,reason:j.reason});return}if(j){const O=T.find(W=>W.source===a.source&&i.edgeLane(W)===b);O&&(Z(T.map(W=>({...W,selected:W.id===O.id}))),Ie(O.id),Ze({edgeId:O.id,message:Cn(j.cap)}));return}const S=i.connectConflict(a.source,a.target,g,T,i.laneForSourceHandle(a.sourceHandle));if(!S)return;Z(T.map(O=>({...O,selected:O.id===S}))),Ie(S),Ze({edgeId:S,message:i.idClashMessage("Can’t draw that edge",S,Nn(T,S,a.source,a.target))});return}Ze(null),Ne(null),Z(f),ne(g,f)},[T,g,Z,ne,n,te]),ue=u.useCallback((a,f)=>{var H,Q,pe;if(n||f.isValid)return;const b=f.fromNode;if(!b)return;const j=((H=f.fromHandle)==null?void 0:H.type)==="target"?"target":"source",S=f.toNode;if(S&&j==="source"){const he=gi(b.id,S.id,bn(ee.current,b.id,f.fromHandle),g,T);if(he){Ne({nodeId:b.id,reason:he});return}}const O=(Q=g.find(he=>he.id===b.id))==null?void 0:Q.data.step;if(O){const he=i.nodePortsForStep(O,te);if((j==="source"?he.out:he.in)<1)return}const W="changedTouches"in a?a.changedTouches[0]:a,_=De({x:W.clientX,y:W.clientY});$e({nodeId:b.id,handleType:j,position:_,lane:bn(ee.current,b.id,f.fromHandle),route:i.routeFromHandle((pe=f.fromHandle)==null?void 0:pe.id)}),re(!0)},[n,De,g,T,te]),Xe=u.useCallback((a,f,b)=>{if(n)return;const j=g.find(H=>H.id===a);if(!j)return;const S=rs(j),O=i.laneForSourceHandle(b),W=120,_=f==="target"?{x:S.x-S.w-W,y:S.y}:O==="error"?{x:S.x,y:S.y+S.h+W}:O==="each"?{x:S.x+S.w+W,y:S.y-S.h-W/2}:{x:S.x+S.w+W,y:S.y};$e({nodeId:a,handleType:f,position:_,lane:O,route:i.routeFromHandle(b)}),re(!0)},[n,g]),Ct=u.useCallback(a=>{if(n)return;const f=i.closerDeleteRefusal(a.nodeIds,g,T);if(f!==void 0){Ne({nodeId:f,reason:"closer_delete"});return}if(a.nodeIds.length===0){const b=new Set(a.edgeIds),j=T.filter(O=>!b.has(O.id)),S=i.strandedClosers(g,T,j);if(S.length>0){Ne({nodeId:S[0],reason:"closer_detached"});return}}ze(a)},[n,g,T]),ys=u.useCallback(a=>Ct({nodeIds:[a],edgeIds:[]}),[Ct]),Zn=u.useCallback(a=>{if(n)return;const f=Xo(a,g,T,G);P(f.nodes),Z(f.edges),q(f.canvas),f.nodes.some(b=>b.id===U)||J(null),f.nodes.some(b=>b.id===de)||Le(null),f.edges.some(b=>b.id===ce)||Ie(null),ne(f.nodes,f.edges,f.canvas)},[g,T,G,P,Z,ne,n,U,de,ce]),Ss=u.useCallback(()=>{if(n)return;const a=oi(g,T,G);P(a.nodes),q(a.canvas),dt.current=!0,ne(a.nodes,T,a.canvas)},[g,T,G,P,ne,n]),Qn=u.useCallback(()=>{n||Ss()},[n,Ss]);u.useEffect(()=>{dt.current&&(dt.current=!1,Me({duration:300}))},[g,Me]);const Ns=u.useRef(m);u.useEffect(()=>{Object.is(Ns.current,m)||(Ns.current=m,Me({duration:300}))},[m,Me]);const[kt,Ze]=u.useState(null),rt=u.useMemo(()=>T.find(a=>a.id===ce)??null,[T,ce]),eo=u.useCallback(a=>{if(n||!ce)return;const f=T.find(W=>W.id===ce);if(!f||i.edgeLane(f)===a)return;const b=i.edgeWhenConflict(T,ce,a,g),j=i.relaneRefusal(T,ce,a,g,te),S=b||j?null:i.setEdgeWhen(T,ce,a,g,te);if(!S){if(j){Ze({edgeId:ce,message:Cn(j.cap)});return}Ze({edgeId:ce,message:b?i.idClashMessage("Can’t switch this edge",b,Nn(T,b,f.source,f.target)):"This edge can’t be switched right now."});return}Ze(null),Z(S);const O=S.find(W=>W.source===f.source&&W.target===f.target&&i.edgeLane(W)===a);Ie((O==null?void 0:O.id)??null),ne(g,S)},[T,g,Z,ne,n,ce,te]),to=u.useCallback(a=>{if(n)return;const f=T.filter(j=>j.id!==a);if(f.length===T.length)return;const b=i.strandedClosers(g,T,f);if(b.length>0){Ne({nodeId:b[0],reason:"closer_detached"});return}Z(f),ce===a&&Ie(null),ne(g,f)},[g,T,Z,ne,n,ce]),Jt=u.useCallback(a=>{if(n)return;const f=new Map;for(const V of a){const oe=i.loopCloserOf(V,g,T);oe!==void 0&&f.set(V,oe)}const b=new Set(f.values()),j=V=>{var oe;return i.isLoopCloser((oe=g.find(me=>me.id===V))==null?void 0:oe.data.step)&&!b.has(V)},S=a.find(j),O=[...a.filter(V=>!j(V)),...[...b].filter(V=>!a.includes(V))];if(S!==void 0&&O.length===0){Ne({nodeId:S,reason:"closer_duplicate"});return}const W=O.map(V=>g.find(oe=>oe.id===V)).filter(V=>V!==void 0);if(W.length===0)return;const _=g.map(V=>V.id),H=W.map(V=>{const oe=i.suggestStepId(_,`${V.data.step.id}_copy`);_.push(oe);const me={...i.stripBody(structuredClone(V.data.step)),id:oe};return{id:oe,type:V.type,position:{x:V.position.x+40,y:V.position.y+60},data:{step:me,isInternal:V.data.isInternal},...W.length>1?{selected:!0}:{}}}),Q=[...W.length>1?g.map(V=>V.selected?{...V,selected:!1}:V):g,...H],pe=new Map(W.map((V,oe)=>[V.id,H[oe].id]));let he=T;for(const[V,oe]of f){const me=pe.get(V),Ce=pe.get(oe);me&&Ce&&(he=[...he,i.eachLaneEdge(me,Ce,!0)])}P(Q),he!==T&&Z(he),J(H[0].id),ne(Q,he)},[g,T,P,Z,ne,n]),Cs=u.useCallback(a=>Jt([a]),[Jt]),so=u.useCallback(a=>{if(n)return;const f=i.isInternalApp(a.uses.app),b=g.map(V=>V.id),j=a.id&&!i.stepNameError(a.id,b)?a.id:i.suggestStepId(b,i.slugifyLabel(i.internalNodeLabel(a.uses.app,a.uses.action))),S=z({id:j,uses:a.uses,...a.with&&Object.keys(a.with).length>0?{with:a.with}:{}}),O={id:j,type:f?"control":"step",position:(xe==null?void 0:xe.position)??(Se==null?void 0:Se.position)??{x:80,y:80+g.length*24},data:{step:S,isInternal:f}},W=Se!=null&&Se.replaces?g.find(V=>V.id===Se.replaces):void 0;if(W&&i.isTriggerStep(a.uses)){const V={...O,position:W.position},oe=[...g.filter(wt=>wt.id!==W.id),V],me=i.renameStepInEdges(T,W.id,j),Ce=ls(G,W.id,j);return P(oe),Z(me),q(Ce),Ne(null),J(j),ne(oe,me,Ce),j}let _=[...g,O],H=T,Q=null;const pe=(V,oe,me,Ce)=>{const wt=i.connectRefusal(V,oe,_,T,me,te);wt&&wt.refused==="loop"&&(Q={nodeId:Ce,reason:wt.reason})};if(xe){const[V,oe]=xe.handleType==="target"?[j,xe.nodeId]:[xe.nodeId,j],Ce=(xe.handleType==="source"?i.insertIntoTandem(V,j,_,T,xe.lane,xe.route):null)??i.applyConnect(V,oe,_,T,xe.lane,te,xe.route);Ce||pe(V,oe,xe.lane,xe.nodeId),H=Ce??T}else{const V=g.find(oe=>i.isTriggerStep(oe.data.step.uses));if(i.isTriggerStep(a.uses)){if(!V){const oe=i.findChainRoot(g,T);if(oe){const me=i.applyConnect(j,oe.id,_,T,"success",te);me||pe(j,oe.id,"success",oe.id),H=me??T}}}else{const me=(V&&!T.some(Ce=>Ce.source===V.id)?V:void 0)??i.findChainTail(g,T);if(me){const Ce=i.applyConnect(me.id,j,_,T,"success",te);Ce||pe(me.id,j,"success",me.id),H=Ce??T}}}const he=i.addTandemCloser(j,_,H);return he&&(_=he.nodes,H=he.edges),P(_),H!==T&&Z(H),Ne(Q),J(j),ne(_,H),j},[g,T,P,Z,ne,n,xe,Se,te,z,G]),ks=u.useCallback((a,f)=>{var H;let b=f;const j=(H=g.find(Q=>Q.id===a))==null?void 0:H.data.step;if(f.uses.connection&&!f.uses.connectionRef&&(j!=null&&j.uses.connectionRef)&&j.uses.app===f.uses.app){const Q=i.selectNodeConnection(i.withConnectionRef(f,j.uses.connectionRef),f.uses.connection,g.map(pe=>pe.data.step),L.current);E(Q.connections),b=Q.step}else b=z(f);const S=b.id!==a;if(S&&g.some(Q=>Q.id===b.id))return;const O=g.map(Q=>Q.id===a?{...Q,id:b.id,data:{step:b,isInternal:i.isInternalApp(b.uses.app)}}:Q);if(S){const Q=i.renameStepInEdges(T,a,b.id),pe=ls(G,a,b.id);P(O),Z(Q),q(pe),U===a&&J(b.id),de===a&&Le(b.id),ne(O,Q,pe);return}P(O);const W=new Set(i.routesForStep(b).map(Q=>Q.id)),_=T.filter(Q=>{var pe;return Q.source!==b.id||((pe=Q.data)==null?void 0:pe.route)===void 0||W.has(String(Q.data.route))});_.length!==T.length&&Z(_),ne(O,_)},[g,T,G,P,Z,U,de,ne,z,E]),Qe=u.useCallback(a=>{n||(q(a),ne(g,T,a))},[n,g,T,ne]),no=u.useCallback(()=>{var S;if(n)return;const a=(S=Ee.current)==null?void 0:S.getBoundingClientRect(),f=a?De({x:a.left+a.width/2,y:a.top+a.height/2}):{x:0,y:0},b=G.notes??[],j={id:kn("note",b.map(O=>O.id)),color:"#facc15",position:{x:Math.round(f.x-100),y:Math.round(f.y-60)},size:{width:200,height:120},content:""};Qe(ds({...G,notes:[...b,j]}))},[n,G,De,Qe]),oo=u.useCallback((a,f)=>{if(n)return;const b=f?Math.min(a.x,f.x):a.x,j=f?Math.min(a.y,f.y):a.y,S=f?Math.abs(f.x-a.x):360,O=f?Math.abs(f.y-a.y):240,W=g.filter(he=>{const V=rs(he),oe=V.x+V.w/2,me=V.y+V.h/2;return oe>=b&&oe<=b+S&&me>=j&&me<=j+O}).map(he=>he.id),_=G.sections??[],H=kn("section",_.map(he=>he.id)),Q={id:H,title:"Section",color:"#6366f1",position:{x:Math.round(b),y:Math.round(j)},size:{width:Math.round(S),height:Math.round(O)},nodes:[]},pe={...G,sections:[..._,Q]};Qe(ds(cs(pe,H,W)))},[n,g,G,Qe]);u.useEffect(()=>{if(!_e)return;const a=f=>{f.key==="Escape"&&(ct(!1),Ge(null))};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[_e]);const io=u.useCallback((a,f)=>{var W;if(n)return;const b=(W=G.sections)==null?void 0:W.find(_=>_.id===a);if(!b)return;const j=new Set(b.nodes),S=g.map(_=>j.has(_.id)?{..._,position:{x:_.position.x+f.dx,y:_.position.y+f.dy}}:_),O={...G,sections:(G.sections??[]).map(_=>_.id===a?{..._,position:{x:_.position.x+f.dx,y:_.position.y+f.dy}}:_)};P(S),q(O),ne(S,T,O)},[n,G,g,T,P,ne]),ro=u.useCallback((a,f)=>{if(n)return;const b=a==="note"?{...G,notes:(G.notes??[]).filter(j=>j.id!==f)}:{...G,sections:(G.sections??[]).filter(j=>j.id!==f)};Qe(b)},[n,G,Qe]),ao=a=>{let f=G;for(const b of a){const j=rs(b),S=j.x+j.w/2,O=j.y+j.h/2,W=(f.sections??[]).find(H=>S>=H.position.x&&S<=H.position.x+H.size.width&&O>=H.position.y&&O<=H.position.y+H.size.height),_=Pn(f,b.id);W?(_.length!==1||_[0]!==W.id)&&(f=cs(f,W.id,[b.id])):_.length>0&&(f=ms(f,b.id))}return f},qt=u.useCallback((a,f,b)=>{(async()=>{const j=await v.saveStepTest(s.id,a,f).catch(S=>(console.error("step run fixture save failed",S),null));await v.recordStepTestRun(s.id,a,{stepTestId:(j==null?void 0:j.id)??null,status:b.status,input:f.input,output:b.output,error:b.error,...b.meta?{meta:b.meta}:{}})})().catch(j=>{console.error("step run persist failed",j)})},[v,s.id]),Es=u.useCallback(a=>{const f=g.find(b=>b.id===a);!f||!k&&i.isControlApp(f.data.step.uses.app)||w({stepId:a,status:"collect"})},[g,k]),lo=u.useCallback(async(a,f,b)=>{if(!k)return;const j=g.find(W=>W.id===a);if(!j)return;const S=i.isTriggerStep(j.data.step.uses),O={stopAt:ps(g.map(W=>W.data.step),a),...b?{state:b}:{},...S?{input:f}:{}};w({stepId:a,status:"running"});try{await k(a,O),w(null)}catch(W){const _=W;w({stepId:a,status:"error",error:_.message??String(W),errorCode:_.code})}},[g,k]),Et=u.useCallback((a,f)=>{if(n)return;const b=g.map(j=>j.id===a?{...j,data:{...j.data,step:f(j.data.step)}}:j);P(b),ne(b,T)},[g,T,P,ne,n]),Ts=u.useCallback(a=>Et(a,f=>Mn(f,!st(f))),[Et]),Is=u.useCallback(a=>Et(a,f=>_n(f,!We(f))),[Et]),co=u.useCallback(async(a,f,b)=>{h==null||h();const j=g.find(H=>H.id===a);if(!j)return;const S=j.data.step,O=i.isTriggerStep(S.uses),W=O?{input:f}:{...S.with??{},...f},_=O?{input:f,with:f}:{input:f,with:W};w({stepId:a,status:"running"});try{const H=await v.invokeAction(S.uses.app,S.uses.action,W,{connectionId:i.connectionIdFor(S,L.current),project:p,...b?{state:b}:{},workflowId:s.id,...S.timeoutMs?{timeoutMs:S.timeoutMs}:{}}),Q=H.logs,pe=H.meta;w({stepId:a,status:"done",value:H.value,logs:Q,...pe?{meta:pe}:{}}),qt(a,_,{status:"succeeded",output:H.value,...pe?{meta:pe}:{}})}catch(H){const Q=H;w({stepId:a,status:"error",error:Q.message??String(H),errorCode:Q.code}),qt(a,_,{status:"failed",error:Q.message??String(H)})}},[g,v,qt,p,h,s.id]),Gt=u.useMemo(()=>({onEdit:a=>{Ae("props"),Le(a)},onEditJson:a=>{Ae("json"),Le(a)},onRun:Es,onDuplicate:Cs,onDelete:ys,onTogglePause:Ts,onToggleDisable:Is,runsFromNode:!!k,onAddFromPort:Xe,readOnly:n}),[Es,Cs,ys,Ts,Is,k,Xe,n]);u.useEffect(()=>{const a=Ee.current;if(!a)return;const f=b=>{const j=b.target.closest(".react-flow__node");if(!j)return;const S=j.getAttribute("data-id");S&&(b.stopPropagation(),Gt.onEdit(S))};return a.addEventListener("dblclick",f,!0),()=>a.removeEventListener("dblclick",f,!0)},[Gt]);const at=g.find(a=>a.id===de),Tt=(at==null?void 0:at.data.step)??null,Kt=A?((Qs=g.find(a=>a.id===A.stepId))==null?void 0:Qs.data.step)??null:null,Yt=(A==null?void 0:A.status)==="collect"&&!!Kt,As=u.useMemo(()=>{const a=new Map;for(const f of g)a.set(f.id,i.fanOutState(f.id,T).count);return a},[g,T]),Rs=ci(g),It=u.useMemo(()=>di(Rs),[Rs]),uo=u.useMemo(()=>ai(T,It.tones,It.loopOf),[T,It]),po=u.useMemo(()=>({step:Gi,control:Ki}),[]),[At,Ps]=u.useState({}),[Rt,Ls]=u.useState({}),[Fs,Ds]=u.useState({}),[Pt,Ms]=u.useState({}),[Ue,Lt]=u.useState(null),[_s,Os]=u.useState([]),fo=de??Ue??"";u.useEffect(()=>{const a=v.loadNodeSamples;if(typeof a!="function"||!s.id){Os([]);return}let f=!1;return a(s.id).then(b=>{f||Os(Array.isArray(b)?b:[])},()=>{}),()=>{f=!0}},[v,s.id,fo]);const Ft=u.useMemo(()=>i.indexNodeSamples(_s),[_s]),Xt=u.useMemo(()=>i.splitNodeOutputs(At,Ft,Pt),[At,Ft,Pt]),He=u.useMemo(()=>i.splitPreviewOutputs(At,Ft,Pt),[At,Ft,Pt]),Te=u.useMemo(()=>({actionDef:(a,f)=>{var b;return(b=B[a])==null?void 0:b.find(j=>j.key===f)},triggerDef:(a,f)=>{var b;return(b=ie[a])==null?void 0:b.find(j=>j.key===f)},testOutputs:Xt.fresh,persistedOutputs:Xt.persisted,loopSamples:Fs}),[B,ie,Xt,Fs]),et=u.useMemo(()=>A?i.upstreamStateSources(A.stepId,g,T,Te):void 0,[A,g,T,Te]),ho=u.useMemo(()=>(et==null?void 0:et.steps)??[],[et]),ye=u.useMemo(()=>{const a=i.upstreamStateSources(de,g,T,Te,Ue);return{...a,steps:i.excludeSelfStep(a.steps,de??Ue)}},[de,Ue,g,T,Te]),ht=u.useMemo(()=>Ei({anchorId:de??Ue,nodes:g,edges:T,floating:i.isFloatingDraft(de,Ue,g,T),initialState:s.initialState,variables:s.variables,shapes:Te,previewOutputs:{...He.persisted,...He.fresh}}),[de,Ue,g,T,s.initialState,s.variables,Te,He]),$s=JSON.stringify([...ye.steps.map(a=>a.id),...ye.extraSampleIds??[]]);u.useEffect(()=>{const a=JSON.parse($s);if(!de&&!Ue||a.length===0){Ps({}),Ls({}),Ds({}),Ms({});return}let f=!1;return Promise.all(a.map(async b=>{try{const j=await v.listStepTests(s.id,b),S=j.length?j[j.length-1]:null;return S?{id:b,output:S.lastRunOutput,runAt:S.lastRunAt,meta:S.lastRunMeta,loopSample:i.foreachTestSample(S)}:null}catch{return null}})).then(b=>{if(f)return;const j={},S={},O={},W={};for(const _ of b)_!=null&&_.meta&&(S[_.id]=_.meta),_!=null&&_.loopSample&&(O[_.id]=_.loopSample),!(!_||_.output===void 0||_.output===null)&&(j[_.id]=_.output,W[_.id]=_.runAt);Ps(j),Ms(W),Ls(S),Ds(O)}),()=>{f=!0}},[v,s.id,de,Ue,$s]);const Zt=u.useMemo(()=>i.declaredSamples(g,Te),[g,Te]),Dt=u.useMemo(()=>({persisted:He.persisted,samples:Zt.samples,event:Zt.event}),[He.persisted,Zt]),Ws=u.useMemo(()=>i.upstreamSampleValues(ye.steps,He.fresh,Rt,ye.loop,Dt),[ye.steps,ye.loop,He.fresh,Rt,Dt]),Bs=u.useMemo(()=>i.upstreamSampleValueSources(ye.steps,He.fresh,Rt,ye.loop,Dt),[ye.steps,ye.loop,He.fresh,Rt,Dt]),Vs=i.useExpressionOptions(),zs=u.useMemo(()=>i.nodeConfigSources(g),[g]),Us=u.useMemo(()=>i.nodeConfigValues(g,C.subs),[g,C.subs]),Qt=u.useMemo(()=>i.nodeMetaValues(g,C.subs,y,M),[g,C.subs,y,M]),Hs=u.useMemo(()=>[...new Set(Object.values(M).flatMap(a=>a.connection?[a.connection]:[]))].sort().join(","),[M]),[Js,mo]=u.useState(()=>new Map);u.useEffect(()=>{if(!Hs)return;let a=!0;return v.listConnections().then(f=>{a&&mo(new Map(f.map(b=>[b.id,b])))}).catch(()=>{}),()=>{a=!1}},[v,Hs]);const es=u.useMemo(()=>i.connectionExpressionSources(M,Js,y),[M,Js,y]),ts=u.useMemo(()=>({...c??{},connections:es.sources,steps:ye.steps,hasTrigger:ye.hasTrigger,eventOutputs:ye.eventOutputs,eventOutputsFrom:ye.eventOutputsFrom,loop:ye.loop,stateShape:{fields:ht.fields,...ht.written?{written:ht.written}:{}},nodeConfigs:zs,nodeConfig:Us,nodeMeta:Qt,valueSources:Bs,sampleValues:{...Vs.sampleValues??{},...(c==null?void 0:c.sampleValues)??{},...es.sampleValues,...i.nodeMetaSampleValues(Qt),...Ws,...ht.sampleValues}}),[c,Vs.sampleValues,ye,ht,Ws,Bs,zs,Us,Qt,es]),mt=u.useRef(null);Be||de?mt.current===null&&(mt.current=K.mark()):mt.current=null;const qs=()=>{re(!1),$e(null),Ve(null),Lt(null)},Gs=()=>{const a=mt.current;if(mt.current=null,n||a===null)return;const f=K.rollbackTo(a);f&&Ys(f)},Ks=a=>{if(n)return;const f=K[a]();f&&Ys(f)},Ys=a=>{var j;const f=Qo(s,a);P(f.nodes.map(S=>({...S,selected:S.id===U}))),Z(f.edges.map(S=>({...S,selected:S.id===ce}))),q(a.canvas),E(a.connections),f.nodes.some(S=>S.id===U)||J(null),f.edges.some(S=>S.id===ce)||Ie(null);const b=f.nodes.some(S=>S.id===de);b||Le(null),re(!1),Lt(null),$e(null),ze(null),ve(null),Ve(null),Ke(null),Ne(null),Ze(null),se.current=void 0,qe(S=>S+1),o(nt(i.flowToWorkflow({...s,nodes:a.nodes,connections:a.connections},f.nodes,f.edges),a.canvas)),!b&&!A&&((j=Ee.current)==null||j.focus({preventScroll:!0}))},Xs=u.useRef(Ks);Xs.current=Ks,u.useEffect(()=>{const a=Ee.current;if(!a)return;let f=a.contains(document.activeElement);const b=S=>{S.type==="focusin"&&S.target===document.body||(f=a.contains(S.target))},j=S=>{if(n||S.defaultPrevented||ns(S.target)||!a.contains(S.target)&&!(f&&S.target===document.body))return;const O=S.key.toLowerCase();!(S.ctrlKey||S.metaKey)||S.altKey||O!=="z"&&!(O==="y"&&!S.shiftKey)||(S.preventDefault(),Xs.current(O==="y"||S.shiftKey?"redo":"undo"))};return document.addEventListener("pointerdown",b),document.addEventListener("focusin",b),document.addEventListener("keydown",j),()=>{document.removeEventListener("pointerdown",b),document.removeEventListener("focusin",b),document.removeEventListener("keydown",j)}},[n]);const Mt=u.useCallback((a,f)=>{var _;if(ns(a.target))return;const b=(_=Ee.current)==null?void 0:_.getBoundingClientRect();if(!b)return;a.preventDefault();const j=mn(g,T),S=j.nodeIds,O=_o(S,f),W=f!==void 0&&!S.includes(f);W&&P(g.map(H=>H.selected!==(H.id===f)?{...H,selected:H.id===f}:H)),Ke({x:a.clientX-b.left,y:a.clientY-b.top,flow:De({x:a.clientX,y:a.clientY}),nodeIds:O,edgeIds:W?[]:j.edgeIds})},[g,T,P,De]),wo=u.useCallback(a=>{var f;Ke(null),a&&((f=Ee.current)==null||f.focus({preventScroll:!0}))},[]),go=a=>{const f=je;if(!(!f||n))if(a==="duplicate")Jt(f.nodeIds);else if(a==="delete")Ct({nodeIds:f.nodeIds,edgeIds:f.edgeIds});else if(a==="replace-trigger"){const b=g.find(j=>j.id===f.nodeIds[0]);if(!b)return;$e(null),Ve({position:b.position,tab:"triggers",replaces:b.id}),re(!0)}else $e(null),Ve({position:f.flow,...a==="add-trigger"?{tab:"triggers"}:{}}),re(!0)},xo=e.jsx(vs.Provider,{value:Gt,children:e.jsx(gs.Provider,{value:te,children:e.jsx(xs.Provider,{value:As,children:e.jsx(zt.Provider,{value:It,children:e.jsx(_i,{apps:y,registration:C,children:e.jsx(i.WorkflowProjectProvider,{project:p,workflowId:s.id,children:e.jsx(i.ExpressionOptionsProvider,{value:ts,children:e.jsxs("section",{ref:Ee,className:"w6w-flow",tabIndex:-1,"aria-label":"Workflow editor",style:{width:"100%",height:r,position:"relative"},onFocusCapture:a=>{se.current=ns(a.target)?{}:void 0},onBlurCapture:()=>{se.current=void 0},onKeyDown:a=>{if(a.defaultPrevented||a.key!=="Backspace"&&a.key!=="Delete"||n||de||Be||Fe)return;const f=a.target;if(f.isContentEditable||f.tagName==="INPUT"||f.tagName==="TEXTAREA"||f.tagName==="SELECT"||f.closest("dialog, .w6w-modal")!==null)return;const b=mn(g,T);!b.nodeIds.length&&!b.edgeIds.length||(a.preventDefault(),!b.nodeIds.length&&b.edgeIds.length===1?to(b.edgeIds[0]):Ct(b))},children:[e.jsxs(le.ReactFlow,{nodes:yt,edges:uo,minZoom:.05,defaultEdgeOptions:{type:"smoothstep"},connectionLineType:le.ConnectionLineType.SmoothStep,onNodesChange:X,onEdgesChange:F,onConnect:fe,onConnectStart:(a,f)=>{ee.current=f},onConnectEnd:ue,onPaneClick:()=>Ne(null),onPaneContextMenu:a=>Mt(a),onNodeContextMenu:(a,f)=>Mt(a,f.id),onEdgeContextMenu:a=>Mt(a),onSelectionContextMenu:a=>Mt(a),onMoveStart:()=>Ke(null),isValidConnection:Nt,onNodeDragStop:(a,f,b)=>{const j=ao(b),S=j!==G;if(S&&q(j),!N&&!S){K.record(Ot(s,g,T,L.current,j));return}ne(g,T,j)},onMoveEnd:(a,f)=>{if(!a||n)return;const b=i.flowToWorkflow(s,g,T),j=i.withViewport(b,f);j!==b&&o(j,{viewportOnly:!0})},onSelectionChange:({nodes:a,edges:f})=>{var b,j,S,O;J(((b=a[0])==null?void 0:b.id)??null),Ie(((j=f[0])==null?void 0:j.id)??null),I.current!==(((S=a[0])==null?void 0:S.id)??null)&&(I.current=((O=a[0])==null?void 0:O.id)??null,Ne(null))},nodeTypes:po,nodesDraggable:!n,nodesConnectable:!n,connectOnClick:!1,elementsSelectable:!0,...Y?{defaultViewport:Y}:{fitView:!0,fitViewOptions:{maxZoom:1}},deleteKeyCode:null,colorMode:ut,proOptions:{hideAttribution:!0},children:[e.jsx(le.Background,{gap:16}),e.jsx(le.Controls,{showInteractive:!1,children:!n&&e.jsx(le.ControlButton,{onClick:Qn,title:"Auto-layout — re-flow the graph into columns","aria-label":"Auto-layout the graph",children:e.jsx(be.Icon,{name:"layout"})})}),e.jsx(le.MiniMap,{pannable:!0,zoomable:!0,style:{background:"var(--w6w-panel-2)"}}),!n&&e.jsxs(le.Panel,{position:"top-left",className:"w6w-flow-tools",children:[e.jsx("button",{type:"button",className:"w6w-btn",onClick:()=>re(!0),children:"+ Node"}),e.jsx(i.IconButton,{label:"Add note",icon:"sticky-note",className:"w6w-flow-tool","data-testid":"add-note",onClick:no}),e.jsx(i.IconButton,{label:"Draw section",title:"Draw section — drag a frame on the canvas (Esc cancels)",icon:"frame",className:`w6w-flow-tool${_e?" active":""}`,"aria-pressed":_e,"data-testid":"draw-section",onClick:()=>{ct(!_e),Ge(null)}})]}),!n&&_e&&e.jsx("div",{className:"w6w-section-draw nopan nodrag nowheel","data-testid":"section-draw-surface",onPointerDown:a=>{if(a.button!==0)return;a.currentTarget.setPointerCapture(a.pointerId);const{clientX:f,clientY:b}=a;Ge({sx:f,sy:b,ex:f,ey:b})},onPointerMove:a=>{const{clientX:f,clientY:b}=a;Ge(j=>j&&{...j,ex:f,ey:b})},onPointerUp:()=>{const a=ke;if(Ge(null),ct(!1),!a)return;const f=De({x:a.sx,y:a.sy}),b=Math.abs(a.ex-a.sx)>6||Math.abs(a.ey-a.sy)>6;oo(f,b?De({x:a.ex,y:a.ey}):null)},children:ke&&(()=>{var j;const a=(j=Ee.current)==null?void 0:j.getBoundingClientRect(),f=(a==null?void 0:a.left)??0,b=(a==null?void 0:a.top)??0;return e.jsx("div",{className:"w6w-section-draw-rect",style:{left:Math.min(ke.sx,ke.ex)-f,top:Math.min(ke.sy,ke.ey)-b,width:Math.abs(ke.ex-ke.sx),height:Math.abs(ke.ey-ke.sy)}})})()}),!n&&rt&&i.edgeLane(rt)!=="each"&&((en=g.find(a=>a.id===rt.source))==null?void 0:en.data.step.uses.app)!==i.ROUTER_APP&&e.jsx(le.Panel,{position:"top-right",children:e.jsxs("div",{className:"w6w-edge-lane",children:[e.jsx("span",{className:"w6w-muted w6w-small",children:"Run on"}),["success","error"].map(a=>e.jsx("button",{type:"button",className:`w6w-btn w6w-btn-sm w6w-btn-ghost${i.edgeLane(rt)===a?" active":""}`,"aria-pressed":i.edgeLane(rt)===a,title:Mi,onClick:()=>eo(a),children:a==="success"?"Success":"Error"},a)),(kt==null?void 0:kt.edgeId)===rt.id&&e.jsx("span",{className:"w6w-edge-lane-err w6w-small",role:"alert",children:kt.message})]})}),it&&e.jsx(le.NodeToolbar,{nodeId:it.nodeId,position:le.Position.Bottom,isVisible:!0,children:e.jsx("div",{className:"w6w-loop-notice w6w-small",role:"alert",children:i.loopRefusalMessage(it.reason)})}),e.jsx(i.CanvasLayer,{canvas:G,readOnly:n,savePosition:N,onChange:Qe,onSectionDrop:io,onRequestDelete:(a,f)=>!n&&ve({kind:a,id:f})})]}),Pe&&e.jsx(i.ConfirmModal,{title:Pe.kind==="note"?"Delete note":"Delete section",message:Pe.kind==="note"?"Delete this note?":"Delete this section? Its nodes are kept.",confirmLabel:"Delete",onConfirm:()=>{ro(Pe.kind,Pe.id),ve(null)},onClose:()=>ve(null)}),Be&&e.jsx(i.StepBuilderModal,{initialTab:Se==null?void 0:Se.tab,onClose:()=>{Gs(),qs()},onDone:qs,onAdd:a=>{const f=so(a);return f&&Lt(f),f},onDraftChange:(a,f)=>ks(a,{id:a,...f}),stepIds:g.map(a=>a.id),onOpenStep:a=>{re(!1),$e(null),Ve(null),Lt(null),Ae("props"),Le(a)},workflowId:s.id,upstreamSteps:i.stepBuilderUpstreamSteps(xe,g,T),loop:i.stepBuilderLoop(xe,g,T,Te)}),Tt&&de&&e.jsx(Xi,{workflowId:s.id,step:Tt,restoreVersion:ge,upstreamSteps:ts.steps??[],loop:ts.loop,readOnly:n,fanOutCount:As.get(de)??0,stateOutputFields:(on=i.resolveOutputShape((tn=Te.actionDef)==null?void 0:tn.call(Te,Tt.uses.app,Tt.uses.action),(sn=Te.testOutputs)==null?void 0:sn[de],(nn=Te.persistedOutputs)==null?void 0:nn[de]))==null?void 0:on.fields.map(a=>a.key),initialView:Oe,stepProblems:at==null?void 0:at.data.stepProblems,otherStepIds:g.filter(a=>a.id!==de).map(a=>a.id),onChange:a=>ks(de,a),onClose:()=>Le(null),onCancel:()=>{Gs(),Le(null)},onTestRun:h}),A&&e.jsxs(i.Modal,{title:`${Yt?"Run node":"Test run"}: ${A.stepId}`,onClose:()=>w(null),children:[Yt&&Kt&&e.jsx(zi,{workflowId:s.id,step:Kt,upstreamSteps:ho,loop:et==null?void 0:et.loop,continues:k?{stopAt:ps(g.map(a=>a.data.step),A.stepId)}:void 0,onCancel:()=>w(null),onRun:(a,f)=>k?lo(A.stepId,a,f):co(A.stepId,a,f)},A.stepId),!Yt&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"w6w-modal-body",children:[A.status==="running"&&e.jsx("p",{className:"w6w-muted w6w-small",children:"Running…"}),A.status==="error"&&e.jsxs("div",{className:"w6w-result w6w-error",children:[A.errorCode&&e.jsx("div",{className:"w6w-small",style:{opacity:.75,marginBottom:4},children:e.jsx("code",{children:A.errorCode})}),A.error||"The node failed with no error message."]}),A.status==="done"&&e.jsxs("div",{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{marginBottom:6},children:"Result"}),e.jsx(i.ResultViewer,{value:A.value,maxHeight:360}),A.meta&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{margin:"10px 0 6px"},children:"Metadata"}),e.jsx(i.ResultViewer,{value:A.meta,maxHeight:360})]})]}),A.logs&&A.logs.length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"w6w-muted w6w-small",style:{margin:"10px 0 6px"},children:"Console output"}),e.jsx(be.Copyable,{value:A.logs.join(`
5
5
  `),label:"Copy console output",children:e.jsx("pre",{className:"w6w-result",style:{whiteSpace:"pre-wrap",maxHeight:200,overflow:"auto",margin:0},children:A.logs.join(`
6
- `)})})]})]}),e.jsx("div",{className:"w6w-modal-actions",children:e.jsx("button",{type:"button",className:"w6w-btn",onClick:()=>w(null),children:"Close"})})]})]}),Fe!==null&&e.jsx(i.ConfirmModal,{title:Fe.nodeIds.length===1?"Delete node":Fe.nodeIds.length>1?`Delete ${Fe.nodeIds.length} nodes`:`Delete ${Fe.edgeIds.length} connections`,message:Zo(Fe,g,T),confirmLabel:"Delete",autoFocusConfirm:!0,onConfirm:()=>{Zn(Fe),ze(null)},onClose:()=>ze(null)}),ve&&e.jsx(vo,{x:ve.x,y:ve.y,items:Oo(ve.nodeIds,!!n,{replaceableTrigger:ve.nodeIds.length===1&&g.some(a=>a.id===ve.nodeIds[0]&&i.isTriggerStep(a.data.step.uses))}),onAction:go,onClose:wo})]})})})})})})})});return e.jsx(i.WorkflowConnectionsContext.Provider,{value:{nodes:g.map(a=>a.data.step),connections:M,setConnections:E,readOnly:n},children:xo})}const Wi=["code"];function Ut(t){try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}function Bi(t){try{const s=JSON.parse(t);if(Array.isArray(s))return{items:s}}catch{return null}return Ut(t)}function Vi({items:t,save:s}){if(!t)return e.jsxs("output",{className:"w6w-small",style:{display:"block"},children:[e.jsx("strong",{children:"Items"})," doesn't resolve to a list yet: no step before this one has a saved test that produces it. Test an earlier step, or paste a sample list under"," ",e.jsx("strong",{children:"Override the incoming state"})," below."]});const o=t[0],n=o!==void 0?(i.inferOutputFields(o)??[]).map(r=>r.key):[];return e.jsxs("div",{className:"w6w-testout",children:[e.jsxs("div",{className:"w6w-testout-label",children:[t.length," ",t.length===1?"item":"items"]}),t.length===0?e.jsx("p",{className:"w6w-muted w6w-small",children:"The list is empty, so there is no item to sample."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w6w-testout-label",children:"First item"}),e.jsx(i.ResultViewer,{value:o,maxHeight:220})]}),s==="saved"&&e.jsxs("output",{className:"w6w-small",style:{display:"block"},children:["Saved as this loop's sample.",n.length>0&&e.jsxs(e.Fragment,{children:[" ","Steps on ",e.jsx("strong",{children:"Each item"})," now offer ",e.jsx("strong",{children:"Current item"})," ›"," ",n.map((r,l)=>e.jsxs("span",{children:[l>0&&", ",e.jsx("code",{children:r})]},r)),"."]})]}),s==="failed"&&e.jsx("p",{className:"w6w-small",role:"alert",children:"Couldn't save the sample. Try Test again."})]})}function Vn(t){const s=i.foreachView(t),o=i.passLoopSeed(t),[n,r]=u.useState(null),[l,c]=u.useState("0"),[p,d]=u.useState({}),[x,h]=u.useState({}),m=n??i.loopItemText(s),k=((s==null?void 0:s.outer)??[]).map(C=>({foreachId:C.foreachId,name:C.name??C.foreachId,itemText:p[C.foreachId]??i.loopItemText(C),indexText:x[C.foreachId]??"0",setItemText:A=>d(w=>({...w,[C.foreachId]:A})),setIndexText:A=>h(w=>({...w,[C.foreachId]:A}))})),j=s?i.parseLoopSeed(m,l):void 0;let y=j!=null&&j.ok?{ok:!0,value:j.value}:j;if(s&&(j!=null&&j.ok)){const C={};for(const A of k){const w=i.parseLoopSeed(A.itemText,A.indexText);if(!w.ok){y={ok:!1,error:`${A.name}: ${w.error}`};break}C[A.foreachId]=w.value}y!=null&&y.ok&&(C[s.foreachId]=j.value,y={ok:!0,value:{...j.value,loops:C}})}return o&&(!y||y.ok)&&(y={ok:!0,value:{...y!=null&&y.ok?y.value:{},pass:o}}),{active:!!s,itemText:m,indexText:l,setItemText:r,setIndexText:c,outers:k,parsed:y}}function zn(t){var s;return(s=t.parsed)!=null&&s.ok?t.parsed.value:void 0}function vs(t){return t.parsed&&!t.parsed.ok?t.parsed.error:null}function Un({seed:t,readOnly:s}){if(!t.active)return null;const o=vs(t);return e.jsxs("div",{className:"w6w-field w6w-loop-seed",children:[t.outers.map(n=>e.jsxs("div",{"data-testid":`loop-seed-outer-${n.foreachId}`,children:[e.jsxs("span",{children:[n.name," item"]}),e.jsx("textarea",{rows:3,value:n.itemText,readOnly:s,spellCheck:!1,"aria-label":`${n.name} item`,onChange:r=>n.setItemText(r.target.value)}),e.jsxs("span",{children:[n.name," index"]}),e.jsx("input",{type:"text",inputMode:"numeric",value:n.indexText,readOnly:s,"aria-label":`${n.name} index`,onChange:r=>n.setIndexText(r.target.value)})]},n.foreachId)),e.jsx("span",{children:"Current item"}),e.jsx("textarea",{rows:3,value:t.itemText,readOnly:s,spellCheck:!1,"aria-label":"Current item",onChange:n=>t.setItemText(n.target.value)}),e.jsx("span",{children:"Index"}),e.jsx("input",{type:"text",inputMode:"numeric",value:t.indexText,readOnly:s,"aria-label":"Index",onChange:n=>t.setIndexText(n.target.value)}),e.jsx("span",{className:"w6w-hint",children:"This step runs once per item of the For each. Test it as one iteration — starting from the sample item, or edit it."}),o&&e.jsx("span",{className:"w6w-hint",role:"alert",children:o})]})}function hs({text:t,onChange:s,seeds:o,readOnly:n,expand:r,hint:l}){const c=Ut(t),p=c?Object.keys(c).length:0,d=p>0,[x,h]=u.useState(d);u.useEffect(()=>{(d||r)&&h(!0)},[d,r]);const m=k=>{s(JSON.stringify(k.lastRunOutput??k.input??{},null,2)),h(!0)};return e.jsxs("div",{className:"w6w-field w6w-incoming-state",children:[e.jsx("span",{children:"Incoming state"}),o.length>0&&e.jsx("div",{className:"w6w-seed-picker",children:e.jsx("div",{className:"w6w-seed-chips",children:o.map(k=>e.jsxs("button",{type:"button",className:"w6w-chip w6w-seed-chip",title:`Use ${k.label}'s saved test as the incoming state`,disabled:n,onClick:()=>m(k.test),children:[e.jsx("code",{children:k.label}),k.test.lastRunStatus?e.jsxs("span",{className:"w6w-muted w6w-small",children:[" · ",k.test.lastRunStatus]}):null]},k.stepId))})}),e.jsxs("details",{className:"w6w-state-override",open:x,onToggle:k=>h(k.currentTarget.open),children:[e.jsxs("summary",{children:["Override the incoming state",p>0?` · ${p} key${p===1?"":"s"} set`:""]}),e.jsx("textarea",{rows:3,value:t,readOnly:n,spellCheck:!1,"aria-label":"Incoming state override (JSON)",onChange:k=>s(k.target.value)}),e.jsx("span",{className:"w6w-hint",children:l??e.jsxs(e.Fragment,{children:["JSON whose keys replace this step's parameters by name, for this test only — so a script's data goes under ",e.jsx("code",{children:"input"}),": ",e.jsx("code",{children:'{"input": {…}}'}),". Upstream outputs already reach ",e.jsx("code",{children:"{{ nodes.<id>.output }}"})," bindings from their saved tests. Reach for this to test against a state the flow cannot currently produce — a field no upstream step returns yet, or a case you can't reproduce by running the flow."]})})]})]})}function zi({workflowId:t,step:s,upstreamSteps:o,loop:n,onRun:r,onCancel:l,continues:c}){var G;const p=i.useW6WApi(),d=i.isTriggerStep(s.uses),x=i.isInternalApp(s.uses.app),h=u.useMemo(()=>{var q;return d?i.asFieldDefs((q=s.with)==null?void 0:q.fields):[]},[d,s.with]),m=u.useMemo(()=>d?i.fieldsToParams(h):x?i.internalNodeParams(s.uses.app,s.uses.action):null,[d,x,h,s.uses.app,s.uses.action]),[k,j]=u.useState(null),y=m??k;u.useEffect(()=>{if(m)return;if(!s.uses.app||!s.uses.action){j([]);return}let q=!1;return j(null),p.getAppActions(s.uses.app).then(K=>{var se;q||j(((se=K.find(ge=>ge.key===s.uses.action))==null?void 0:se.params)??[])}).catch(()=>!q&&j([])),()=>{q=!0}},[p,m,s.uses.app,s.uses.action]);const[C,A]=u.useState(()=>{var q;return d?i.seedValues(i.asFieldDefs((q=s.with)==null?void 0:q.fields)):{}}),[w,D]=u.useState("{}"),$=i.useSeedSources(t,o,!d),M=Vn(n),R=(G=i.useExpressionOptions().stateShape)==null?void 0:G.written,L=i.startStateFromSeeds($,zn(M),R),E=i.useRememberedTestInput(t,s.id),[z,Y]=u.useState(!1),[N,g]=u.useState(!1);u.useEffect(()=>{if(!E.loaded)return;let q=!1;const K=(se,ge)=>{se&&Object.keys(se).length>0&&(d?A(qe=>({...qe,...se})):D(JSON.stringify(se,null,2)),ge&&g(!0)),Y(!0)};if(E.input!==void 0){K(E.input,!0);return}return p.listStepTests(t,s.id).then(se=>{if(q)return;const ge=se.length?se[se.length-1]:null;K(d?ge==null?void 0:ge.with:ge==null?void 0:ge.input,!1)}).catch(()=>{q||Y(!0)}),()=>{q=!0}},[p,t,s.id,d,E.loaded]);const[P,X]=u.useState(0),B=()=>{E.clear(),g(!1),d?A(i.seedValues(h)):D("{}"),X(q=>q+1)},ie=q=>{A(q),T(!0),g(!1),X(K=>K+1)},[te,T]=u.useState(!0),Z=Ut(w),F=d?te:Z!==null,U=d?C:{...s.with??{},...Z??{}},J=d?null:vs(M),ae=!!y&&z&&F&&!J&&i.requiredParamsFilled(y,U);return e.jsxs("div",{className:"w6w-stepconfig",children:[e.jsx("div",{className:"w6w-modal-body",children:e.jsxs("div",{className:"w6w-stack",children:[c&&e.jsxs("p",{className:"w6w-muted w6w-small","data-testid":"run-from-node-hint",children:["Runs this node, then continues through every node after it",c.stopAt.length>0?e.jsxs(e.Fragment,{children:[" ","and stops before"," ",c.stopAt.length===1?"the paused node":"paused nodes"," ",c.stopAt.map((q,K)=>e.jsxs("span",{children:[K>0?", ":"",e.jsx("code",{children:q})]},q))]}):null,". Disabled nodes are skipped."]}),N&&y!==null&&z&&e.jsx(i.LastUsedNote,{onClear:B}),y===null||!z?e.jsx("p",{className:"w6w-muted w6w-small",children:y===null?"Loading parameters…":"Loading saved values…"}):d?e.jsxs(e.Fragment,{children:[e.jsx(i.PropertyEntryForm,{params:y,values:C,onChange:A,onValidityChange:T},P),s.uses.trigger===!0&&e.jsx(i.TriggerSampleButton,{app:s.uses.app,trigger:s.uses.action,onUse:ie}),y.length===0&&e.jsxs("span",{className:"w6w-hint",children:["This trigger declares no fields — provide a sample payload to run with. It becomes the trigger's output state (",e.jsx("code",{children:"input"}),")."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Runs ",e.jsx("code",{children:s.uses.action})," with the configuration saved on this node — only the incoming state changes per run. Edit the node to change how it is configured."]}),e.jsx(Un,{seed:M}),e.jsx(hs,{text:w,onChange:D,seeds:$})]})]})}),e.jsxs("div",{className:"w6w-modal-actions",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:l,children:"Cancel"}),!ae&&y!==null&&z&&e.jsx("span",{className:"w6w-muted w6w-small",children:J?`${J} Fix it to run.`:F?d?"Fill the required fields to test.":"This step is missing required configuration — set it on the Configure tab.":d?"The payload must be a JSON object to run.":"The incoming state must be a JSON object to run."}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:!ae,onClick:()=>{E.save(d?C:Z??{},y??[]),r(d?C:Z??{},d?void 0:L)},children:"▶ Run"})]})]})}function Ui(t){return i.isLoopOpener(t)}function Hn({id:t}){const{tones:s,loopOf:o}=u.useContext(zt),n=Dn(t,o);return n.length===0?null:e.jsx("span",{className:"w6w-loop-dots",children:n.map(r=>e.jsx("span",{className:"w6w-loop-dot",role:"img","aria-label":`In loop · ${r}`,title:`In loop · ${r}`,style:{background:Bt(s.get(r)??1)}},r))})}function Jn(t){return li(t,u.useContext(zt).tones)}function Je({type:t,position:s,multiple:o,id:n,variant:r,top:l,routeLabel:c}){const p=le.useNodeId(),d=u.useContext(js),x=!!p&&!!d&&!d.readOnly,h=()=>{x&&p&&d.onAddFromPort(p,t,n)},m=r==="error"?"a step that handles this step's failure":r==="each"?"the first step of this loop's body":t==="target"?"a step before this one":"the next step";return e.jsx(le.Handle,{type:t,position:s,id:n,className:r==="error"?"w6w-handle-error":r==="each"?"w6w-handle-each":o?"w6w-handle-multi":void 0,style:{...o?{height:22,borderRadius:3,width:8}:{},...l?{top:l}:{}},onClick:x?h:void 0,title:c?`${c} — drag or click to connect`:x?`Drag to empty canvas (or click) to add ${m} · drag to a port to connect`:r==="error"?"On error — drag to route this step's failure separately":r==="each"?"Each item — drag to the first step to repeat for every item":o?t==="target"?"Accepts multiple incoming connections":"Multiple outgoing connections":void 0})}function qn({id:t,step:s,runnable:o}){const n=u.useContext(js);if(!n||n.readOnly)return null;const r=o||n.runsFromNode,l=n.runsFromNode?"Run from this node — continues through the nodes after it":"Test-run this node",c=st(s),p=We(s);return e.jsxs(le.NodeToolbar,{position:le.Position.Top,className:"w6w-node-toolbar",children:[r&&e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:l,"aria-label":l,onClick:()=>n.onRun(t),children:e.jsx(be.Icon,{name:"run",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn","data-testid":"node-pause-toggle","aria-pressed":c,title:c?"Resume — test runs go through this node":"Pause — test runs stop before this node","aria-label":c?"Unpause node":"Pause node",onClick:()=>n.onTogglePause(t),children:e.jsx(be.Icon,{name:"pause",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn","data-testid":"node-disable-toggle","aria-pressed":p,title:p?"Enable — this node runs again":"Disable — skip this node in every run","aria-label":p?"Enable node":"Disable node",onClick:()=>n.onToggleDisable(t),children:e.jsx(be.Icon,{name:"ban",size:15})}),e.jsx("span",{className:"w6w-node-toolbar-divider","aria-hidden":"true"}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:"Edit","aria-label":"Edit node",onClick:()=>n.onEdit(t),children:e.jsx(be.Icon,{name:"edit",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:"Duplicate","aria-label":"Duplicate node",onClick:()=>n.onDuplicate(t),children:e.jsx(be.Icon,{name:"copy",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn danger",title:"Delete","aria-label":"Delete node",onClick:()=>n.onDelete(t),children:e.jsx(be.Icon,{name:"trash",size:15})})]})}function Gn({step:t,count:s}){if(s<2)return null;const o=t.fanOut==="parallel",n=i.fanOutLabel(s,o?"parallel":"sequential");return e.jsxs("div",{className:"w6w-fanout-badge",role:"img","aria-label":n,title:n,children:[e.jsx("span",{"aria-hidden":"true",children:o?"⇉":"→"})," ",s]})}function Kn({step:t}){const s=st(t),o=We(t);return!s&&!o?null:e.jsxs("div",{children:[o&&e.jsxs("span",{className:"w6w-node-flag w6w-node-flag-disabled","data-testid":"step-disabled-badge",role:"img","aria-label":gn,title:gn,children:[e.jsx(be.Icon,{name:"ban",size:11})," Disabled"]}),s&&e.jsxs("span",{className:"w6w-node-flag w6w-node-flag-paused","data-testid":"step-paused-badge",role:"img","aria-label":wn,title:wn,children:[e.jsx(be.Icon,{name:"pause",size:11})," Paused"]})]})}function Yn(t){return!t||t.length===0?{}:{"data-step-problem":t.map(s=>s.code).join(" "),title:t.map(i.stepProblemTooltip).join(`
6
+ `)})})]})]}),e.jsx("div",{className:"w6w-modal-actions",children:e.jsx("button",{type:"button",className:"w6w-btn",onClick:()=>w(null),children:"Close"})})]})]}),Fe!==null&&e.jsx(i.ConfirmModal,{title:Fe.nodeIds.length===1?"Delete node":Fe.nodeIds.length>1?`Delete ${Fe.nodeIds.length} nodes`:`Delete ${Fe.edgeIds.length} connections`,message:Zo(Fe,g,T),confirmLabel:"Delete",autoFocusConfirm:!0,onConfirm:()=>{Zn(Fe),ze(null)},onClose:()=>ze(null)}),je&&e.jsx(jo,{x:je.x,y:je.y,items:Oo(je.nodeIds,!!n,{replaceableTrigger:je.nodeIds.length===1&&g.some(a=>a.id===je.nodeIds[0]&&i.isTriggerStep(a.data.step.uses))}),onAction:go,onClose:wo})]})})})})})})})});return e.jsx(i.WorkflowConnectionsContext.Provider,{value:{nodes:g.map(a=>a.data.step),connections:M,setConnections:E,readOnly:n},children:xo})}const Wi=["code"];function Ut(t){try{const s=JSON.parse(t);return s&&typeof s=="object"&&!Array.isArray(s)?s:null}catch{return null}}function Bi(t){try{const s=JSON.parse(t);if(Array.isArray(s))return{items:s}}catch{return null}return Ut(t)}function Vi({items:t,save:s}){if(!t)return e.jsxs("output",{className:"w6w-small",style:{display:"block"},children:[e.jsx("strong",{children:"Items"})," doesn't resolve to a list yet: no step before this one has a saved test that produces it. Test an earlier step, or paste a sample list under"," ",e.jsx("strong",{children:"Override the incoming state"})," below."]});const o=t[0],n=o!==void 0?(i.inferOutputFields(o)??[]).map(r=>r.key):[];return e.jsxs("div",{className:"w6w-testout",children:[e.jsxs("div",{className:"w6w-testout-label",children:[t.length," ",t.length===1?"item":"items"]}),t.length===0?e.jsx("p",{className:"w6w-muted w6w-small",children:"The list is empty, so there is no item to sample."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w6w-testout-label",children:"First item"}),e.jsx(i.ResultViewer,{value:o,maxHeight:220})]}),s==="saved"&&e.jsxs("output",{className:"w6w-small",style:{display:"block"},children:["Saved as this loop's sample.",n.length>0&&e.jsxs(e.Fragment,{children:[" ","Steps on ",e.jsx("strong",{children:"Each item"})," now offer ",e.jsx("strong",{children:"Current item"})," ›"," ",n.map((r,l)=>e.jsxs("span",{children:[l>0&&", ",e.jsx("code",{children:r})]},r)),"."]})]}),s==="failed"&&e.jsx("p",{className:"w6w-small",role:"alert",children:"Couldn't save the sample. Try Test again."})]})}function Vn(t){const s=i.foreachView(t),o=i.passLoopSeed(t),[n,r]=u.useState(null),[l,c]=u.useState("0"),[p,d]=u.useState({}),[x,h]=u.useState({}),m=n??i.loopItemText(s),k=((s==null?void 0:s.outer)??[]).map(C=>({foreachId:C.foreachId,name:C.name??C.foreachId,itemText:p[C.foreachId]??i.loopItemText(C),indexText:x[C.foreachId]??"0",setItemText:A=>d(w=>({...w,[C.foreachId]:A})),setIndexText:A=>h(w=>({...w,[C.foreachId]:A}))})),v=s?i.parseLoopSeed(m,l):void 0;let y=v!=null&&v.ok?{ok:!0,value:v.value}:v;if(s&&(v!=null&&v.ok)){const C={};for(const A of k){const w=i.parseLoopSeed(A.itemText,A.indexText);if(!w.ok){y={ok:!1,error:`${A.name}: ${w.error}`};break}C[A.foreachId]=w.value}y!=null&&y.ok&&(C[s.foreachId]=v.value,y={ok:!0,value:{...v.value,loops:C}})}return o&&(!y||y.ok)&&(y={ok:!0,value:{...y!=null&&y.ok?y.value:{},pass:o}}),{active:!!s,itemText:m,indexText:l,setItemText:r,setIndexText:c,outers:k,parsed:y}}function zn(t){var s;return(s=t.parsed)!=null&&s.ok?t.parsed.value:void 0}function js(t){return t.parsed&&!t.parsed.ok?t.parsed.error:null}function Un({seed:t,readOnly:s}){if(!t.active)return null;const o=js(t);return e.jsxs("div",{className:"w6w-field w6w-loop-seed",children:[t.outers.map(n=>e.jsxs("div",{"data-testid":`loop-seed-outer-${n.foreachId}`,children:[e.jsxs("span",{children:[n.name," item"]}),e.jsx("textarea",{rows:3,value:n.itemText,readOnly:s,spellCheck:!1,"aria-label":`${n.name} item`,onChange:r=>n.setItemText(r.target.value)}),e.jsxs("span",{children:[n.name," index"]}),e.jsx("input",{type:"text",inputMode:"numeric",value:n.indexText,readOnly:s,"aria-label":`${n.name} index`,onChange:r=>n.setIndexText(r.target.value)})]},n.foreachId)),e.jsx("span",{children:"Current item"}),e.jsx("textarea",{rows:3,value:t.itemText,readOnly:s,spellCheck:!1,"aria-label":"Current item",onChange:n=>t.setItemText(n.target.value)}),e.jsx("span",{children:"Index"}),e.jsx("input",{type:"text",inputMode:"numeric",value:t.indexText,readOnly:s,"aria-label":"Index",onChange:n=>t.setIndexText(n.target.value)}),e.jsx("span",{className:"w6w-hint",children:"This step runs once per item of the For each. Test it as one iteration — starting from the sample item, or edit it."}),o&&e.jsx("span",{className:"w6w-hint",role:"alert",children:o})]})}function hs({text:t,onChange:s,seeds:o,readOnly:n,expand:r,hint:l}){const c=Ut(t),p=c?Object.keys(c).length:0,d=p>0,[x,h]=u.useState(d);u.useEffect(()=>{(d||r)&&h(!0)},[d,r]);const m=k=>{s(JSON.stringify(k.lastRunOutput??k.input??{},null,2)),h(!0)};return e.jsxs("div",{className:"w6w-field w6w-incoming-state",children:[e.jsx("span",{children:"Incoming state"}),o.length>0&&e.jsx("div",{className:"w6w-seed-picker",children:e.jsx("div",{className:"w6w-seed-chips",children:o.map(k=>e.jsxs("button",{type:"button",className:"w6w-chip w6w-seed-chip",title:`Use ${k.label}'s saved test as the incoming state`,disabled:n,onClick:()=>m(k.test),children:[e.jsx("code",{children:k.label}),k.test.lastRunStatus?e.jsxs("span",{className:"w6w-muted w6w-small",children:[" · ",k.test.lastRunStatus]}):null]},k.stepId))})}),e.jsxs("details",{className:"w6w-state-override",open:x,onToggle:k=>h(k.currentTarget.open),children:[e.jsxs("summary",{children:["Override the incoming state",p>0?` · ${p} key${p===1?"":"s"} set`:""]}),e.jsx("textarea",{rows:3,value:t,readOnly:n,spellCheck:!1,"aria-label":"Incoming state override (JSON)",onChange:k=>s(k.target.value)}),e.jsx("span",{className:"w6w-hint",children:l??e.jsxs(e.Fragment,{children:["JSON whose keys replace this step's parameters by name, for this test only — so a script's data goes under ",e.jsx("code",{children:"input"}),": ",e.jsx("code",{children:'{"input": {…}}'}),". Upstream outputs already reach ",e.jsx("code",{children:"{{ nodes.<id>.output }}"})," bindings from their saved tests. Reach for this to test against a state the flow cannot currently produce — a field no upstream step returns yet, or a case you can't reproduce by running the flow."]})})]})]})}function zi({workflowId:t,step:s,upstreamSteps:o,loop:n,onRun:r,onCancel:l,continues:c}){var G;const p=i.useW6WApi(),d=i.isTriggerStep(s.uses),x=i.isInternalApp(s.uses.app),h=u.useMemo(()=>{var q;return d?i.asFieldDefs((q=s.with)==null?void 0:q.fields):[]},[d,s.with]),m=u.useMemo(()=>d?i.fieldsToParams(h):x?i.internalNodeParams(s.uses.app,s.uses.action):null,[d,x,h,s.uses.app,s.uses.action]),[k,v]=u.useState(null),y=m??k;u.useEffect(()=>{if(m)return;if(!s.uses.app||!s.uses.action){v([]);return}let q=!1;return v(null),p.getAppActions(s.uses.app).then(K=>{var se;q||v(((se=K.find(ge=>ge.key===s.uses.action))==null?void 0:se.params)??[])}).catch(()=>!q&&v([])),()=>{q=!0}},[p,m,s.uses.app,s.uses.action]);const[C,A]=u.useState(()=>{var q;return d?i.seedValues(i.asFieldDefs((q=s.with)==null?void 0:q.fields)):{}}),[w,D]=u.useState("{}"),$=i.useSeedSources(t,o,!d),M=Vn(n),R=(G=i.useExpressionOptions().stateShape)==null?void 0:G.written,L=i.startStateFromSeeds($,zn(M),R),E=i.useRememberedTestInput(t,s.id),[z,Y]=u.useState(!1),[N,g]=u.useState(!1);u.useEffect(()=>{if(!E.loaded)return;let q=!1;const K=(se,ge)=>{se&&Object.keys(se).length>0&&(d?A(qe=>({...qe,...se})):D(JSON.stringify(se,null,2)),ge&&g(!0)),Y(!0)};if(E.input!==void 0){K(E.input,!0);return}return p.listStepTests(t,s.id).then(se=>{if(q)return;const ge=se.length?se[se.length-1]:null;K(d?ge==null?void 0:ge.with:ge==null?void 0:ge.input,!1)}).catch(()=>{q||Y(!0)}),()=>{q=!0}},[p,t,s.id,d,E.loaded]);const[P,X]=u.useState(0),B=()=>{E.clear(),g(!1),d?A(i.seedValues(h)):D("{}"),X(q=>q+1)},ie=q=>{A(q),T(!0),g(!1),X(K=>K+1)},[te,T]=u.useState(!0),Z=Ut(w),F=d?te:Z!==null,U=d?C:{...s.with??{},...Z??{}},J=d?null:js(M),ae=!!y&&z&&F&&!J&&i.requiredParamsFilled(y,U);return e.jsxs("div",{className:"w6w-stepconfig",children:[e.jsx("div",{className:"w6w-modal-body",children:e.jsxs("div",{className:"w6w-stack",children:[c&&e.jsxs("p",{className:"w6w-muted w6w-small","data-testid":"run-from-node-hint",children:["Runs this node, then continues through every node after it",c.stopAt.length>0?e.jsxs(e.Fragment,{children:[" ","and stops before"," ",c.stopAt.length===1?"the paused node":"paused nodes"," ",c.stopAt.map((q,K)=>e.jsxs("span",{children:[K>0?", ":"",e.jsx("code",{children:q})]},q))]}):null,". Disabled nodes are skipped."]}),N&&y!==null&&z&&e.jsx(i.LastUsedNote,{onClear:B}),y===null||!z?e.jsx("p",{className:"w6w-muted w6w-small",children:y===null?"Loading parameters…":"Loading saved values…"}):d?e.jsxs(e.Fragment,{children:[e.jsx(i.PropertyEntryForm,{params:y,values:C,onChange:A,onValidityChange:T},P),s.uses.trigger===!0&&e.jsx(i.TriggerSampleButton,{app:s.uses.app,trigger:s.uses.action,onUse:ie}),y.length===0&&e.jsxs("span",{className:"w6w-hint",children:["This trigger declares no fields — provide a sample payload to run with. It becomes the trigger's output state (",e.jsx("code",{children:"input"}),")."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Runs ",e.jsx("code",{children:s.uses.action})," with the configuration saved on this node — only the incoming state changes per run. Edit the node to change how it is configured."]}),e.jsx(Un,{seed:M}),e.jsx(hs,{text:w,onChange:D,seeds:$})]})]})}),e.jsxs("div",{className:"w6w-modal-actions",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:l,children:"Cancel"}),!ae&&y!==null&&z&&e.jsx("span",{className:"w6w-muted w6w-small",children:J?`${J} Fix it to run.`:F?d?"Fill the required fields to test.":"This step is missing required configuration — set it on the Configure tab.":d?"The payload must be a JSON object to run.":"The incoming state must be a JSON object to run."}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:!ae,onClick:()=>{E.save(d?C:Z??{},y??[]),r(d?C:Z??{},d?void 0:L)},children:"▶ Run"})]})]})}function Ui(t){return i.isLoopOpener(t)}function Hn({id:t}){const{tones:s,loopOf:o}=u.useContext(zt),n=Dn(t,o);return n.length===0?null:e.jsx("span",{className:"w6w-loop-dots",children:n.map(r=>e.jsx("span",{className:"w6w-loop-dot",role:"img","aria-label":`In loop · ${r}`,title:`In loop · ${r}`,style:{background:Bt(s.get(r)??1)}},r))})}function Jn(t){return li(t,u.useContext(zt).tones)}function Je({type:t,position:s,multiple:o,id:n,variant:r,top:l,routeLabel:c}){const p=le.useNodeId(),d=u.useContext(vs),x=!!p&&!!d&&!d.readOnly,h=()=>{x&&p&&d.onAddFromPort(p,t,n)},m=r==="error"?"a step that handles this step's failure":r==="each"?"the first step of this loop's body":t==="target"?"a step before this one":"the next step";return e.jsx(le.Handle,{type:t,position:s,id:n,className:r==="error"?"w6w-handle-error":r==="each"?"w6w-handle-each":o?"w6w-handle-multi":void 0,style:{...o?{height:22,borderRadius:3,width:8}:{},...l?{top:l}:{}},onClick:x?h:void 0,title:c?`${c} — drag or click to connect`:x?`Drag to empty canvas (or click) to add ${m} · drag to a port to connect`:r==="error"?"On error — drag to route this step's failure separately":r==="each"?"Each item — drag to the first step to repeat for every item":o?t==="target"?"Accepts multiple incoming connections":"Multiple outgoing connections":void 0})}function qn({id:t,step:s,runnable:o}){const n=u.useContext(vs);if(!n||n.readOnly)return null;const r=o||n.runsFromNode,l=n.runsFromNode?"Run from this node — continues through the nodes after it":"Test-run this node",c=st(s),p=We(s);return e.jsxs(le.NodeToolbar,{position:le.Position.Top,className:"w6w-node-toolbar",children:[r&&e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:l,"aria-label":l,onClick:()=>n.onRun(t),children:e.jsx(be.Icon,{name:"run",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn","data-testid":"node-pause-toggle","aria-pressed":c,title:c?"Resume — test runs go through this node":"Pause — test runs stop before this node","aria-label":c?"Unpause node":"Pause node",onClick:()=>n.onTogglePause(t),children:e.jsx(be.Icon,{name:"pause",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn","data-testid":"node-disable-toggle","aria-pressed":p,title:p?"Enable — this node runs again":"Disable — skip this node in every run","aria-label":p?"Enable node":"Disable node",onClick:()=>n.onToggleDisable(t),children:e.jsx(be.Icon,{name:"ban",size:15})}),e.jsx("span",{className:"w6w-node-toolbar-divider","aria-hidden":"true"}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:"Edit","aria-label":"Edit node",onClick:()=>n.onEdit(t),children:e.jsx(be.Icon,{name:"edit",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn",title:"Duplicate","aria-label":"Duplicate node",onClick:()=>n.onDuplicate(t),children:e.jsx(be.Icon,{name:"copy",size:15})}),e.jsx("button",{type:"button",className:"w6w-node-toolbar-btn danger",title:"Delete","aria-label":"Delete node",onClick:()=>n.onDelete(t),children:e.jsx(be.Icon,{name:"trash",size:15})})]})}function Gn({step:t,count:s}){if(s<2)return null;const o=t.fanOut==="parallel",n=i.fanOutLabel(s,o?"parallel":"sequential");return e.jsxs("div",{className:"w6w-fanout-badge",role:"img","aria-label":n,title:n,children:[e.jsx("span",{"aria-hidden":"true",children:o?"⇉":"→"})," ",s]})}function Kn({step:t}){const s=st(t),o=We(t);return!s&&!o?null:e.jsxs("div",{children:[o&&e.jsxs("span",{className:"w6w-node-flag w6w-node-flag-disabled","data-testid":"step-disabled-badge",role:"img","aria-label":gn,title:gn,children:[e.jsx(be.Icon,{name:"ban",size:11})," Disabled"]}),s&&e.jsxs("span",{className:"w6w-node-flag w6w-node-flag-paused","data-testid":"step-paused-badge",role:"img","aria-label":wn,title:wn,children:[e.jsx(be.Icon,{name:"pause",size:11})," Paused"]})]})}function Yn(t){return!t||t.length===0?{}:{"data-step-problem":t.map(s=>s.code).join(" "),title:t.map(i.stepProblemTooltip).join(`
7
7
  `)}}function Xn({problems:t}){if(!t||t.length===0)return null;const s=t.map(i.stepProblemTooltip).join(`
8
- `);return e.jsx("span",{"data-step-problem-badge":"",role:"img","aria-label":s,title:s,style:{position:"absolute",top:-9,right:-9,width:18,height:18,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--w6w-danger)",color:"#fff"},children:e.jsx(be.Icon,{name:"warning",size:12})})}function Hi(t){const s=i.useW6WApi(),o=t.uses.action,[n,r]=u.useState(null),l=t.uses.trigger===!0,c=t.uses.app;return u.useEffect(()=>{if(!l||!s.getAppTriggers)return;let p=!1;return s.getAppTriggers(c).then(d=>{var x;return!p&&r(((x=d.find(h=>h.key===o))==null?void 0:x.title)??null)}).catch(()=>{}),()=>{p=!0}},[s,c,o,l]),n||o}function Ji(t){const s=i.useW6WApi(),o=s.listSubscriptionsForWorkflow,n=s.retrySubscriptionRegistration,r=t.id,l=[...Pi(t.nodes),...(t.nodes??[]).filter(y=>{var C,A;return(((C=y.uses)==null?void 0:C.app)===i.WEBHOOK_APP||((A=y.uses)==null?void 0:A.app)===i.FORM_APP)&&y.uses.trigger!==!0})],c=l.length>0,p=l.map(y=>`${y.id}:${y.uses.app}:${y.uses.action}:${i.connectionIdFor(y,t.connections)??""}`).join("|"),[d,x]=u.useState([]),h=u.useMemo(()=>Ri(d),[d]),[m,k]=u.useState(0);u.useEffect(()=>{if(!o||!c){x([]);return}let y=!1;return o.call(s,r).then(C=>!y&&x(C)).catch(()=>{}),()=>{y=!0}},[s,o,r,c,p,m]);const j=u.useMemo(()=>n?async y=>{try{await n.call(s,y)}finally{k(C=>C+1)}}:void 0,[s,n]);return u.useMemo(()=>({byNode:h,subs:d,retry:j}),[h,d,j])}function qi({nodeId:t}){const{byNode:s,retry:o}=u.useContext(Bn),[n,r]=u.useState(!1),l=s.get(t),c=Ai(l,o!==void 0);return!l||!c?null:e.jsxs("div",{className:"w6w-small","data-trigger-registration":l.status,"data-tone":c.tone,style:{marginTop:3,paddingLeft:2},children:[e.jsx("span",{style:c.tone==="danger"?{color:"var(--w6w-danger)"}:void 0,children:c.label}),e.jsxs("span",{className:"w6w-muted",children:[" · ",c.lastFire]}),c.error&&e.jsx("div",{role:"alert",style:{color:"var(--w6w-danger)"},children:c.error}),c.retryVisible&&o&&e.jsx("button",{type:"button",className:"nodrag",disabled:n,onClick:()=>{r(!0),o(l.id).catch(()=>{}).finally(()=>r(!1))},children:"Retry"})]})}function Gi({id:t,data:s,selected:o}){const n=s.step,l=u.useContext(bs).get(n.uses.app),c=(l==null?void 0:l.displayName)||n.uses.app||"—",p=i.isTriggerStep(n.uses),d=Hi(n),x=n.uses.trigger?`${c} · ${d}`:c,h=i.nodePortsForStep(n,u.useContext(gs)),m=Wn(s.stepStatus??"no-run",s.runStatus),k=e.jsx(Gn,{step:n,count:u.useContext(xs).get(t)??0}),j=Jn(t);return e.jsxs("div",{className:[s.loopOf?"w6w-node-in-loop":"",We(n)?"w6w-node-disabled":""].filter(Boolean).join(" ")||void 0,"data-loop-of":s.loopOf,style:j,"data-disabled":We(n)||void 0,"data-paused":st(n)||void 0,children:[e.jsx(qn,{id:t,step:n,runnable:!0}),e.jsxs("div",{className:p?"w6w-node-trigger":void 0,"data-node-kind":p?"trigger":void 0,"data-run-status":s.stepStatus??"no-run",...Yn(s.stepProblems),style:{position:"relative",...s.stepProblems?{boxShadow:"0 0 0 2px var(--w6w-danger)"}:{},border:`${m.borderWidth}px ${m.borderStyle} ${o?"var(--w6w-accent)":m.borderColor}`,opacity:We(n)?.45:o?1:m.opacity,background:"var(--w6w-panel)",color:"var(--w6w-text)",...p?{}:{borderRadius:4,padding:"8px 12px"},minWidth:180,fontSize:13,display:"flex",alignItems:"center",gap:10},children:[e.jsx(Xn,{problems:s.stepProblems}),h.in>0&&e.jsx(Je,{type:"target",position:le.Position.Left,multiple:h.in>1}),e.jsx(i.AppIcon,{src:l==null?void 0:l.iconSvg,srcDark:l==null?void 0:l.iconSvgDark,brandColor:l==null?void 0:l.brandColor,name:c,size:28}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontWeight:600},children:x}),e.jsx("div",{className:"w6w-muted w6w-small",style:{marginTop:2},children:e.jsx("code",{children:n.uses.action||"—"})})]}),h.out>0&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{type:"source",position:le.Position.Right,multiple:h.out>1}),!p&&e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:i.ERROR_SOURCE_HANDLE,variant:"error"})]})]}),k,e.jsx(Kn,{step:n}),p&&n.uses.trigger===!0&&e.jsx(qi,{nodeId:t}),s.loopOf&&e.jsx(Hn,{id:t}),e.jsxs("div",{className:"w6w-muted",style:{marginTop:3,fontSize:10,opacity:.75,paddingLeft:2},children:[n.id,l!=null&&l.version?` - v${l.version}`:""]}),n.notes&&e.jsx("div",{className:"w6w-muted w6w-node-notes",title:n.notes,children:n.notes})]})}function Ki({id:t,data:s,selected:o}){const n=s.step,r=i.routesForStep(n),l=n.uses.app===i.ROUTER_APP,c=i.isIfStep(n),p=r.length?i.routerPortLayout(r):c?i.ifPortLayout():void 0,d=JSON.stringify(r.map(M=>M.id)),x=le.useUpdateNodeInternals();u.useEffect(()=>{x(t)},[t,d,x]);const h=i.internalNodeLabel(n.uses.app,n.uses.action),m=i.internalNodeIcon(n.uses.app,n.uses.action),k=i.nodePortsForStep(n,u.useContext(gs)),j=i.isTriggerStep(n.uses),y=Ui(n),C=i.isLoopCloser(n),A=Wn(s.stepStatus??"no-run",s.runStatus),w=e.jsx(Gn,{step:n,count:u.useContext(xs).get(t)??0}),D=Jn(t),$=u.useContext(zt).tones;return e.jsxs("div",{className:[y?"w6w-node-foreach":"",s.loopOf?"w6w-node-in-loop":"",We(n)?"w6w-node-disabled":""].filter(Boolean).join(" ")||void 0,"data-loop-of":s.loopOf,style:D,"data-disabled":We(n)||void 0,"data-paused":st(n)||void 0,children:[e.jsx(qn,{id:t,step:n,runnable:!i.isControlApp(n.uses.app)}),e.jsxs("div",{className:j?"w6w-node-trigger":l?"w6w-node-router":void 0,"data-node-kind":j?"trigger":void 0,"data-run-status":s.stepStatus??"no-run",...Yn(s.stepProblems),style:{position:"relative",...s.stepProblems?{boxShadow:"0 0 0 2px var(--w6w-danger)"}:{},border:`${A.borderWidth}px ${A.borderStyle} ${o?"var(--w6w-accent)":A.borderColor}`,opacity:We(n)?.45:o?1:A.opacity,background:"var(--w6w-panel-2)",color:"var(--w6w-text)",...j?{}:{borderRadius:4,padding:"6px 14px 6px 8px"},minWidth:140,...p!=null&&p.minHeight?{minHeight:p.minHeight,boxSizing:"border-box"}:{},fontSize:13,display:"flex",alignItems:"center",gap:10},children:[e.jsx(Xn,{problems:s.stepProblems}),k.in>0&&e.jsx(Je,{type:"target",position:le.Position.Left,multiple:k.in>1}),m&&e.jsx(i.InternalIcon,{icon:m}),e.jsxs("div",{style:{minWidth:0,textAlign:"left"},children:[e.jsx("div",{style:{fontWeight:600},children:h}),e.jsx("div",{className:"w6w-muted w6w-small",style:{marginTop:2},children:e.jsx("code",{children:n.uses.action||"—"})})]}),y&&e.jsxs("div",{className:"w6w-foreach-ports w6w-small","aria-hidden":"true",children:[e.jsx("span",{children:i.isForeachStep(n)?"Each item":"Each pass"}),e.jsx("span",{children:"Done"})]}),C&&e.jsx("span",{className:"w6w-loop-back w6w-small","data-testid":"loop-back-marker",title:s.loopOf?`Loops back to ${s.loopOf}`:"Loops back",style:s.loopOf?{"--w6w-loop-color":Bt($.get(s.loopOf)??1)}:void 0,children:"↺ Loops back"}),c&&(p==null?void 0:p.right[0])&&e.jsx("span",{className:"w6w-if-true-label w6w-small","aria-hidden":"true",children:p.right[0].label}),!c&&!!(p!=null&&p.right.length)&&e.jsx("div",{className:"w6w-router-ports w6w-small",style:{gridTemplateRows:`repeat(${p.right.length}, 1fr)`},"aria-hidden":"true",children:p.right.map(M=>e.jsx("span",{title:M.label,children:M.label},M.id))}),k.out>0&&!C&&e.jsxs(e.Fragment,{children:[y&&e.jsx(Je,{type:"source",position:le.Position.Right,multiple:!1,id:i.EACH_SOURCE_HANDLE,variant:"each"}),p?e.jsxs(e.Fragment,{children:[p.right.map(M=>e.jsx(Je,{type:"source",position:le.Position.Right,multiple:!1,id:M.handleId,top:M.top,routeLabel:M.label},M.id)),p.bottom&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:p.bottom.handleId,routeLabel:p.bottom.label}),e.jsx("span",{className:"w6w-router-fallback-label w6w-small","aria-hidden":"true",children:p.bottom.label})]})]}):e.jsx(Je,{type:"source",position:le.Position.Right,multiple:k.out>1,id:y?i.routeHandle(i.FOREACH_DONE_ROUTE):void 0}),!j&&!l&&!c&&n.uses.app!==i.RACE_APP&&e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:i.ERROR_SOURCE_HANDLE,variant:"error"})]})]}),w,e.jsx(Kn,{step:n}),s.loopOf&&e.jsx(Hn,{id:t}),s.legacyLoop&&e.jsx("div",{className:"w6w-loop-legacy-note w6w-small",children:"This loop was converted from an older definition. Its steps after For each now run once per item; check the order, then save."}),e.jsx("div",{className:"w6w-muted",style:{marginTop:3,fontSize:10,opacity:.75,paddingLeft:2},children:n.id}),n.notes&&e.jsx("div",{className:"w6w-muted w6w-node-notes",title:n.notes,children:n.notes})]})}function Yi(t,s){var c,p;if(!s)return t;const o={...(t==null?void 0:t.steps)??{}};let n=!1;for(const[d,x]of Object.entries(s)){const h=/^nodes\.([^.]+)\.output$/.exec(d);!h||((c=o[h[1]])==null?void 0:c.output)!==void 0||(o[h[1]]={...o[h[1]]??{},output:x},n=!0)}const r=s["trigger.event"],l=r!==void 0&&((p=t==null?void 0:t.trigger)==null?void 0:p.event)===void 0;return!n&&!l?t:{...t??{},...n?{steps:o}:{},...l?{trigger:{...(t==null?void 0:t.trigger)??{},event:r}}:{}}}function Xi(t){return e.jsx(Zi,{...t})}function Zi({workflowId:t,step:s,restoreVersion:o,upstreamSteps:n,loop:r,onChange:l,onClose:c,onCancel:p,readOnly:d,initialView:x="props",fanOutCount:h=0,stateOutputFields:m,onTestRun:k,stepProblems:j,otherStepIds:y}){var St,Nt,it,Ne;const C=i.useW6WApi(),A=u.useContext(bs),[w,D]=u.useState(s),$=i.useWorkflowConnections(),M=i.connectionIdFor(w,$==null?void 0:$.connections),R={...w,uses:{...w.uses,connection:M}},E=w.uses.connectionRef!==void 0&&!M||i.isConnectionBlocked(R,j),z=j==null?void 0:j.find(I=>I.code==="unknown_connection"&&I.connection===M),Y=(j??[]).filter(I=>"fix"in I),[N,g]=u.useState(E?"setup":"configure"),[P,X]=u.useState(x==="json"?"code":x==="settings"?"config":"props"),[B,ie]=u.useState("props"),[te,T]=u.useState(()=>i.stepToJson(s)),[Z,F]=u.useState("{}"),U=u.useRef(null),[J,ae]=u.useState(!1),G=u.useRef(o);u.useEffect(()=>{G.current!==o&&(G.current=o,D(s),T(i.stepToJson(s)))},[o,s]);const[q,K]=u.useState(!1),[se,ge]=u.useState(null),[qe,_e]=u.useState(null),[ct,ke]=u.useState(null),[Ge,Pe]=u.useState(!1),je=i.isInternalApp(w.uses.app),ce=w.uses.trigger===!0;u.useEffect(()=>{if(je){ge(i.internalNodeParams(w.uses.app,w.uses.action));const ee=i.internalNodeDef(w.uses.app,w.uses.action),fe=i.INTERNAL_NODES.filter(ue=>ue.app===w.uses.app&&ue.groupActions&&(!ue.hidden||(ee==null?void 0:ee.hidden)));_e(fe.length?fe.map(ue=>({key:ue.action,title:ue.label,params:ue.params})):null);return}if(!w.uses.app){_e(null),ge([]);return}let I=!1;return ge(null),(ce?i.getTriggerDefs(C,w.uses.app):C.getAppActions(w.uses.app)).then(ee=>{var fe;I||(_e(ee),ge(w.uses.action?((fe=ee.find(ue=>ue.key===w.uses.action))==null?void 0:fe.params)??[]:[]))}).catch(()=>!I&&ge([])),()=>{I=!0}},[C,w.uses.app,w.uses.action,je,ce]);const Ie=u.useRef(0);u.useEffect(()=>()=>{Ie.current++},[]);const Be=u.useCallback(()=>{je||!w.uses.app||C.listConnectionsForApp(w.uses.app).then(I=>{ke(I),Pe(!1)}).catch(()=>Pe(!0))},[C,w.uses.app,je]);u.useEffect(()=>{if(je||!w.uses.app)return;let I=!1;return ke(null),Pe(!1),C.listConnectionsForApp(w.uses.app).then(ee=>{I||(ke(ee),Pe(!1))}).catch(()=>!I&&Pe(!0)),()=>{I=!0}},[C,w.uses.app,je]);const re=u.useCallback(I=>{D(I),l(I)},[l]),jt=Ko({enabled:w.uses.app===i.SCRIPT_APP&&!d,values:w.with??{},onChange:I=>re({...w,with:I})}),de=I=>{I==="code"&&T(i.stepToJson(w)),X(I)},Le=I=>{const ee=i.stepNameError(I,y??[]);return ee||re({...w,id:I}),ee},Oe=!!w.uses.app&&!!w.uses.action&&!i.isControlApp(w.uses.app),Ae=i.isForeachStep(w),ve=i.isTriggerStep(w.uses),Ke=N==="test"&&Oe&&!ve,Se=i.useSeedSources(t,n,Oe&&!ve||Ae),Ve=Vn(Oe&&!ve?r:void 0),Fe=i.useExpressionOptions(),ze=i.startStateFromSeeds(Se,zn(Ve),(St=Fe.stateShape)==null?void 0:St.written),dt=Yi(ze,Fe.sampleValues),Ee=i.useRememberedTestInput(Oe&&!ve||Ae?t:void 0,w.id),[xe,$e]=u.useState(!1);u.useEffect(()=>{if((!Oe||ve)&&!Ae||!Ee.loaded)return;if(!Ae&&Ee.input!==void 0){const ee=Ee.input;if(Object.keys(ee).length===0)return;const fe=JSON.stringify(ee,null,2);F(ue=>ue.trim()==="{}"?fe:ue),$e(!0);return}let I=!1;return C.listStepTests(t,w.id).then(ee=>{if(I)return;const fe=ee.length?ee[ee.length-1]:null;if(!(fe!=null&&fe.input)||Object.keys(fe.input).length===0)return;const ue=JSON.stringify(fe.input,null,2);F(Xe=>Xe.trim()==="{}"?ue:Xe)}).catch(()=>{}),()=>{I=!0}},[C,t,w.id,Oe,ve,Ae,Ee.loaded]);const De=Ae?Bi(Z):Ut(Z),Me={...w.with??{},...De??{}},ut=De??{},nt=!!se&&!vs(Ve)&&i.requiredParamsFilled(se,Me)&&(w.uses.app!==i.CALL_APP||q),ne=Ae?i.resolveLoopItemsInState(Me.items,ze):void 0,[ot,Ye]=u.useState("idle"),vt=I=>{F(I),Ye("idle")},pt=async()=>{if(ne){Ye("saving");try{await C.saveStepTest(t,w.id,i.foreachTestFixture(ne,ut)),Ye("saved")}catch{Ye("failed")}}},we=A.get(w.uses.app),yt=ce?(Nt=qe==null?void 0:qe.find(I=>I.key===w.uses.action))==null?void 0:Nt.webhook:void 0,ft=je?i.internalNodeIcon(w.uses.app,w.uses.action):null,Ht=je?ft?e.jsx(i.InternalIcon,{icon:ft}):null:e.jsx(i.AppIcon,{src:we==null?void 0:we.iconSvg,srcDark:we==null?void 0:we.iconSvgDark,brandColor:we==null?void 0:we.brandColor,name:we==null?void 0:we.displayName});return e.jsx(i.Modal,{ariaLabel:"Edit step",titleIcon:Ht,title:e.jsx(i.StepNameEditor,{value:w.id,onCommit:Le,readOnly:d}),onClose:p??c,size:"wide",children:e.jsxs("div",{className:"w6w-stepconfig",children:[e.jsxs("div",{className:"w6w-tabsbar",children:[e.jsx("div",{className:"w6w-subtabs",children:["setup","configure","test"].filter(I=>w.uses.app!==i.RACE_APP||I!=="test").map(I=>e.jsx("button",{type:"button",className:`w6w-subtab${N===I?" active":""}`,disabled:E&&I!=="setup",onClick:()=>g(I),children:I==="setup"?"Setup":I==="configure"?"Configure":"Test"},I))}),Ke?e.jsx(i.ConfigViewToggle,{view:B,views:["props","code"],onChange:I=>ie(I)}):e.jsx(i.ConfigViewToggle,{view:P,customized:i.hasParamCustomization(w.with??{}),onChange:de,disabled:N!=="configure"})]}),E&&z&&e.jsxs("div",{role:"alert",className:"w6w-field-error",children:["Connection ",z.connection," no longer exists — choose another to continue."]}),Y.length>0&&e.jsx("div",{className:"w6w-stepproblem-fixes",style:{display:"grid",gap:6},children:Y.map(I=>e.jsxs("div",{className:"w6w-small",style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("span",{children:i.stepProblemTooltip(I)}),e.jsx("button",{type:"button",className:"w6w-btn","data-fix-code":I.code,disabled:d,onClick:()=>{const ee=$n(w,I);re(ee),T(i.stepToJson(ee))},children:"fix"in I?I.fix.label:""})]},I.code))}),e.jsxs("div",{className:"w6w-stepconfig-body",children:[N==="setup"&&w.uses.app===i.CALL_APP&&e.jsx(i.CallTargetForm,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d,onValidityChange:K,setupOnly:!0}),N==="setup"&&w.uses.app!==i.CALL_APP&&e.jsx(tr,{step:w,app:we,actions:qe,conns:ct,connsFailed:Ge,isInternal:je,actionLabel:ce?"Trigger":"Action",readOnly:d,onChangeAction:I=>{var fe;const ee=je?i.internalNodeDefaults(w.uses.app,I):{};if(je)for(const ue of i.internalNodeParams(w.uses.app,I))ue.key in(w.with??{})&&(ee[ue.key]=(fe=w.with)==null?void 0:fe[ue.key]);re({...w,uses:{...w.uses,action:I},with:ee})},onChangeTriggerEvents:(I,ee)=>re({...w,uses:{...w.uses,action:I},with:{...w.with,actions:ee}}),onChangeConnection:I=>{if(!$){const{connectionRef:fe,...ue}=w.uses;re({...w,uses:{...ue,connection:I}});return}const ee=i.selectNodeConnection(w,I,($==null?void 0:$.nodes)??[w],($==null?void 0:$.connections)??{});$==null||$.setConnections(ee.connections),re(ee.step)},onChangeConnectionRef:I=>re(i.withConnectionRef(w,I)),onConnectionCreated:Be,onChangeApp:I=>{const ee=++Ie.current;if(I===w.uses.app){re(w);return}const fe={...w,uses:{app:I,action:"",...ce?{trigger:!0}:{}},with:{}};(i.isInternalApp(I)?Promise.resolve([]):C.listConnectionsForApp(I)).catch(()=>[]).then(ue=>{if(ee!==Ie.current)return;const Xe=i.defaultConnectionFor(fe,ue,($==null?void 0:$.nodes)??[],($==null?void 0:$.connections)??{});re({...fe,uses:{...fe.uses,...Xe}})})}}),N==="configure"&&e.jsxs(e.Fragment,{children:[(w.uses.app===i.WEBHOOK_APP||w.uses.app===i.FORM_APP)&&C.listSubscriptionsForWorkflow&&C.createSubscription&&e.jsx(er,{workflowId:t,step:w,readOnly:d}),ce&&yt&&w.uses.action&&C.listSubscriptionsForWorkflow&&e.jsx(Mo,{workflowId:t,nodeId:w.id,appId:w.uses.app,triggerKey:w.uses.action,appName:(we==null?void 0:we.displayName)??w.uses.app,setup:yt,connectionId:M&&!M.startsWith("zerocred:")?M:null,params:w.with??{},readOnly:d}),se===null?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading parameters…"}):P==="props"?w.uses.app===i.CALL_APP?e.jsx(i.CallTargetForm,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d,onValidityChange:K}):w.uses.app===i.RACE_APP?e.jsx("p",{className:"w6w-muted w6w-small",children:i.RACE_DESCRIPTION}):w.uses.action==="wait"&&i.isControlApp(w.uses.app)?e.jsx(i.WaitEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.action==="if"&&i.isControlApp(w.uses.app)?e.jsx(i.ConditionEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app==="@w6w/stop"?e.jsx(i.StopEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app===i.ROUTER_APP?e.jsx(i.RouterEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app===i.FORM_APP?e.jsxs("div",{className:"w6w-stack",children:[e.jsx(yo,{value:(it=w.with)==null?void 0:it.form,readOnly:d,stepId:w.id,onChange:I=>re({...w,with:{...w.with,form:I}})}),e.jsx(i.ParamsForm,{params:se.filter(I=>I.key!=="form"),values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})})]}):e.jsxs(e.Fragment,{children:[w.uses.app===i.SCRIPT_APP&&e.jsx(Yo,{values:w.with??{},conversion:jt,readOnly:d}),e.jsx(i.ParamsForm,{params:se,values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I}),dynamic:je||!w.uses.action?void 0:{appId:w.uses.app,actionKey:w.uses.action,kind:i.isTriggerStep(w.uses)?"trigger":"action",connectionId:E?void 0:M,appName:we==null?void 0:we.displayName}})]}):P==="code"?e.jsx(i.JsonEditor,{value:te,onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":`Node ${w.id} JSON`,copyable:!0}):P==="params-code"?e.jsx(i.ParamCustomization,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d}):e.jsxs("div",{className:"w6w-stack",children:[e.jsx(i.NodeConfigForm,{config:{retry:w.retry,onError:w.onError,notes:w.notes,timeoutMs:w.timeoutMs},onChange:I=>re({...w,...I}),readOnly:d,failureHandling:!ve,retryControls:!i.isControlApp(w.uses.app)&&w.uses.app!==i.CALL_APP}),Qi,e.jsx(i.StepFanOutControl,{step:w,count:h,readOnly:d,onChange:re}),i.stateWriteVisible(w)&&e.jsx(i.StepStateControl,{step:w,inLoop:r!==void 0,outputFields:m,readOnly:d,onChange:re})]})]}),N==="test"&&e.jsx("div",{className:"w6w-stack",children:Oe?ve?e.jsx(i.TriggerFillForm,{app:w.uses.app,action:w.uses.action,fields:ce||(Ne=w.with)==null?void 0:Ne.fields,appTrigger:ce,persist:{workflowId:t,stepId:w.id,input:ut},listen:(w.uses.app===i.WEBHOOK_APP||w.uses.app===i.FORM_APP)&&C.listSubscriptionsForWorkflow&&C.startWebhookListen?{stepWith:w.with,readOnly:d,appId:w.uses.app}:void 0}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Tests ",e.jsx("code",{children:w.uses.action})," with the configuration saved on this step — only the incoming state changes per run."]}),e.jsx(Un,{seed:Ve,readOnly:d}),xe&&!d&&e.jsx(i.LastUsedNote,{onClear:()=>{Ee.clear(),$e(!1),F("{}")}}),e.jsx(hs,{text:Z,onChange:F,seeds:Se,readOnly:d}),se===null?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading parameters…"}):e.jsx(Uo,{params:se,values:Me,testStartState:dt,view:B,literalKeys:w.uses.app===i.SCRIPT_APP?Wi:void 0}),e.jsx(i.StepTestRun,{ref:U,app:w.uses.app,action:w.uses.action,connectionId:M,values:Me,timeoutMs:w.timeoutMs,state:ze,canRun:nt,hideRunButton:!0,persist:{workflowId:t,stepId:w.id,input:ut},onBusyChange:ae})]}):Ae?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Resolves ",e.jsx("strong",{children:"Items"})," against the incoming state — nothing inside the loop runs. ",e.jsx("strong",{children:"Test"})," saves the first item as this loop's sample, so the steps on its ",e.jsx("strong",{children:"Each item"})," output can pick its keys. To run the loop's work, test a step on ",e.jsx("strong",{children:"Each item"}),": it runs once, on one item."]}),e.jsx(hs,{text:Z,onChange:vt,seeds:Se,readOnly:d,expand:!ne,hint:e.jsxs(e.Fragment,{children:["Paste a sample list — ",e.jsx("code",{children:'[{"id": 1, "name": "…"}]'})," — or"," ",e.jsx("code",{children:'{"items": […]}'}),". It replaces what ",e.jsx("strong",{children:"Items"})," ","resolves to, for this test only."]})}),e.jsx(Vi,{items:ne,save:ot})]}):e.jsx("p",{className:"w6w-muted w6w-small",children:"Flow-control nodes can't be tested on their own."})})]}),e.jsxs("div",{className:"w6w-modal-actions w6w-stepconfig-footer",children:[p&&!d&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:p,children:"Cancel"}),w.uses.app===i.RACE_APP&&N==="configure"?e.jsx("button",{type:"button",className:"w6w-btn",onClick:c,children:"Done"}):N!=="test"?e.jsxs(e.Fragment,{children:[p&&!d&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:c,children:"Done"}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:E,onClick:()=>g(N==="setup"?"configure":"test"),children:"Next →"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:c,children:"Done"}),Oe&&!ve&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:d||!nt||J,onClick:()=>{var I;k==null||k(),(I=U.current)==null||I.run()},children:J?"Testing…":"Test"}),Ae&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:d||!(ne!=null&&ne.length)||ot==="saving",onClick:()=>void pt(),children:ot==="saving"?"Testing…":"Test"})]})]})]})})}const Qi=!1;function er({workflowId:t,step:s,readOnly:o}){const n=i.useW6WApi(),r=s.uses.app===i.FORM_APP,[l,c]=u.useState(void 0),[p,d]=u.useState(null),[x,h]=u.useState(!1),m=(l==null?void 0:l.webhookUrl)??(l==null?void 0:l.formUrl);u.useEffect(()=>{const j=n.listSubscriptionsForWorkflow;if(!j)return;let y=!1;return j(t).then(C=>{y||c(r?i.pickFormSubscription(C,s.id):i.pickWebhookSubscription(C,s.id))}).catch(C=>!y&&d(C.message)),()=>{y=!0}},[n,t,s.id,r]);const k=()=>{const j=n.createSubscription;j&&(d(null),h(!0),j(r?i.FORM_APP:i.WEBHOOK_APP,s.uses.action,{workflowId:t,connectionId:null,params:r?{node:s.id}:s.with??{}}).then(y=>{h(!1),c(y)}).catch(y=>{h(!1),d(y instanceof Error?y.message:String(y))}))};return e.jsxs("div",{className:"w6w-stack w6w-url-panel",children:[e.jsx("p",{className:"w6w-muted w6w-small",children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Form URL"})," — share it, or embed it in an iframe. Each submission starts the workflow once it is published."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Webhook URL"})," — the address a third party posts to."]})}),p&&e.jsx("div",{className:"w6w-result w6w-error",children:p}),m?e.jsxs("div",{className:"w6w-listen-url",children:[e.jsx(be.Copyable,{value:m,readOnly:!0,children:e.jsx("input",{type:"text",readOnly:!0,value:m,"aria-label":r?"Form URL":"Webhook URL"})}),r&&e.jsx("a",{className:"w6w-btn w6w-btn-ghost w6w-btn-sm",href:m,target:"_blank",rel:"noreferrer",children:"Open form"})]}):l===void 0?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading…"}):!o&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:x,onClick:k,children:x?"Creating…":r?"Create form URL":"Create webhook URL"})]})}function tr({step:t,app:s,actions:o,conns:n,connsFailed:r,isInternal:l,actionLabel:c="Action",readOnly:p,onChangeAction:d,onChangeTriggerEvents:x,onChangeConnection:h,onChangeConnectionRef:m,onChangeApp:k,onConnectionCreated:j}){const y=t.uses.trigger?i.eventbriteTriggerChoices(t.uses.app,o,t.uses.action,t.with??{}):null,[C,A]=u.useState(null),w=u.useRef(null),D=i.useWorkflowConnections(),$=i.connectionIdFor(t,D==null?void 0:D.connections);return e.jsxs("div",{className:"w6w-stack",children:[t.uses.connectionRef&&!$&&e.jsx("p",{role:"alert",className:"w6w-field-error",children:"The shared connection is missing or unbound. Choose an account."}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"App"}),e.jsxs("div",{className:"w6w-app-conn-row",ref:w,children:[e.jsxs("button",{type:"button",className:"w6w-app-conn-btn","aria-label":"App","aria-expanded":C==="app",disabled:p,onClick:()=>A(M=>M==="app"?null:"app"),children:[!l&&s&&e.jsx(i.AppIcon,{src:s.iconSvg,srcDark:s.iconSvgDark,brandColor:s.brandColor,name:s.displayName,size:20}),e.jsx("span",{className:"w6w-conn-label-name",children:l?t.uses.app:(s==null?void 0:s.displayName)??t.uses.app})]}),!l&&e.jsx(i.WorkflowConnectionPicker,{step:t,conns:n,failed:r,readOnly:p,open:C==="conn",onOpenChange:M=>A(M?"conn":null),anchorRef:w,onChangeConnection:h,onChangeConnectionRef:m,onConnectionCreated:j})]}),C==="app"&&e.jsx(i.AnchoredFlyout,{anchorRef:w,onClose:()=>A(null),children:e.jsx(i.AppPicker,{onSelectApp:M=>{const R=M.id===t.uses.app;k(M.id),A(R?"conn":null)}})})]}),l&&!(o!=null&&o.length)?e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Action"}),e.jsx("div",{className:"w6w-muted w6w-small",children:e.jsx("code",{children:t.uses.action})})]}):y?e.jsx(i.EventbriteTriggerPicker,{choices:y,readOnly:p,onChange:M=>x(y.triggerKey,M)}):e.jsxs("label",{className:"w6w-field",children:[e.jsx("span",{children:c}),e.jsx(i.Combobox,{value:t.uses.action,disabled:p||o===null,onChange:d,options:o===null?[{value:t.uses.action,label:t.uses.action}]:o.map(M=>({value:M.key,label:M.title??M.key}))})]})]})}function En({trigger:t}){return e.jsx("span",{className:"w6w-connection-node-kind",role:"img","aria-label":t?"Trigger":"Node",children:e.jsx("svg",{"aria-hidden":"true",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:t?e.jsx("path",{d:"M13 2 4 14h7l-1 8 10-12h-7l1-8Z"}):e.jsxs(e.Fragment,{children:[e.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"3"}),e.jsx("path",{d:"M2 12h3m14 0h3"})]})})})}function sr({resources:t}){const s=i.useW6WApi(),o=t.highlightNode;u.useEffect(()=>()=>o==null?void 0:o(null),[o]);const[n,r]=u.useState([]),[l,c]=u.useState(!0),[p,d]=u.useState(),[x,h]=u.useState(),[m,k]=u.useState(null),[j,y]=u.useState(!1),[C,A]=u.useState(!1),w=u.useRef(0),D=u.useCallback(async()=>{const F=++w.current;c(!0),d(void 0);try{const U=await s.listConnections();return F!==w.current?void 0:(r(U),U)}catch(U){F===w.current&&d(U.message)}finally{F===w.current&&c(!1)}},[s]);u.useEffect(()=>(D(),()=>{w.current++}),[D]);const[$,M]=u.useState(new Map),R=JSON.stringify([...new Set([...Object.values(t.connections).map(F=>F.app),...n.map(F=>F.appId)])].filter(F=>{var U;return!((U=t.apps)!=null&&U.has(F))&&!n.some(J=>J.appId===F&&J.app!==void 0)}).sort());u.useEffect(()=>{var G,q;let F=!1;const U=JSON.parse(R);if(l||!U.length)return;const J=(G=s.listAppsByIds)==null?void 0:G.bind(s),ae=J?Promise.all(Array.from({length:Math.ceil(U.length/50)},(K,se)=>J(U.slice(se*50,(se+1)*50)))).then(K=>K.flat()):(q=s.listApps)==null?void 0:q.call(s);return ae==null||ae.then(K=>{F||M(new Map(K.map(se=>[se.id,se])))}).catch(()=>{}),()=>{F=!0}},[s,R,l]);const L=F=>{var G;const U=n.find(q=>q.appId===F&&q.app)??n.find(q=>q.appId===F&&q.app!==void 0),J=U?i.resolveConnectionAppMeta(U,$):$.get(F),ae=(G=t.apps)==null?void 0:G.get(F);return ae?{...J,...ae}:J},E=F=>{var U;return((U=L(F))==null?void 0:U.displayName)||F},z=F=>{if(t.readOnly)return!1;try{return t.edit(F),h(void 0),!0}catch(U){return h(U.message),!1}},Y=F=>i.nextWorkflowConnectionName(F.appId,t.connections),N=()=>{k(null),h(void 0),y(!1)},g=m!=null&&m.ref?t.connections[m.ref]:void 0,P=n.find(F=>F.id===(m==null?void 0:m.connection)),X=(g==null?void 0:g.app)??(P==null?void 0:P.appId),B=t.nodes.filter(F=>F.uses.app===X),ie=t.nodes.filter(F=>(m==null?void 0:m.ref)!==void 0&&F.uses.connectionRef===m.ref),te=n.filter(F=>!g||F.appId===g.app).map(F=>({value:F.id,label:g?F.displayName||F.id:`${E(F.appId)} · ${F.displayName||F.id}`}));m!=null&&m.connection&&!te.some(F=>F.value===m.connection)&&te.unshift({value:m.connection,label:m.connection.startsWith("zerocred:")?"Built-in":m.connection});const T=(F,U=28)=>{const J=L(F);return e.jsx(i.AppIcon,{src:J==null?void 0:J.iconSvg,srcDark:J==null?void 0:J.iconSvgDark,brandColor:J==null?void 0:J.brandColor,name:E(F),size:U})},Z=()=>{if(!m||!m.name.trim()||!m.connection||!X)return;const F=m.ref!==void 0?{type:"update",ref:m.ref,name:m.name,connection:m.connection,nodeIds:m.allNodes?B.map(U=>U.id):void 0}:{type:"add",name:m.name,app:X,connection:m.connection};z(F)&&N()};return e.jsxs("div",{className:"w6w-stack","data-testid":"workflow-connections-panel",children:[e.jsxs("div",{className:"w6w-workflow-connections-heading",children:[e.jsx("h3",{children:"Connections"}),e.jsx(i.IconButton,{label:"Add connection",disabled:t.readOnly,onClick:()=>{h(void 0),k({name:"",connection:"",allNodes:!1})},children:e.jsx("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),p&&e.jsxs("div",{role:"alert",className:"w6w-stack",children:[e.jsxs("p",{className:"w6w-field-error",children:["Couldn’t load connections: ",p]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:()=>void D(),children:"Retry"})]}),Object.entries(t.connections).map(([F,U])=>{var q;const J=t.nodes.filter(K=>K.uses.connectionRef===F),ae=n.find(K=>K.id===U.connection),G=(ae==null?void 0:ae.displayName)||((q=U.connection)!=null&&q.startsWith("zerocred:")?"Built-in":U.connection)||"No credentials selected";return e.jsxs("section",{className:"w6w-workflow-connection","data-connection-resource":F,children:[e.jsxs("div",{className:"w6w-connection-app-heading",children:[T(U.app),e.jsxs("div",{className:"w6w-connection-summary",children:[e.jsx("strong",{children:E(U.app)}),e.jsx("span",{className:"w6w-small",children:G}),e.jsxs("span",{className:"w6w-muted w6w-small",children:[F,ae!=null&&ae.state?` · ${ae.state}`:""]})]}),e.jsx(i.IconButton,{icon:"edit",label:`Edit connection ${F}`,disabled:t.readOnly,onClick:()=>{h(void 0),k({ref:F,name:F,connection:U.connection??"",allNodes:!1})}})]}),J.length>0?e.jsxs("details",{className:"w6w-connection-consumers",onToggle:K=>{K.currentTarget.open||o==null||o(null)},children:[e.jsxs("summary",{className:"w6w-muted w6w-small",children:["Used by ",J.length," ",J.length===1?"node":"nodes"]}),e.jsx("ul",{className:"w6w-connection-node-list",children:J.map(K=>e.jsx("li",{children:t.focusNode?e.jsxs("button",{type:"button",className:"w6w-btn w6w-btn-ghost","aria-label":`Show ${K.id} on canvas`,onClick:()=>{var se;return(se=t.focusNode)==null?void 0:se.call(t,K.id)},onMouseEnter:()=>o==null?void 0:o(K.id),onMouseLeave:()=>o==null?void 0:o(null),onFocus:()=>o==null?void 0:o(K.id),onBlur:()=>o==null?void 0:o(null),children:[e.jsx(En,{trigger:i.isTriggerStep(K.uses)}),e.jsxs("span",{className:"w6w-connection-node-label",children:[e.jsx("strong",{children:K.uses.action}),e.jsx("span",{className:"w6w-muted w6w-small",children:K.id})]})]}):e.jsxs("span",{className:"w6w-connection-app-heading",children:[e.jsx(En,{trigger:i.isTriggerStep(K.uses)}),e.jsxs("span",{className:"w6w-connection-node-label",children:[e.jsx("strong",{children:K.uses.action}),e.jsx("span",{className:"w6w-muted w6w-small",children:K.id})]})]})},K.id))})]}):e.jsx("span",{className:"w6w-muted w6w-small",children:"Not used by any nodes yet."})]},F)}),!Object.keys(t.connections).length&&e.jsx("p",{className:"w6w-muted w6w-small",children:"No workflow connections yet."}),m&&!C&&!j&&e.jsxs(i.Modal,{title:m.ref!==void 0?"Edit connection":"Add connection",titleIcon:X?T(X):void 0,subtitle:X?E(X):void 0,onClose:N,children:[e.jsxs("div",{className:"w6w-modal-body w6w-stack",children:[x&&e.jsx("p",{role:"alert",className:"w6w-field-error",children:x}),p&&e.jsxs("div",{role:"alert",className:"w6w-stack",children:[e.jsxs("p",{className:"w6w-field-error",children:["Couldn’t load credentials: ",p]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:()=>void D(),children:"Retry"})]}),m.ref!==void 0&&!g&&e.jsx("p",{role:"alert",children:"This workflow connection no longer exists."}),e.jsxs("label",{className:"w6w-field",children:[e.jsx("span",{children:"Workflow connection name"}),e.jsx("input",{className:"w6w-input","aria-label":"Workflow connection name",value:m.name,disabled:t.readOnly,onChange:F=>k({...m,name:F.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:g?"Credentials":"Existing connection"}),e.jsx(i.Combobox,{"aria-label":g?"Credentials":"Connection to add",options:te,value:m.connection,placeholder:l?"Loading connections…":"Choose a connection…",disabled:t.readOnly||l||!!p,onChange:F=>{const U=n.find(J=>J.id===F);k({...m,connection:F,name:!m.name&&U?Y(U):m.name})}})]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",disabled:t.readOnly,onClick:()=>A(!0),children:"Create new credentials"}),g&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"w6w-muted w6w-small",children:m.allNodes?`Saving applies these credentials to all ${B.length} ${E(g.app)} nodes.`:`Saving updates credentials for ${ie.length} linked ${ie.length===1?"node":"nodes"}.`}),B.length>0&&e.jsxs("label",{className:"w6w-connection-scope",children:[e.jsx("input",{type:"checkbox",checked:m.allNodes||B.every(F=>F.uses.connectionRef===m.ref),disabled:t.readOnly||B.every(F=>F.uses.connectionRef===m.ref),onChange:F=>k({...m,allNodes:F.target.checked})}),"Use for all ",B.length," ",E(g.app)," ",B.length===1?"node":"nodes"," in this workflow"]}),e.jsxs("div",{className:"w6w-connection-remove",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",disabled:t.readOnly||ie.length>0,onClick:()=>y(!0),children:"Remove from workflow"}),ie.length>0&&e.jsx("p",{className:"w6w-muted w6w-small",children:"Assign another connection to the linked nodes before removing this one."})]})]})]}),e.jsxs("div",{className:"w6w-modal-actions",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:N,children:"Cancel"}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:t.readOnly||l||!!p||!m.name.trim()||!m.connection||!X||m.ref!==void 0&&!g,onClick:Z,children:m.ref!==void 0?"Save changes":"Add to workflow"})]})]}),m&&j&&e.jsx(i.ConfirmModal,{title:"Remove workflow connection",message:`Remove “${m.ref}” from this workflow? The saved credentials will remain available.`,confirmLabel:"Remove",onClose:()=>y(!1),onConfirm:()=>{m.ref&&z({type:"remove",ref:m.ref})?N():y(!1)}}),m&&C&&e.jsx(i.AddConnectionModal,{initialAppId:g==null?void 0:g.app,onClose:()=>A(!1),onCreated:({connectionId:F})=>{A(!1),D().then(U=>{const J=U==null?void 0:U.find(ae=>ae.id===F);J&&k(ae=>ae?{...ae,connection:J.id,name:ae.name||Y(J)}:null)})}})]})}exports.CALL_APP=i.CALL_APP;exports.CONTROL_APP=i.CONTROL_APP;exports.CanvasLayer=i.CanvasLayer;exports.DATA_APP=i.DATA_APP;exports.ExpressionOptionsProvider=i.ExpressionOptionsProvider;exports.INTERNAL_NODES=i.INTERNAL_NODES;exports.Markdown=i.Markdown;exports.RACE_APP=i.RACE_APP;exports.SCHEDULER_APP=i.SCHEDULER_APP;exports.SCRIPT_APP=i.SCRIPT_APP;exports.TRIGGER_APP=i.TRIGGER_APP;exports.WEBHOOK_APP=i.WEBHOOK_APP;exports.asFieldDefs=i.asFieldDefs;exports.centralizeConnections=i.centralizeConnections;exports.coerceDefault=i.coerceDefault;exports.connectionIdFor=i.connectionIdFor;exports.fieldWidget=i.fieldWidget;exports.fieldsToParams=i.fieldsToParams;exports.flowToWorkflow=i.flowToWorkflow;exports.internalNodeDefaults=i.internalNodeDefaults;exports.internalNodeIcon=i.internalNodeIcon;exports.internalNodeLabel=i.internalNodeLabel;exports.internalNodeParams=i.internalNodeParams;exports.isControlApp=i.isControlApp;exports.isInternalApp=i.isInternalApp;exports.isTriggerApp=i.isTriggerApp;exports.isTriggerStep=i.isTriggerStep;exports.seedValues=i.seedValues;exports.workflowToFlow=i.workflowToFlow;exports.MAX_NOTES=Tn;exports.MAX_NOTE_BYTES=An;exports.MAX_SECTIONS=In;exports.WorkflowConnectionsPanel=sr;exports.WorkflowFlowEditor=Oi;exports.applyStepProblemFix=$n;exports.assignMembership=cs;exports.clampCanvas=ds;exports.findLoopProblems=fi;exports.findStateWriteProblems=wi;exports.isDisabledStep=We;exports.isPausedStep=st;exports.pausedStopAt=ps;exports.pruneSectionMembers=ms;exports.renameSectionMember=ls;exports.roundGeometry=as;exports.sectionsContaining=Pn;exports.withCanvasGeometry=Rn;exports.withDisabled=_n;exports.withPaused=Mn;
8
+ `);return e.jsx("span",{"data-step-problem-badge":"",role:"img","aria-label":s,title:s,style:{position:"absolute",top:-9,right:-9,width:18,height:18,borderRadius:"50%",display:"flex",alignItems:"center",justifyContent:"center",background:"var(--w6w-danger)",color:"#fff"},children:e.jsx(be.Icon,{name:"warning",size:12})})}function Hi(t){const s=i.useW6WApi(),o=t.uses.action,[n,r]=u.useState(null),l=t.uses.trigger===!0,c=t.uses.app;return u.useEffect(()=>{if(!l||!s.getAppTriggers)return;let p=!1;return s.getAppTriggers(c).then(d=>{var x;return!p&&r(((x=d.find(h=>h.key===o))==null?void 0:x.title)??null)}).catch(()=>{}),()=>{p=!0}},[s,c,o,l]),n||o}function Ji(t){const s=i.useW6WApi(),o=s.listSubscriptionsForWorkflow,n=s.retrySubscriptionRegistration,r=t.id,l=[...Pi(t.nodes),...(t.nodes??[]).filter(y=>{var C,A;return(((C=y.uses)==null?void 0:C.app)===i.WEBHOOK_APP||((A=y.uses)==null?void 0:A.app)===i.FORM_APP)&&y.uses.trigger!==!0})],c=l.length>0,p=l.map(y=>`${y.id}:${y.uses.app}:${y.uses.action}:${i.connectionIdFor(y,t.connections)??""}`).join("|"),[d,x]=u.useState([]),h=u.useMemo(()=>Ri(d),[d]),[m,k]=u.useState(0);u.useEffect(()=>{if(!o||!c){x([]);return}let y=!1;return o.call(s,r).then(C=>!y&&x(C)).catch(()=>{}),()=>{y=!0}},[s,o,r,c,p,m]);const v=u.useMemo(()=>n?async y=>{try{await n.call(s,y)}finally{k(C=>C+1)}}:void 0,[s,n]);return u.useMemo(()=>({byNode:h,subs:d,retry:v}),[h,d,v])}function qi({nodeId:t}){const{byNode:s,retry:o}=u.useContext(Bn),[n,r]=u.useState(!1),l=s.get(t),c=Ai(l,o!==void 0);return!l||!c?null:e.jsxs("div",{className:"w6w-small","data-trigger-registration":l.status,"data-tone":c.tone,style:{marginTop:3,paddingLeft:2},children:[e.jsx("span",{style:c.tone==="danger"?{color:"var(--w6w-danger)"}:void 0,children:c.label}),e.jsxs("span",{className:"w6w-muted",children:[" · ",c.lastFire]}),c.error&&e.jsx("div",{role:"alert",title:c.error,style:{color:"var(--w6w-danger)",maxWidth:300,overflow:"hidden",overflowWrap:"anywhere",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:c.error}),c.retryVisible&&o&&e.jsx("button",{type:"button",className:"nodrag",disabled:n,onClick:()=>{r(!0),o(l.id).catch(()=>{}).finally(()=>r(!1))},children:"Retry"})]})}function Gi({id:t,data:s,selected:o}){const n=s.step,l=u.useContext(bs).get(n.uses.app),c=(l==null?void 0:l.displayName)||n.uses.app||"—",p=i.isTriggerStep(n.uses),d=Hi(n),x=n.uses.trigger?`${c} · ${d}`:c,h=i.nodePortsForStep(n,u.useContext(gs)),m=Wn(s.stepStatus??"no-run",s.runStatus),k=e.jsx(Gn,{step:n,count:u.useContext(xs).get(t)??0}),v=Jn(t);return e.jsxs("div",{className:[s.loopOf?"w6w-node-in-loop":"",We(n)?"w6w-node-disabled":""].filter(Boolean).join(" ")||void 0,"data-loop-of":s.loopOf,style:v,"data-disabled":We(n)||void 0,"data-paused":st(n)||void 0,children:[e.jsx(qn,{id:t,step:n,runnable:!0}),e.jsxs("div",{className:p?"w6w-node-trigger":void 0,"data-node-kind":p?"trigger":void 0,"data-run-status":s.stepStatus??"no-run",...Yn(s.stepProblems),style:{position:"relative",...s.stepProblems?{boxShadow:"0 0 0 2px var(--w6w-danger)"}:{},border:`${m.borderWidth}px ${m.borderStyle} ${o?"var(--w6w-accent)":m.borderColor}`,opacity:We(n)?.45:o?1:m.opacity,background:"var(--w6w-panel)",color:"var(--w6w-text)",...p?{}:{borderRadius:4,padding:"8px 12px"},minWidth:180,fontSize:13,display:"flex",alignItems:"center",gap:10},children:[e.jsx(Xn,{problems:s.stepProblems}),h.in>0&&e.jsx(Je,{type:"target",position:le.Position.Left,multiple:h.in>1}),e.jsx(i.AppIcon,{src:l==null?void 0:l.iconSvg,srcDark:l==null?void 0:l.iconSvgDark,brandColor:l==null?void 0:l.brandColor,name:c,size:28}),e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontWeight:600},children:x}),e.jsx("div",{className:"w6w-muted w6w-small",style:{marginTop:2},children:e.jsx("code",{children:n.uses.action||"—"})})]}),h.out>0&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{type:"source",position:le.Position.Right,multiple:h.out>1}),!p&&e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:i.ERROR_SOURCE_HANDLE,variant:"error"})]})]}),k,e.jsx(Kn,{step:n}),p&&n.uses.trigger===!0&&e.jsx(qi,{nodeId:t}),s.loopOf&&e.jsx(Hn,{id:t}),e.jsxs("div",{className:"w6w-muted",style:{marginTop:3,fontSize:10,opacity:.75,paddingLeft:2},children:[n.id,l!=null&&l.version?` - v${l.version}`:""]}),n.notes&&e.jsx("div",{className:"w6w-muted w6w-node-notes",title:n.notes,children:n.notes})]})}function Ki({id:t,data:s,selected:o}){const n=s.step,r=i.routesForStep(n),l=n.uses.app===i.ROUTER_APP,c=i.isIfStep(n),p=r.length?i.routerPortLayout(r):c?i.ifPortLayout():void 0,d=JSON.stringify(r.map(M=>M.id)),x=le.useUpdateNodeInternals();u.useEffect(()=>{x(t)},[t,d,x]);const h=i.internalNodeLabel(n.uses.app,n.uses.action),m=i.internalNodeIcon(n.uses.app,n.uses.action),k=i.nodePortsForStep(n,u.useContext(gs)),v=i.isTriggerStep(n.uses),y=Ui(n),C=i.isLoopCloser(n),A=Wn(s.stepStatus??"no-run",s.runStatus),w=e.jsx(Gn,{step:n,count:u.useContext(xs).get(t)??0}),D=Jn(t),$=u.useContext(zt).tones;return e.jsxs("div",{className:[y?"w6w-node-foreach":"",s.loopOf?"w6w-node-in-loop":"",We(n)?"w6w-node-disabled":""].filter(Boolean).join(" ")||void 0,"data-loop-of":s.loopOf,style:D,"data-disabled":We(n)||void 0,"data-paused":st(n)||void 0,children:[e.jsx(qn,{id:t,step:n,runnable:!i.isControlApp(n.uses.app)}),e.jsxs("div",{className:v?"w6w-node-trigger":l?"w6w-node-router":void 0,"data-node-kind":v?"trigger":void 0,"data-run-status":s.stepStatus??"no-run",...Yn(s.stepProblems),style:{position:"relative",...s.stepProblems?{boxShadow:"0 0 0 2px var(--w6w-danger)"}:{},border:`${A.borderWidth}px ${A.borderStyle} ${o?"var(--w6w-accent)":A.borderColor}`,opacity:We(n)?.45:o?1:A.opacity,background:"var(--w6w-panel-2)",color:"var(--w6w-text)",...v?{}:{borderRadius:4,padding:"6px 14px 6px 8px"},minWidth:140,...p!=null&&p.minHeight?{minHeight:p.minHeight,boxSizing:"border-box"}:{},fontSize:13,display:"flex",alignItems:"center",gap:10},children:[e.jsx(Xn,{problems:s.stepProblems}),k.in>0&&e.jsx(Je,{type:"target",position:le.Position.Left,multiple:k.in>1}),m&&e.jsx(i.InternalIcon,{icon:m}),e.jsxs("div",{style:{minWidth:0,textAlign:"left"},children:[e.jsx("div",{style:{fontWeight:600},children:h}),e.jsx("div",{className:"w6w-muted w6w-small",style:{marginTop:2},children:e.jsx("code",{children:n.uses.action||"—"})})]}),y&&e.jsxs("div",{className:"w6w-foreach-ports w6w-small","aria-hidden":"true",children:[e.jsx("span",{children:i.isForeachStep(n)?"Each item":"Each pass"}),e.jsx("span",{children:"Done"})]}),C&&e.jsx("span",{className:"w6w-loop-back w6w-small","data-testid":"loop-back-marker",title:s.loopOf?`Loops back to ${s.loopOf}`:"Loops back",style:s.loopOf?{"--w6w-loop-color":Bt($.get(s.loopOf)??1)}:void 0,children:"↺ Loops back"}),c&&(p==null?void 0:p.right[0])&&e.jsx("span",{className:"w6w-if-true-label w6w-small","aria-hidden":"true",children:p.right[0].label}),!c&&!!(p!=null&&p.right.length)&&e.jsx("div",{className:"w6w-router-ports w6w-small",style:{gridTemplateRows:`repeat(${p.right.length}, 1fr)`},"aria-hidden":"true",children:p.right.map(M=>e.jsx("span",{title:M.label,children:M.label},M.id))}),k.out>0&&!C&&e.jsxs(e.Fragment,{children:[y&&e.jsx(Je,{type:"source",position:le.Position.Right,multiple:!1,id:i.EACH_SOURCE_HANDLE,variant:"each"}),p?e.jsxs(e.Fragment,{children:[p.right.map(M=>e.jsx(Je,{type:"source",position:le.Position.Right,multiple:!1,id:M.handleId,top:M.top,routeLabel:M.label},M.id)),p.bottom&&e.jsxs(e.Fragment,{children:[e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:p.bottom.handleId,routeLabel:p.bottom.label}),e.jsx("span",{className:"w6w-router-fallback-label w6w-small","aria-hidden":"true",children:p.bottom.label})]})]}):e.jsx(Je,{type:"source",position:le.Position.Right,multiple:k.out>1,id:y?i.routeHandle(i.FOREACH_DONE_ROUTE):void 0}),!v&&!l&&!c&&n.uses.app!==i.RACE_APP&&e.jsx(Je,{type:"source",position:le.Position.Bottom,multiple:!1,id:i.ERROR_SOURCE_HANDLE,variant:"error"})]})]}),w,e.jsx(Kn,{step:n}),s.loopOf&&e.jsx(Hn,{id:t}),s.legacyLoop&&e.jsx("div",{className:"w6w-loop-legacy-note w6w-small",children:"This loop was converted from an older definition. Its steps after For each now run once per item; check the order, then save."}),e.jsx("div",{className:"w6w-muted",style:{marginTop:3,fontSize:10,opacity:.75,paddingLeft:2},children:n.id}),n.notes&&e.jsx("div",{className:"w6w-muted w6w-node-notes",title:n.notes,children:n.notes})]})}function Yi(t,s){var c,p;if(!s)return t;const o={...(t==null?void 0:t.steps)??{}};let n=!1;for(const[d,x]of Object.entries(s)){const h=/^nodes\.([^.]+)\.output$/.exec(d);!h||((c=o[h[1]])==null?void 0:c.output)!==void 0||(o[h[1]]={...o[h[1]]??{},output:x},n=!0)}const r=s["trigger.event"],l=r!==void 0&&((p=t==null?void 0:t.trigger)==null?void 0:p.event)===void 0;return!n&&!l?t:{...t??{},...n?{steps:o}:{},...l?{trigger:{...(t==null?void 0:t.trigger)??{},event:r}}:{}}}function Xi(t){return e.jsx(Zi,{...t})}function Zi({workflowId:t,step:s,restoreVersion:o,upstreamSteps:n,loop:r,onChange:l,onClose:c,onCancel:p,readOnly:d,initialView:x="props",fanOutCount:h=0,stateOutputFields:m,onTestRun:k,stepProblems:v,otherStepIds:y}){var St,Nt,it,Ne;const C=i.useW6WApi(),A=u.useContext(bs),[w,D]=u.useState(s),$=i.useWorkflowConnections(),M=i.connectionIdFor(w,$==null?void 0:$.connections),R={...w,uses:{...w.uses,connection:M}},E=w.uses.connectionRef!==void 0&&!M||i.isConnectionBlocked(R,v),z=v==null?void 0:v.find(I=>I.code==="unknown_connection"&&I.connection===M),Y=(v??[]).filter(I=>"fix"in I),[N,g]=u.useState(E?"setup":"configure"),[P,X]=u.useState(x==="json"?"code":x==="settings"?"config":"props"),[B,ie]=u.useState("props"),[te,T]=u.useState(()=>i.stepToJson(s)),[Z,F]=u.useState("{}"),U=u.useRef(null),[J,ae]=u.useState(!1),G=u.useRef(o);u.useEffect(()=>{G.current!==o&&(G.current=o,D(s),T(i.stepToJson(s)))},[o,s]);const[q,K]=u.useState(!1),[se,ge]=u.useState(null),[qe,_e]=u.useState(null),[ct,ke]=u.useState(null),[Ge,Pe]=u.useState(!1),ve=i.isInternalApp(w.uses.app),ce=w.uses.trigger===!0;u.useEffect(()=>{if(ve){ge(i.internalNodeParams(w.uses.app,w.uses.action));const ee=i.internalNodeDef(w.uses.app,w.uses.action),fe=i.INTERNAL_NODES.filter(ue=>ue.app===w.uses.app&&ue.groupActions&&(!ue.hidden||(ee==null?void 0:ee.hidden)));_e(fe.length?fe.map(ue=>({key:ue.action,title:ue.label,params:ue.params})):null);return}if(!w.uses.app){_e(null),ge([]);return}let I=!1;return ge(null),(ce?i.getTriggerDefs(C,w.uses.app):C.getAppActions(w.uses.app)).then(ee=>{var fe;I||(_e(ee),ge(w.uses.action?((fe=ee.find(ue=>ue.key===w.uses.action))==null?void 0:fe.params)??[]:[]))}).catch(()=>!I&&ge([])),()=>{I=!0}},[C,w.uses.app,w.uses.action,ve,ce]);const Ie=u.useRef(0);u.useEffect(()=>()=>{Ie.current++},[]);const Be=u.useCallback(()=>{ve||!w.uses.app||C.listConnectionsForApp(w.uses.app).then(I=>{ke(I),Pe(!1)}).catch(()=>Pe(!0))},[C,w.uses.app,ve]);u.useEffect(()=>{if(ve||!w.uses.app)return;let I=!1;return ke(null),Pe(!1),C.listConnectionsForApp(w.uses.app).then(ee=>{I||(ke(ee),Pe(!1))}).catch(()=>!I&&Pe(!0)),()=>{I=!0}},[C,w.uses.app,ve]);const re=u.useCallback(I=>{D(I),l(I)},[l]),vt=Ko({enabled:w.uses.app===i.SCRIPT_APP&&!d,values:w.with??{},onChange:I=>re({...w,with:I})}),de=I=>{I==="code"&&T(i.stepToJson(w)),X(I)},Le=I=>{const ee=i.stepNameError(I,y??[]);return ee||re({...w,id:I}),ee},Oe=!!w.uses.app&&!!w.uses.action&&!i.isControlApp(w.uses.app),Ae=i.isForeachStep(w),je=i.isTriggerStep(w.uses),Ke=N==="test"&&Oe&&!je,Se=i.useSeedSources(t,n,Oe&&!je||Ae),Ve=Vn(Oe&&!je?r:void 0),Fe=i.useExpressionOptions(),ze=i.startStateFromSeeds(Se,zn(Ve),(St=Fe.stateShape)==null?void 0:St.written),dt=Yi(ze,Fe.sampleValues),Ee=i.useRememberedTestInput(Oe&&!je||Ae?t:void 0,w.id),[xe,$e]=u.useState(!1);u.useEffect(()=>{if((!Oe||je)&&!Ae||!Ee.loaded)return;if(!Ae&&Ee.input!==void 0){const ee=Ee.input;if(Object.keys(ee).length===0)return;const fe=JSON.stringify(ee,null,2);F(ue=>ue.trim()==="{}"?fe:ue),$e(!0);return}let I=!1;return C.listStepTests(t,w.id).then(ee=>{if(I)return;const fe=ee.length?ee[ee.length-1]:null;if(!(fe!=null&&fe.input)||Object.keys(fe.input).length===0)return;const ue=JSON.stringify(fe.input,null,2);F(Xe=>Xe.trim()==="{}"?ue:Xe)}).catch(()=>{}),()=>{I=!0}},[C,t,w.id,Oe,je,Ae,Ee.loaded]);const De=Ae?Bi(Z):Ut(Z),Me={...w.with??{},...De??{}},ut=De??{},nt=!!se&&!js(Ve)&&i.requiredParamsFilled(se,Me)&&(w.uses.app!==i.CALL_APP||q),ne=Ae?i.resolveLoopItemsInState(Me.items,ze):void 0,[ot,Ye]=u.useState("idle"),jt=I=>{F(I),Ye("idle")},pt=async()=>{if(ne){Ye("saving");try{await C.saveStepTest(t,w.id,i.foreachTestFixture(ne,ut)),Ye("saved")}catch{Ye("failed")}}},we=A.get(w.uses.app),yt=ce?(Nt=qe==null?void 0:qe.find(I=>I.key===w.uses.action))==null?void 0:Nt.webhook:void 0,ft=ve?i.internalNodeIcon(w.uses.app,w.uses.action):null,Ht=ve?ft?e.jsx(i.InternalIcon,{icon:ft}):null:e.jsx(i.AppIcon,{src:we==null?void 0:we.iconSvg,srcDark:we==null?void 0:we.iconSvgDark,brandColor:we==null?void 0:we.brandColor,name:we==null?void 0:we.displayName});return e.jsx(i.Modal,{ariaLabel:"Edit step",titleIcon:Ht,title:e.jsx(i.StepNameEditor,{value:w.id,onCommit:Le,readOnly:d}),onClose:p??c,size:"wide",children:e.jsxs("div",{className:"w6w-stepconfig",children:[e.jsxs("div",{className:"w6w-tabsbar",children:[e.jsx("div",{className:"w6w-subtabs",children:["setup","configure","test"].filter(I=>w.uses.app!==i.RACE_APP||I!=="test").map(I=>e.jsx("button",{type:"button",className:`w6w-subtab${N===I?" active":""}`,disabled:E&&I!=="setup",onClick:()=>g(I),children:I==="setup"?"Setup":I==="configure"?"Configure":"Test"},I))}),Ke?e.jsx(i.ConfigViewToggle,{view:B,views:["props","code"],onChange:I=>ie(I)}):e.jsx(i.ConfigViewToggle,{view:P,customized:i.hasParamCustomization(w.with??{}),onChange:de,disabled:N!=="configure"})]}),E&&z&&e.jsxs("div",{role:"alert",className:"w6w-field-error",children:["Connection ",z.connection," no longer exists — choose another to continue."]}),Y.length>0&&e.jsx("div",{className:"w6w-stepproblem-fixes",style:{display:"grid",gap:6},children:Y.map(I=>e.jsxs("div",{className:"w6w-small",style:{display:"flex",gap:8,alignItems:"center"},children:[e.jsx("span",{children:i.stepProblemTooltip(I)}),e.jsx("button",{type:"button",className:"w6w-btn","data-fix-code":I.code,disabled:d,onClick:()=>{const ee=$n(w,I);re(ee),T(i.stepToJson(ee))},children:"fix"in I?I.fix.label:""})]},I.code))}),e.jsxs("div",{className:"w6w-stepconfig-body",children:[N==="setup"&&w.uses.app===i.CALL_APP&&e.jsx(i.CallTargetForm,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d,onValidityChange:K,setupOnly:!0}),N==="setup"&&w.uses.app!==i.CALL_APP&&e.jsx(tr,{step:w,app:we,actions:qe,conns:ct,connsFailed:Ge,isInternal:ve,actionLabel:ce?"Trigger":"Action",readOnly:d,onChangeAction:I=>{var fe;const ee=ve?i.internalNodeDefaults(w.uses.app,I):{};if(ve)for(const ue of i.internalNodeParams(w.uses.app,I))ue.key in(w.with??{})&&(ee[ue.key]=(fe=w.with)==null?void 0:fe[ue.key]);re({...w,uses:{...w.uses,action:I},with:ee})},onChangeTriggerEvents:(I,ee)=>re({...w,uses:{...w.uses,action:I},with:{...w.with,actions:ee}}),onChangeConnection:I=>{if(!$){const{connectionRef:fe,...ue}=w.uses;re({...w,uses:{...ue,connection:I}});return}const ee=i.selectNodeConnection(w,I,($==null?void 0:$.nodes)??[w],($==null?void 0:$.connections)??{});$==null||$.setConnections(ee.connections),re(ee.step)},onChangeConnectionRef:I=>re(i.withConnectionRef(w,I)),onConnectionCreated:Be,onChangeApp:I=>{const ee=++Ie.current;if(I===w.uses.app){re(w);return}const fe={...w,uses:{app:I,action:"",...ce?{trigger:!0}:{}},with:{}};(i.isInternalApp(I)?Promise.resolve([]):C.listConnectionsForApp(I)).catch(()=>[]).then(ue=>{if(ee!==Ie.current)return;const Xe=i.defaultConnectionFor(fe,ue,($==null?void 0:$.nodes)??[],($==null?void 0:$.connections)??{});re({...fe,uses:{...fe.uses,...Xe}})})}}),N==="configure"&&e.jsxs(e.Fragment,{children:[(w.uses.app===i.WEBHOOK_APP||w.uses.app===i.FORM_APP)&&C.listSubscriptionsForWorkflow&&C.createSubscription&&e.jsx(er,{workflowId:t,step:w,readOnly:d}),ce&&yt&&w.uses.action&&C.listSubscriptionsForWorkflow&&e.jsx(Mo,{workflowId:t,nodeId:w.id,appId:w.uses.app,triggerKey:w.uses.action,appName:(we==null?void 0:we.displayName)??w.uses.app,setup:yt,connectionId:M&&!M.startsWith("zerocred:")?M:null,params:w.with??{},readOnly:d}),se===null?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading parameters…"}):P==="props"?w.uses.app===i.CALL_APP?e.jsx(i.CallTargetForm,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d,onValidityChange:K}):w.uses.app===i.RACE_APP?e.jsx("p",{className:"w6w-muted w6w-small",children:i.RACE_DESCRIPTION}):w.uses.action==="wait"&&i.isControlApp(w.uses.app)?e.jsx(i.WaitEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.action==="if"&&i.isControlApp(w.uses.app)?e.jsx(i.ConditionEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app==="@w6w/stop"?e.jsx(i.StopEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app===i.ROUTER_APP?e.jsx(i.RouterEditor,{values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})}):w.uses.app===i.FORM_APP?e.jsxs("div",{className:"w6w-stack",children:[e.jsx(yo,{value:(it=w.with)==null?void 0:it.form,readOnly:d,stepId:w.id,onChange:I=>re({...w,with:{...w.with,form:I}})}),e.jsx(i.ParamsForm,{params:se.filter(I=>I.key!=="form"),values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I})})]}):e.jsxs(e.Fragment,{children:[w.uses.app===i.SCRIPT_APP&&e.jsx(Yo,{values:w.with??{},conversion:vt,readOnly:d}),e.jsx(i.ParamsForm,{params:se,values:w.with??{},readOnly:d,onChange:I=>re({...w,with:I}),dynamic:ve||!w.uses.action?void 0:{appId:w.uses.app,actionKey:w.uses.action,kind:i.isTriggerStep(w.uses)?"trigger":"action",connectionId:E?void 0:M,appName:we==null?void 0:we.displayName}})]}):P==="code"?e.jsx(i.JsonEditor,{value:te,onChange:()=>{},readOnly:!0,minHeight:"260px",height:"100%","aria-label":`Node ${w.id} JSON`,copyable:!0}):P==="params-code"?e.jsx(i.ParamCustomization,{values:w.with??{},onChange:I=>re({...w,with:I}),readOnly:d}):e.jsxs("div",{className:"w6w-stack",children:[e.jsx(i.NodeConfigForm,{config:{retry:w.retry,onError:w.onError,notes:w.notes,timeoutMs:w.timeoutMs},onChange:I=>re({...w,...I}),readOnly:d,failureHandling:!je,retryControls:!i.isControlApp(w.uses.app)&&w.uses.app!==i.CALL_APP}),Qi,e.jsx(i.StepFanOutControl,{step:w,count:h,readOnly:d,onChange:re}),i.stateWriteVisible(w)&&e.jsx(i.StepStateControl,{step:w,inLoop:r!==void 0,outputFields:m,readOnly:d,onChange:re})]})]}),N==="test"&&e.jsx("div",{className:"w6w-stack",children:Oe?je?e.jsx(i.TriggerFillForm,{app:w.uses.app,action:w.uses.action,fields:ce||(Ne=w.with)==null?void 0:Ne.fields,appTrigger:ce,persist:{workflowId:t,stepId:w.id,input:ut},listen:(w.uses.app===i.WEBHOOK_APP||w.uses.app===i.FORM_APP)&&C.listSubscriptionsForWorkflow&&C.startWebhookListen?{stepWith:w.with,readOnly:d,appId:w.uses.app}:void 0}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Tests ",e.jsx("code",{children:w.uses.action})," with the configuration saved on this step — only the incoming state changes per run."]}),e.jsx(Un,{seed:Ve,readOnly:d}),xe&&!d&&e.jsx(i.LastUsedNote,{onClear:()=>{Ee.clear(),$e(!1),F("{}")}}),e.jsx(hs,{text:Z,onChange:F,seeds:Se,readOnly:d}),se===null?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading parameters…"}):e.jsx(Uo,{params:se,values:Me,testStartState:dt,view:B,literalKeys:w.uses.app===i.SCRIPT_APP?Wi:void 0}),e.jsx(i.StepTestRun,{ref:U,app:w.uses.app,action:w.uses.action,connectionId:M,values:Me,timeoutMs:w.timeoutMs,state:ze,canRun:nt,hideRunButton:!0,persist:{workflowId:t,stepId:w.id,input:ut},onBusyChange:ae})]}):Ae?e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"w6w-muted w6w-small",children:["Resolves ",e.jsx("strong",{children:"Items"})," against the incoming state — nothing inside the loop runs. ",e.jsx("strong",{children:"Test"})," saves the first item as this loop's sample, so the steps on its ",e.jsx("strong",{children:"Each item"})," output can pick its keys. To run the loop's work, test a step on ",e.jsx("strong",{children:"Each item"}),": it runs once, on one item."]}),e.jsx(hs,{text:Z,onChange:jt,seeds:Se,readOnly:d,expand:!ne,hint:e.jsxs(e.Fragment,{children:["Paste a sample list — ",e.jsx("code",{children:'[{"id": 1, "name": "…"}]'})," — or"," ",e.jsx("code",{children:'{"items": […]}'}),". It replaces what ",e.jsx("strong",{children:"Items"})," ","resolves to, for this test only."]})}),e.jsx(Vi,{items:ne,save:ot})]}):e.jsx("p",{className:"w6w-muted w6w-small",children:"Flow-control nodes can't be tested on their own."})})]}),e.jsxs("div",{className:"w6w-modal-actions w6w-stepconfig-footer",children:[p&&!d&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:p,children:"Cancel"}),w.uses.app===i.RACE_APP&&N==="configure"?e.jsx("button",{type:"button",className:"w6w-btn",onClick:c,children:"Done"}):N!=="test"?e.jsxs(e.Fragment,{children:[p&&!d&&e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:c,children:"Done"}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:E,onClick:()=>g(N==="setup"?"configure":"test"),children:"Next →"})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:c,children:"Done"}),Oe&&!je&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:d||!nt||J,onClick:()=>{var I;k==null||k(),(I=U.current)==null||I.run()},children:J?"Testing…":"Test"}),Ae&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:d||!(ne!=null&&ne.length)||ot==="saving",onClick:()=>void pt(),children:ot==="saving"?"Testing…":"Test"})]})]})]})})}const Qi=!1;function er({workflowId:t,step:s,readOnly:o}){const n=i.useW6WApi(),r=s.uses.app===i.FORM_APP,[l,c]=u.useState(void 0),[p,d]=u.useState(null),[x,h]=u.useState(!1),m=(l==null?void 0:l.webhookUrl)??(l==null?void 0:l.formUrl);u.useEffect(()=>{const v=n.listSubscriptionsForWorkflow;if(!v)return;let y=!1;return v(t).then(C=>{y||c(r?i.pickFormSubscription(C,s.id):i.pickWebhookSubscription(C,s.id))}).catch(C=>!y&&d(C.message)),()=>{y=!0}},[n,t,s.id,r]);const k=()=>{const v=n.createSubscription;v&&(d(null),h(!0),v(r?i.FORM_APP:i.WEBHOOK_APP,s.uses.action,{workflowId:t,connectionId:null,params:r?{node:s.id}:s.with??{}}).then(y=>{h(!1),c(y)}).catch(y=>{h(!1),d(y instanceof Error?y.message:String(y))}))};return e.jsxs("div",{className:"w6w-stack w6w-url-panel",children:[e.jsx("p",{className:"w6w-muted w6w-small",children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Form URL"})," — share it, or embed it in an iframe. Each submission starts the workflow once it is published."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Webhook URL"})," — the address a third party posts to."]})}),p&&e.jsx("div",{className:"w6w-result w6w-error",children:p}),m?e.jsxs("div",{className:"w6w-listen-url",children:[e.jsx(be.Copyable,{value:m,readOnly:!0,children:e.jsx("input",{type:"text",readOnly:!0,value:m,"aria-label":r?"Form URL":"Webhook URL"})}),r&&e.jsx("a",{className:"w6w-btn w6w-btn-ghost w6w-btn-sm",href:m,target:"_blank",rel:"noreferrer",children:"Open form"})]}):l===void 0?e.jsx("p",{className:"w6w-muted w6w-small",children:"Loading…"}):!o&&e.jsx("button",{type:"button",className:"w6w-btn",disabled:x,onClick:k,children:x?"Creating…":r?"Create form URL":"Create webhook URL"})]})}function tr({step:t,app:s,actions:o,conns:n,connsFailed:r,isInternal:l,actionLabel:c="Action",readOnly:p,onChangeAction:d,onChangeTriggerEvents:x,onChangeConnection:h,onChangeConnectionRef:m,onChangeApp:k,onConnectionCreated:v}){const y=t.uses.trigger?i.eventbriteTriggerChoices(t.uses.app,o,t.uses.action,t.with??{}):null,[C,A]=u.useState(null),w=u.useRef(null),D=i.useWorkflowConnections(),$=i.connectionIdFor(t,D==null?void 0:D.connections);return e.jsxs("div",{className:"w6w-stack",children:[t.uses.connectionRef&&!$&&e.jsx("p",{role:"alert",className:"w6w-field-error",children:"The shared connection is missing or unbound. Choose an account."}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"App"}),e.jsxs("div",{className:"w6w-app-conn-row",ref:w,children:[e.jsxs("button",{type:"button",className:"w6w-app-conn-btn","aria-label":"App","aria-expanded":C==="app",disabled:p,onClick:()=>A(M=>M==="app"?null:"app"),children:[!l&&s&&e.jsx(i.AppIcon,{src:s.iconSvg,srcDark:s.iconSvgDark,brandColor:s.brandColor,name:s.displayName,size:20}),e.jsx("span",{className:"w6w-conn-label-name",children:l?t.uses.app:(s==null?void 0:s.displayName)??t.uses.app})]}),!l&&e.jsx(i.WorkflowConnectionPicker,{step:t,conns:n,failed:r,readOnly:p,open:C==="conn",onOpenChange:M=>A(M?"conn":null),anchorRef:w,onChangeConnection:h,onChangeConnectionRef:m,onConnectionCreated:v})]}),C==="app"&&e.jsx(i.AnchoredFlyout,{anchorRef:w,onClose:()=>A(null),children:e.jsx(i.AppPicker,{onSelectApp:M=>{const R=M.id===t.uses.app;k(M.id),A(R?"conn":null)}})})]}),l&&!(o!=null&&o.length)?e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:"Action"}),e.jsx("div",{className:"w6w-muted w6w-small",children:e.jsx("code",{children:t.uses.action})})]}):y?e.jsx(i.EventbriteTriggerPicker,{choices:y,readOnly:p,onChange:M=>x(y.triggerKey,M)}):e.jsxs("label",{className:"w6w-field",children:[e.jsx("span",{children:c}),e.jsx(i.Combobox,{value:t.uses.action,disabled:p||o===null,onChange:d,options:o===null?[{value:t.uses.action,label:t.uses.action}]:o.map(M=>({value:M.key,label:M.title??M.key}))})]})]})}function En({trigger:t}){return e.jsx("span",{className:"w6w-connection-node-kind",role:"img","aria-label":t?"Trigger":"Node",children:e.jsx("svg",{"aria-hidden":"true",width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:t?e.jsx("path",{d:"M13 2 4 14h7l-1 8 10-12h-7l1-8Z"}):e.jsxs(e.Fragment,{children:[e.jsx("rect",{x:"5",y:"5",width:"14",height:"14",rx:"3"}),e.jsx("path",{d:"M2 12h3m14 0h3"})]})})})}function sr({resources:t}){const s=i.useW6WApi(),o=t.highlightNode;u.useEffect(()=>()=>o==null?void 0:o(null),[o]);const[n,r]=u.useState([]),[l,c]=u.useState(!0),[p,d]=u.useState(),[x,h]=u.useState(),[m,k]=u.useState(null),[v,y]=u.useState(!1),[C,A]=u.useState(!1),w=u.useRef(0),D=u.useCallback(async()=>{const F=++w.current;c(!0),d(void 0);try{const U=await s.listConnections();return F!==w.current?void 0:(r(U),U)}catch(U){F===w.current&&d(U.message)}finally{F===w.current&&c(!1)}},[s]);u.useEffect(()=>(D(),()=>{w.current++}),[D]);const[$,M]=u.useState(new Map),R=JSON.stringify([...new Set([...Object.values(t.connections).map(F=>F.app),...n.map(F=>F.appId)])].filter(F=>{var U;return!((U=t.apps)!=null&&U.has(F))&&!n.some(J=>J.appId===F&&J.app!==void 0)}).sort());u.useEffect(()=>{var G,q;let F=!1;const U=JSON.parse(R);if(l||!U.length)return;const J=(G=s.listAppsByIds)==null?void 0:G.bind(s),ae=J?Promise.all(Array.from({length:Math.ceil(U.length/50)},(K,se)=>J(U.slice(se*50,(se+1)*50)))).then(K=>K.flat()):(q=s.listApps)==null?void 0:q.call(s);return ae==null||ae.then(K=>{F||M(new Map(K.map(se=>[se.id,se])))}).catch(()=>{}),()=>{F=!0}},[s,R,l]);const L=F=>{var G;const U=n.find(q=>q.appId===F&&q.app)??n.find(q=>q.appId===F&&q.app!==void 0),J=U?i.resolveConnectionAppMeta(U,$):$.get(F),ae=(G=t.apps)==null?void 0:G.get(F);return ae?{...J,...ae}:J},E=F=>{var U;return((U=L(F))==null?void 0:U.displayName)||F},z=F=>{if(t.readOnly)return!1;try{return t.edit(F),h(void 0),!0}catch(U){return h(U.message),!1}},Y=F=>i.nextWorkflowConnectionName(F.appId,t.connections),N=()=>{k(null),h(void 0),y(!1)},g=m!=null&&m.ref?t.connections[m.ref]:void 0,P=n.find(F=>F.id===(m==null?void 0:m.connection)),X=(g==null?void 0:g.app)??(P==null?void 0:P.appId),B=t.nodes.filter(F=>F.uses.app===X),ie=t.nodes.filter(F=>(m==null?void 0:m.ref)!==void 0&&F.uses.connectionRef===m.ref),te=n.filter(F=>!g||F.appId===g.app).map(F=>({value:F.id,label:g?F.displayName||F.id:`${E(F.appId)} · ${F.displayName||F.id}`}));m!=null&&m.connection&&!te.some(F=>F.value===m.connection)&&te.unshift({value:m.connection,label:m.connection.startsWith("zerocred:")?"Built-in":m.connection});const T=(F,U=28)=>{const J=L(F);return e.jsx(i.AppIcon,{src:J==null?void 0:J.iconSvg,srcDark:J==null?void 0:J.iconSvgDark,brandColor:J==null?void 0:J.brandColor,name:E(F),size:U})},Z=()=>{if(!m||!m.name.trim()||!m.connection||!X)return;const F=m.ref!==void 0?{type:"update",ref:m.ref,name:m.name,connection:m.connection,nodeIds:m.allNodes?B.map(U=>U.id):void 0}:{type:"add",name:m.name,app:X,connection:m.connection};z(F)&&N()};return e.jsxs("div",{className:"w6w-stack","data-testid":"workflow-connections-panel",children:[e.jsxs("div",{className:"w6w-workflow-connections-heading",children:[e.jsx("h3",{children:"Connections"}),e.jsx(i.IconButton,{label:"Add connection",disabled:t.readOnly,onClick:()=>{h(void 0),k({name:"",connection:"",allNodes:!1})},children:e.jsx("svg",{"aria-hidden":"true",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),p&&e.jsxs("div",{role:"alert",className:"w6w-stack",children:[e.jsxs("p",{className:"w6w-field-error",children:["Couldn’t load connections: ",p]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:()=>void D(),children:"Retry"})]}),Object.entries(t.connections).map(([F,U])=>{var q;const J=t.nodes.filter(K=>K.uses.connectionRef===F),ae=n.find(K=>K.id===U.connection),G=(ae==null?void 0:ae.displayName)||((q=U.connection)!=null&&q.startsWith("zerocred:")?"Built-in":U.connection)||"No credentials selected";return e.jsxs("section",{className:"w6w-workflow-connection","data-connection-resource":F,children:[e.jsxs("div",{className:"w6w-connection-app-heading",children:[T(U.app),e.jsxs("div",{className:"w6w-connection-summary",children:[e.jsx("strong",{children:E(U.app)}),e.jsx("span",{className:"w6w-small",children:G}),e.jsxs("span",{className:"w6w-muted w6w-small",children:[F,ae!=null&&ae.state?` · ${ae.state}`:""]})]}),e.jsx(i.IconButton,{icon:"edit",label:`Edit connection ${F}`,disabled:t.readOnly,onClick:()=>{h(void 0),k({ref:F,name:F,connection:U.connection??"",allNodes:!1})}})]}),J.length>0?e.jsxs("details",{className:"w6w-connection-consumers",onToggle:K=>{K.currentTarget.open||o==null||o(null)},children:[e.jsxs("summary",{className:"w6w-muted w6w-small",children:["Used by ",J.length," ",J.length===1?"node":"nodes"]}),e.jsx("ul",{className:"w6w-connection-node-list",children:J.map(K=>e.jsx("li",{children:t.focusNode?e.jsxs("button",{type:"button",className:"w6w-btn w6w-btn-ghost","aria-label":`Show ${K.id} on canvas`,onClick:()=>{var se;return(se=t.focusNode)==null?void 0:se.call(t,K.id)},onMouseEnter:()=>o==null?void 0:o(K.id),onMouseLeave:()=>o==null?void 0:o(null),onFocus:()=>o==null?void 0:o(K.id),onBlur:()=>o==null?void 0:o(null),children:[e.jsx(En,{trigger:i.isTriggerStep(K.uses)}),e.jsxs("span",{className:"w6w-connection-node-label",children:[e.jsx("strong",{children:K.uses.action}),e.jsx("span",{className:"w6w-muted w6w-small",children:K.id})]})]}):e.jsxs("span",{className:"w6w-connection-app-heading",children:[e.jsx(En,{trigger:i.isTriggerStep(K.uses)}),e.jsxs("span",{className:"w6w-connection-node-label",children:[e.jsx("strong",{children:K.uses.action}),e.jsx("span",{className:"w6w-muted w6w-small",children:K.id})]})]})},K.id))})]}):e.jsx("span",{className:"w6w-muted w6w-small",children:"Not used by any nodes yet."})]},F)}),!Object.keys(t.connections).length&&e.jsx("p",{className:"w6w-muted w6w-small",children:"No workflow connections yet."}),m&&!C&&!v&&e.jsxs(i.Modal,{title:m.ref!==void 0?"Edit connection":"Add connection",titleIcon:X?T(X):void 0,subtitle:X?E(X):void 0,onClose:N,children:[e.jsxs("div",{className:"w6w-modal-body w6w-stack",children:[x&&e.jsx("p",{role:"alert",className:"w6w-field-error",children:x}),p&&e.jsxs("div",{role:"alert",className:"w6w-stack",children:[e.jsxs("p",{className:"w6w-field-error",children:["Couldn’t load credentials: ",p]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:()=>void D(),children:"Retry"})]}),m.ref!==void 0&&!g&&e.jsx("p",{role:"alert",children:"This workflow connection no longer exists."}),e.jsxs("label",{className:"w6w-field",children:[e.jsx("span",{children:"Workflow connection name"}),e.jsx("input",{className:"w6w-input","aria-label":"Workflow connection name",value:m.name,disabled:t.readOnly,onChange:F=>k({...m,name:F.target.value})})]}),e.jsxs("div",{className:"w6w-field",children:[e.jsx("span",{children:g?"Credentials":"Existing connection"}),e.jsx(i.Combobox,{"aria-label":g?"Credentials":"Connection to add",options:te,value:m.connection,placeholder:l?"Loading connections…":"Choose a connection…",disabled:t.readOnly||l||!!p,onChange:F=>{const U=n.find(J=>J.id===F);k({...m,connection:F,name:!m.name&&U?Y(U):m.name})}})]}),e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",disabled:t.readOnly,onClick:()=>A(!0),children:"Create new credentials"}),g&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"w6w-muted w6w-small",children:m.allNodes?`Saving applies these credentials to all ${B.length} ${E(g.app)} nodes.`:`Saving updates credentials for ${ie.length} linked ${ie.length===1?"node":"nodes"}.`}),B.length>0&&e.jsxs("label",{className:"w6w-connection-scope",children:[e.jsx("input",{type:"checkbox",checked:m.allNodes||B.every(F=>F.uses.connectionRef===m.ref),disabled:t.readOnly||B.every(F=>F.uses.connectionRef===m.ref),onChange:F=>k({...m,allNodes:F.target.checked})}),"Use for all ",B.length," ",E(g.app)," ",B.length===1?"node":"nodes"," in this workflow"]}),e.jsxs("div",{className:"w6w-connection-remove",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",disabled:t.readOnly||ie.length>0,onClick:()=>y(!0),children:"Remove from workflow"}),ie.length>0&&e.jsx("p",{className:"w6w-muted w6w-small",children:"Assign another connection to the linked nodes before removing this one."})]})]})]}),e.jsxs("div",{className:"w6w-modal-actions",children:[e.jsx("button",{type:"button",className:"w6w-btn w6w-btn-ghost",onClick:N,children:"Cancel"}),e.jsx("button",{type:"button",className:"w6w-btn",disabled:t.readOnly||l||!!p||!m.name.trim()||!m.connection||!X||m.ref!==void 0&&!g,onClick:Z,children:m.ref!==void 0?"Save changes":"Add to workflow"})]})]}),m&&v&&e.jsx(i.ConfirmModal,{title:"Remove workflow connection",message:`Remove “${m.ref}” from this workflow? The saved credentials will remain available.`,confirmLabel:"Remove",onClose:()=>y(!1),onConfirm:()=>{m.ref&&z({type:"remove",ref:m.ref})?N():y(!1)}}),m&&C&&e.jsx(i.AddConnectionModal,{initialAppId:g==null?void 0:g.app,onClose:()=>A(!1),onCreated:({connectionId:F})=>{A(!1),D().then(U=>{const J=U==null?void 0:U.find(ae=>ae.id===F);J&&k(ae=>ae?{...ae,connection:J.id,name:ae.name||Y(J)}:null)})}})]})}exports.CALL_APP=i.CALL_APP;exports.CONTROL_APP=i.CONTROL_APP;exports.CanvasLayer=i.CanvasLayer;exports.DATA_APP=i.DATA_APP;exports.ExpressionOptionsProvider=i.ExpressionOptionsProvider;exports.INTERNAL_NODES=i.INTERNAL_NODES;exports.Markdown=i.Markdown;exports.RACE_APP=i.RACE_APP;exports.SCHEDULER_APP=i.SCHEDULER_APP;exports.SCRIPT_APP=i.SCRIPT_APP;exports.TRIGGER_APP=i.TRIGGER_APP;exports.WEBHOOK_APP=i.WEBHOOK_APP;exports.asFieldDefs=i.asFieldDefs;exports.centralizeConnections=i.centralizeConnections;exports.coerceDefault=i.coerceDefault;exports.connectionIdFor=i.connectionIdFor;exports.fieldWidget=i.fieldWidget;exports.fieldsToParams=i.fieldsToParams;exports.flowToWorkflow=i.flowToWorkflow;exports.internalNodeDefaults=i.internalNodeDefaults;exports.internalNodeIcon=i.internalNodeIcon;exports.internalNodeLabel=i.internalNodeLabel;exports.internalNodeParams=i.internalNodeParams;exports.isControlApp=i.isControlApp;exports.isInternalApp=i.isInternalApp;exports.isTriggerApp=i.isTriggerApp;exports.isTriggerStep=i.isTriggerStep;exports.seedValues=i.seedValues;exports.workflowToFlow=i.workflowToFlow;exports.MAX_NOTES=Tn;exports.MAX_NOTE_BYTES=An;exports.MAX_SECTIONS=In;exports.WorkflowConnectionsPanel=sr;exports.WorkflowFlowEditor=Oi;exports.applyStepProblemFix=$n;exports.assignMembership=cs;exports.clampCanvas=ds;exports.findLoopProblems=fi;exports.findStateWriteProblems=wi;exports.isDisabledStep=We;exports.isPausedStep=st;exports.pausedStopAt=ps;exports.pruneSectionMembers=ms;exports.renameSectionMember=ls;exports.roundGeometry=as;exports.sectionsContaining=Pn;exports.withCanvasGeometry=Rn;exports.withDisabled=_n;exports.withPaused=Mn;
9
9
  //# sourceMappingURL=flow.cjs.map