@collective-intelligence/extensions-sdk-frontend-react 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
1
  export { type QueryKey, studioAgentRunsGetOptions, studioAgentRunsGetQueryKey, studioAgentRunsListInfiniteOptions, studioAgentRunsListInfiniteQueryKey, studioAgentRunsListOptions, studioAgentRunsListQueryKey, studioViewDataGetItemOptions, studioViewDataGetItemQueryKey, studioViewDataSearchInfiniteOptions, studioViewDataSearchInfiniteQueryKey, studioViewDataSearchMembersInfiniteOptions, studioViewDataSearchMembersInfiniteQueryKey, studioViewDataSearchMembersOptions, studioViewDataSearchMembersQueryKey, studioViewDataSearchOptions, studioViewDataSearchQueryKey, studioViewDataUpdateItemMutation, studioWorkflowRunsGetOptions, studioWorkflowRunsGetQueryKey, studioWorkflowRunsListInfiniteOptions, studioWorkflowRunsListInfiniteQueryKey, studioWorkflowRunsListOptions, studioWorkflowRunsListQueryKey } from "./@tanstack/react-query.gen";
2
2
  export { client, type CreateClientConfig } from "./client.gen";
3
3
  export { type Options, studioAgentRunsGet, studioAgentRunsList, studioViewDataGetItem, studioViewDataSearch, studioViewDataSearchMembers, studioViewDataUpdateItem, studioWorkflowRunsGet, studioWorkflowRunsList } from "./sdk.gen";
4
- export type { ClientOptions, EffectHttpApiErrorBadRequestEncoded, EffectHttpApiErrorForbiddenEncoded, EffectHttpApiErrorInternalServerErrorEncoded, EffectHttpApiErrorNotFoundEncoded, EffectHttpApiErrorUnauthorizedEncoded, EntityFileFieldConflictDiagnosticEncoded, EntityFileFieldDiagnosticEncoded, EntityRelationFieldDiagnosticEncoded, EntityUniqueFieldConflictDiagnosticEncoded, EntityValueDiagnosticEncoded, InvalidIncludePathEncoded, KnowledgePageDepthExceededEncoded, KnowledgeReadLimitExceededEncoded, StudioAgentRunsGetData, StudioAgentRunsGetError, StudioAgentRunsGetErrors, StudioAgentRunsGetResponse, StudioAgentRunsGetResponses, StudioAgentRunsListData, StudioAgentRunsListError, StudioAgentRunsListErrors, StudioAgentRunsListResponse, StudioAgentRunsListResponses, StudioViewDataGetItemData, StudioViewDataGetItemError, StudioViewDataGetItemErrors, StudioViewDataGetItemResponses, StudioViewDataSearchData, StudioViewDataSearchError, StudioViewDataSearchErrors, StudioViewDataSearchMembersData, StudioViewDataSearchMembersError, StudioViewDataSearchMembersErrors, StudioViewDataSearchMembersResponses, StudioViewDataSearchResponses, StudioViewDataUpdateItemData, StudioViewDataUpdateItemError, StudioViewDataUpdateItemErrors, StudioViewDataUpdateItemResponse, StudioViewDataUpdateItemResponses, StudioWorkflowRunsGetData, StudioWorkflowRunsGetError, StudioWorkflowRunsGetErrors, StudioWorkflowRunsGetResponse, StudioWorkflowRunsGetResponses, StudioWorkflowRunsListData, StudioWorkflowRunsListError, StudioWorkflowRunsListErrors, StudioWorkflowRunsListResponse, StudioWorkflowRunsListResponses, Suspend4 } from "./types.gen";
4
+ export type { ClientOptions, EffectHttpApiErrorBadRequestEncoded, EffectHttpApiErrorForbiddenEncoded, EffectHttpApiErrorInternalServerErrorEncoded, EffectHttpApiErrorNotFoundEncoded, EffectHttpApiErrorUnauthorizedEncoded, EntityFileFieldConflictDiagnosticEncoded, EntityFileFieldDiagnosticEncoded, EntityRelationFieldDiagnosticEncoded, EntityRemoteFirstConflictDiagnosticEncoded, EntityRemoteFirstDiagnosticEncoded, EntityRemoteFirstUnavailableDiagnosticEncoded, EntityUniqueFieldConflictDiagnosticEncoded, EntityValueDiagnosticEncoded, InvalidIncludePathEncoded, KnowledgePageDepthExceededEncoded, KnowledgeReadLimitExceededEncoded, StudioAgentRunsGetData, StudioAgentRunsGetError, StudioAgentRunsGetErrors, StudioAgentRunsGetResponse, StudioAgentRunsGetResponses, StudioAgentRunsListData, StudioAgentRunsListError, StudioAgentRunsListErrors, StudioAgentRunsListResponse, StudioAgentRunsListResponses, StudioViewDataGetItemData, StudioViewDataGetItemError, StudioViewDataGetItemErrors, StudioViewDataGetItemResponses, StudioViewDataSearchData, StudioViewDataSearchError, StudioViewDataSearchErrors, StudioViewDataSearchMembersData, StudioViewDataSearchMembersError, StudioViewDataSearchMembersErrors, StudioViewDataSearchMembersResponses, StudioViewDataSearchResponses, StudioViewDataUpdateItemData, StudioViewDataUpdateItemError, StudioViewDataUpdateItemErrors, StudioViewDataUpdateItemResponse, StudioViewDataUpdateItemResponses, StudioWorkflowRunsGetData, StudioWorkflowRunsGetError, StudioWorkflowRunsGetErrors, StudioWorkflowRunsGetResponse, StudioWorkflowRunsGetResponses, StudioWorkflowRunsListData, StudioWorkflowRunsListError, StudioWorkflowRunsListErrors, StudioWorkflowRunsListResponse, StudioWorkflowRunsListResponses, Suspend4 } from "./types.gen";
@@ -2,5 +2,5 @@ import{infiniteQueryOptions as P,queryOptions as x}from"@tanstack/react-query";f
2
2
  `);let Z=y.split(`
3
3
 
4
4
  `);y=Z.pop()??"";for(let Ee of Z){let ke=Ee.split(`
5
- `),L=[],ee;for(let g of ke)if(g.startsWith("data:"))L.push(g.replace(/^data:\s*/,""));else if(g.startsWith("event:"))ee=g.replace(/^event:\s*/,"");else if(g.startsWith("id:"))i=g.replace(/^id:\s*/,"");else if(g.startsWith("retry:")){let re=Number.parseInt(g.replace(/^retry:\s*/,""),10);if(!Number.isNaN(re))O=re}let k,te=!1;if(L.length){let g=L.join(`
6
- `);try{k=JSON.parse(g),te=!0}catch{k=g}}if(te){if(o)await o(k);if(n)k=await n(k)}if(r?.({data:k,event:ee,id:i,retry:O}),L.length)yield k}}}finally{h.removeEventListener("abort",Y),f.releaseLock()}break}catch(b){if(t?.(b),s!==void 0&&p>=s)break;let E=Math.min(O*2**(p-1),a??30000);await w(E)}}}()}}var xe=(e)=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ae=(e)=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Ie=(e)=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},C=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){let a=(e?o:o.map((u)=>encodeURIComponent(u))).join(Ae(n));switch(n){case"label":return`.${a}`;case"matrix":return`;${r}=${a}`;case"simple":return a;default:return`${r}=${a}`}}let d=xe(n),s=o.map((a)=>{if(n==="label"||n==="simple")return e?a:encodeURIComponent(a);return V({allowReserved:e,name:r,value:a})}).join(d);return n==="label"||n==="matrix"?d+s:s},V=({allowReserved:e,name:t,value:r})=>{if(r===void 0||r===null)return"";if(typeof r==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},z=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:d})=>{if(o instanceof Date)return d?o.toISOString():`${r}=${o.toISOString()}`;if(n!=="deepObject"&&!t){let u=[];Object.entries(o).forEach(([c,i])=>{u=[...u,c,e?i:encodeURIComponent(i)]});let S=u.join(",");switch(n){case"form":return`${r}=${S}`;case"label":return`.${S}`;case"matrix":return`;${r}=${S}`;default:return S}}let s=Ie(n),a=Object.entries(o).map(([u,S])=>V({allowReserved:e,name:n==="deepObject"?`${r}[${u}]`:u,value:S})).join(s);return n==="label"||n==="matrix"?s+a:a};var Ve=/\{[^{}]+\}/g,qe=({path:e,url:t})=>{let r=t,n=t.match(Ve);if(n)for(let o of n){let d=!1,s=o.substring(1,o.length-1),a="simple";if(s.endsWith("*"))d=!0,s=s.substring(0,s.length-1);if(s.startsWith("."))s=s.substring(1),a="label";else if(s.startsWith(";"))s=s.substring(1),a="matrix";let u=e[s];if(u===void 0||u===null)continue;if(Array.isArray(u)){r=r.replace(o,C({explode:d,name:s,style:a,value:u}));continue}if(typeof u==="object"){r=r.replace(o,z({explode:d,name:s,style:a,value:u,valueOnly:!0}));continue}if(a==="matrix"){r=r.replace(o,`;${V({name:s,value:u})}`);continue}let S=encodeURIComponent(a==="label"?`.${u}`:u);r=r.replace(o,S)}return r},oe=({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let d=o.startsWith("/")?o:`/${o}`,s=(e??"")+d;if(t)s=qe({path:t,url:s});let a=r?n(r):"";if(a.startsWith("?"))a=a.substring(1);if(a)s+=`?${a}`;return s};function v(e){let t=e.body!==void 0;if(t&&e.bodySerializer){if("serializedBody"in e)return e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null;return e.body!==""?e.body:null}if(t)return e.body;return}var se=async(e,t)=>{let r=typeof t==="function"?await t(e):t;if(!r)return;if(e.scheme==="bearer")return`Bearer ${r}`;if(e.scheme==="basic")return`Basic ${btoa(r)}`;return r};var ie={bodySerializer:(e)=>JSON.stringify(e,(t,r)=>typeof r==="bigint"?r.toString():r)};var ae=({parameters:e={},...t}={})=>(n)=>{let o=[];if(n&&typeof n==="object")for(let d in n){let s=n[d];if(s===void 0||s===null)continue;let a=e[d]||t;if(Array.isArray(s)){let u=C({allowReserved:a.allowReserved,explode:!0,name:d,style:"form",value:s,...a.array});if(u)o.push(u)}else if(typeof s==="object"){let u=z({allowReserved:a.allowReserved,explode:!0,name:d,style:"deepObject",value:s,...a.object});if(u)o.push(u)}else{let u=V({allowReserved:a.allowReserved,name:d,value:s});if(u)o.push(u)}}return o.join("&")},ue=(e)=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(!t)return;if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((r)=>t.startsWith(r)))return"blob";if(t.startsWith("text/"))return"text";return},Te=(e,t)=>{if(!t)return!1;if(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`))return!0;return!1},de=async({security:e,...t})=>{for(let r of e){if(Te(t,r.name))continue;let n=await se(r,t.auth);if(!n)continue;let o=r.name??"Authorization";switch(r.in){case"query":if(!t.query)t.query={};t.query[o]=n;break;case"cookie":t.headers.append("Cookie",`${o}=${n}`);break;case"header":default:t.headers.set(o,n);break}}},B=(e)=>oe({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==="function"?e.querySerializer:ae(e.querySerializer),url:e.url}),F=(e,t)=>{let r={...e,...t};if(r.baseUrl?.endsWith("/"))r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1);return r.headers=G(e.headers,t.headers),r},Le=(e)=>{let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t},G=(...e)=>{let t=new Headers;for(let r of e){if(!r)continue;let n=r instanceof Headers?Le(r):Object.entries(r);for(let[o,d]of n)if(d===null)t.delete(o);else if(Array.isArray(d))for(let s of d)t.append(o,s);else if(d!==void 0)t.set(o,typeof d==="object"?JSON.stringify(d):d)}return t};class W{fns=[];clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);if(this.fns[t])this.fns[t]=null}exists(e){let t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){if(typeof e==="number")return this.fns[e]?e:-1;return this.fns.indexOf(e)}update(e,t){let r=this.getInterceptorIndex(e);if(this.fns[r])return this.fns[r]=t,e;return!1}use(e){return this.fns.push(e),this.fns.length-1}}var pe=()=>({error:new W,request:new W,response:new W}),Ce=ae({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ze={"Content-Type":"application/json"},T=(e={})=>({...ie,headers:ze,parseAs:"auto",querySerializer:Ce,...e});var H=(e={})=>{let t=F(T(),e),r=()=>({...t}),n=(c)=>(t=F(t,c),r()),o=pe(),d=async(c)=>{let i={...t,...c,fetch:c.fetch??t.fetch??globalThis.fetch,headers:G(t.headers,c.headers),serializedBody:void 0};if(i.security)await de({...i,security:i.security});if(i.requestValidator)await i.requestValidator(i);if(i.body!==void 0&&i.bodySerializer)i.serializedBody=i.bodySerializer(i.body);if(i.body===void 0||i.serializedBody==="")i.headers.delete("Content-Type");let w=i,A=B(w);return{opts:w,url:A}},s=async(c)=>{let{opts:i,url:w}=await d(c),A={redirect:"follow",...i,body:v(i)},m=new Request(w,A);for(let l of o.request.fns)if(l)m=await l(m,i);let O=i.fetch,p;try{p=await O(m)}catch(l){let f=l;for(let y of o.error.fns)if(y)f=await y(l,void 0,m,i);if(f=f||{},i.throwOnError)throw f;return i.responseStyle==="data"?void 0:{error:f,request:m,response:void 0}}for(let l of o.response.fns)if(l)p=await l(p,m,i);let h={request:m,response:p};if(p.ok){let l=(i.parseAs==="auto"?ue(p.headers.get("Content-Type")):i.parseAs)??"json";if(p.status===204||p.headers.get("Content-Length")==="0"){let y;switch(l){case"arrayBuffer":case"blob":case"text":y=await p[l]();break;case"formData":y=new FormData;break;case"stream":y=p.body;break;case"json":default:y={};break}return i.responseStyle==="data"?y:{data:y,...h}}let f;switch(l){case"arrayBuffer":case"blob":case"formData":case"text":f=await p[l]();break;case"json":{let y=await p.text();f=y?JSON.parse(y):{};break}case"stream":return i.responseStyle==="data"?p.body:{data:p.body,...h}}if(l==="json"){if(i.responseValidator)await i.responseValidator(f);if(i.responseTransformer)f=await i.responseTransformer(f)}return i.responseStyle==="data"?f:{data:f,...h}}let q=await p.text(),b;try{b=JSON.parse(q)}catch{}let E=b??q,I=E;for(let l of o.error.fns)if(l)I=await l(E,p,m,i);if(I=I||{},i.throwOnError)throw I;return i.responseStyle==="data"?void 0:{error:I,...h}},a=(c)=>(i)=>s({...i,method:c}),u=(c)=>async(i)=>{let{opts:w,url:A}=await d(i);return ne({...w,body:w.body,headers:w.headers,method:c,onRequest:async(m,O)=>{let p=new Request(m,O);for(let h of o.request.fns)if(h)p=await h(p,w);return p},serializedBody:v(w),url:A})};return{buildUrl:(c)=>B({...t,...c}),connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:r,head:a("HEAD"),interceptors:o,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:s,setConfig:n,sse:{connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),head:u("HEAD"),options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),trace:u("TRACE")},trace:a("TRACE")}};var R=H(T());var Q=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/agent-runs",...e}),N=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/agent-runs/{runId}",...e}),U=(e)=>(e.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}/relation-members/search",...e,headers:{"Content-Type":"application/json",...e.headers}}),K=(e)=>(e.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/search",...e,headers:{"Content-Type":"application/json",...e.headers}}),_=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}",...e}),J=(e)=>(e.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}",...e,headers:{"Content-Type":"application/json",...e.headers}}),j=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/workflow-runs",...e}),X=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/workflow-runs/{runId}",...e});var D=(e,t,r,n)=>{let o={_id:e,baseUrl:t?.baseUrl||(t?.client??R).getConfig().baseUrl};if(r)o._infinite=r;if(n)o.tags=n;if(t?.body)o.body=t.body;if(t?.headers)o.headers=t.headers;if(t?.path)o.path=t.path;if(t?.query)o.query=t.query;return[o]},ce=(e)=>D("studioAgentRunsList",e),We=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await Q({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:ce(e)}),M=(e,t)=>{let r={...e[0]};if(t.body)r.body={...e[0].body,...t.body};if(t.headers)r.headers={...e[0].headers,...t.headers};if(t.path)r.path={...e[0].path,...t.path};if(t.query)r.query={...e[0].query,...t.query};return r},le=(e)=>D("studioAgentRunsList",e,!0),Ge=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{query:{page:t}}),{data:s}=await Q({...e,...d,signal:n,throwOnError:!0});return s},queryKey:le(e)}),ye=(e)=>D("studioAgentRunsGet",e),Qe=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await N({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:ye(e)}),fe=(e)=>D("studioViewDataSearchMembers",e),Ue=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await U({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:fe(e)}),Se=(e)=>D("studioViewDataSearchMembers",e,!0),Ke=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{body:{cursor:t}}),{data:s}=await U({...e,...d,signal:n,throwOnError:!0});return s},queryKey:Se(e)}),we=(e)=>D("studioViewDataSearch",e),je=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await K({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:we(e)}),he=(e)=>D("studioViewDataSearch",e,!0),Pe=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{body:{cursor:t}}),{data:s}=await K({...e,...d,signal:n,throwOnError:!0});return s},queryKey:he(e)}),Re=(e)=>D("studioViewDataGetItem",e),Me=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await _({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:Re(e)}),ve=(e)=>({mutationFn:async(r)=>{let{data:n}=await J({...e,...r,throwOnError:!0});return n}}),me=(e)=>D("studioWorkflowRunsList",e),Be=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await j({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:me(e)}),ge=(e)=>D("studioWorkflowRunsList",e,!0),Fe=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{query:{page:t}}),{data:s}=await j({...e,...d,signal:n,throwOnError:!0});return s},queryKey:ge(e)}),De=(e)=>D("studioWorkflowRunsGet",e),He=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await X({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:De(e)});export{R as client,N as studioAgentRunsGet,Qe as studioAgentRunsGetOptions,ye as studioAgentRunsGetQueryKey,Q as studioAgentRunsList,Ge as studioAgentRunsListInfiniteOptions,le as studioAgentRunsListInfiniteQueryKey,We as studioAgentRunsListOptions,ce as studioAgentRunsListQueryKey,_ as studioViewDataGetItem,Me as studioViewDataGetItemOptions,Re as studioViewDataGetItemQueryKey,K as studioViewDataSearch,Pe as studioViewDataSearchInfiniteOptions,he as studioViewDataSearchInfiniteQueryKey,U as studioViewDataSearchMembers,Ke as studioViewDataSearchMembersInfiniteOptions,Se as studioViewDataSearchMembersInfiniteQueryKey,Ue as studioViewDataSearchMembersOptions,fe as studioViewDataSearchMembersQueryKey,je as studioViewDataSearchOptions,we as studioViewDataSearchQueryKey,J as studioViewDataUpdateItem,ve as studioViewDataUpdateItemMutation,X as studioWorkflowRunsGet,He as studioWorkflowRunsGetOptions,De as studioWorkflowRunsGetQueryKey,j as studioWorkflowRunsList,Fe as studioWorkflowRunsListInfiniteOptions,ge as studioWorkflowRunsListInfiniteQueryKey,Be as studioWorkflowRunsListOptions,me as studioWorkflowRunsListQueryKey};
5
+ `),C=[],ee;for(let g of ke)if(g.startsWith("data:"))C.push(g.replace(/^data:\s*/,""));else if(g.startsWith("event:"))ee=g.replace(/^event:\s*/,"");else if(g.startsWith("id:"))i=g.replace(/^id:\s*/,"");else if(g.startsWith("retry:")){let re=Number.parseInt(g.replace(/^retry:\s*/,""),10);if(!Number.isNaN(re))O=re}let k,te=!1;if(C.length){let g=C.join(`
6
+ `);try{k=JSON.parse(g),te=!0}catch{k=g}}if(te){if(o)await o(k);if(n)k=await n(k)}if(r?.({data:k,event:ee,id:i,retry:O}),C.length)yield k}}}finally{h.removeEventListener("abort",Y),f.releaseLock()}break}catch(b){if(t?.(b),s!==void 0&&p>=s)break;let E=Math.min(O*2**(p-1),a??30000);await w(E)}}}()}}var xe=(e)=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Ae=(e)=>{switch(e){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},Ie=(e)=>{switch(e){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},L=({allowReserved:e,explode:t,name:r,style:n,value:o})=>{if(!t){let a=(e?o:o.map((u)=>encodeURIComponent(u))).join(Ae(n));switch(n){case"label":return`.${a}`;case"matrix":return`;${r}=${a}`;case"simple":return a;default:return`${r}=${a}`}}let d=xe(n),s=o.map((a)=>{if(n==="label"||n==="simple")return e?a:encodeURIComponent(a);return V({allowReserved:e,name:r,value:a})}).join(d);return n==="label"||n==="matrix"?d+s:s},V=({allowReserved:e,name:t,value:r})=>{if(r===void 0||r===null)return"";if(typeof r==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${t}=${e?r:encodeURIComponent(r)}`},z=({allowReserved:e,explode:t,name:r,style:n,value:o,valueOnly:d})=>{if(o instanceof Date)return d?o.toISOString():`${r}=${o.toISOString()}`;if(n!=="deepObject"&&!t){let u=[];Object.entries(o).forEach(([c,i])=>{u=[...u,c,e?i:encodeURIComponent(i)]});let S=u.join(",");switch(n){case"form":return`${r}=${S}`;case"label":return`.${S}`;case"matrix":return`;${r}=${S}`;default:return S}}let s=Ie(n),a=Object.entries(o).map(([u,S])=>V({allowReserved:e,name:n==="deepObject"?`${r}[${u}]`:u,value:S})).join(s);return n==="label"||n==="matrix"?s+a:a};var Ve=/\{[^{}]+\}/g,qe=({path:e,url:t})=>{let r=t,n=t.match(Ve);if(n)for(let o of n){let d=!1,s=o.substring(1,o.length-1),a="simple";if(s.endsWith("*"))d=!0,s=s.substring(0,s.length-1);if(s.startsWith("."))s=s.substring(1),a="label";else if(s.startsWith(";"))s=s.substring(1),a="matrix";let u=e[s];if(u===void 0||u===null)continue;if(Array.isArray(u)){r=r.replace(o,L({explode:d,name:s,style:a,value:u}));continue}if(typeof u==="object"){r=r.replace(o,z({explode:d,name:s,style:a,value:u,valueOnly:!0}));continue}if(a==="matrix"){r=r.replace(o,`;${V({name:s,value:u})}`);continue}let S=encodeURIComponent(a==="label"?`.${u}`:u);r=r.replace(o,S)}return r},oe=({baseUrl:e,path:t,query:r,querySerializer:n,url:o})=>{let d=o.startsWith("/")?o:`/${o}`,s=(e??"")+d;if(t)s=qe({path:t,url:s});let a=r?n(r):"";if(a.startsWith("?"))a=a.substring(1);if(a)s+=`?${a}`;return s};function v(e){let t=e.body!==void 0;if(t&&e.bodySerializer){if("serializedBody"in e)return e.serializedBody!==void 0&&e.serializedBody!==""?e.serializedBody:null;return e.body!==""?e.body:null}if(t)return e.body;return}var se=async(e,t)=>{let r=typeof t==="function"?await t(e):t;if(!r)return;if(e.scheme==="bearer")return`Bearer ${r}`;if(e.scheme==="basic")return`Basic ${btoa(r)}`;return r};var ie={bodySerializer:(e)=>JSON.stringify(e,(t,r)=>typeof r==="bigint"?r.toString():r)};var ae=({parameters:e={},...t}={})=>(n)=>{let o=[];if(n&&typeof n==="object")for(let d in n){let s=n[d];if(s===void 0||s===null)continue;let a=e[d]||t;if(Array.isArray(s)){let u=L({allowReserved:a.allowReserved,explode:!0,name:d,style:"form",value:s,...a.array});if(u)o.push(u)}else if(typeof s==="object"){let u=z({allowReserved:a.allowReserved,explode:!0,name:d,style:"deepObject",value:s,...a.object});if(u)o.push(u)}else{let u=V({allowReserved:a.allowReserved,name:d,value:s});if(u)o.push(u)}}return o.join("&")},ue=(e)=>{if(!e)return"stream";let t=e.split(";")[0]?.trim();if(!t)return;if(t.startsWith("application/json")||t.endsWith("+json"))return"json";if(t==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((r)=>t.startsWith(r)))return"blob";if(t.startsWith("text/"))return"text";return},Te=(e,t)=>{if(!t)return!1;if(e.headers.has(t)||e.query?.[t]||e.headers.get("Cookie")?.includes(`${t}=`))return!0;return!1},de=async({security:e,...t})=>{for(let r of e){if(Te(t,r.name))continue;let n=await se(r,t.auth);if(!n)continue;let o=r.name??"Authorization";switch(r.in){case"query":if(!t.query)t.query={};t.query[o]=n;break;case"cookie":t.headers.append("Cookie",`${o}=${n}`);break;case"header":default:t.headers.set(o,n);break}}},B=(e)=>oe({baseUrl:e.baseUrl,path:e.path,query:e.query,querySerializer:typeof e.querySerializer==="function"?e.querySerializer:ae(e.querySerializer),url:e.url}),F=(e,t)=>{let r={...e,...t};if(r.baseUrl?.endsWith("/"))r.baseUrl=r.baseUrl.substring(0,r.baseUrl.length-1);return r.headers=G(e.headers,t.headers),r},Ce=(e)=>{let t=[];return e.forEach((r,n)=>{t.push([n,r])}),t},G=(...e)=>{let t=new Headers;for(let r of e){if(!r)continue;let n=r instanceof Headers?Ce(r):Object.entries(r);for(let[o,d]of n)if(d===null)t.delete(o);else if(Array.isArray(d))for(let s of d)t.append(o,s);else if(d!==void 0)t.set(o,typeof d==="object"?JSON.stringify(d):d)}return t};class W{fns=[];clear(){this.fns=[]}eject(e){let t=this.getInterceptorIndex(e);if(this.fns[t])this.fns[t]=null}exists(e){let t=this.getInterceptorIndex(e);return Boolean(this.fns[t])}getInterceptorIndex(e){if(typeof e==="number")return this.fns[e]?e:-1;return this.fns.indexOf(e)}update(e,t){let r=this.getInterceptorIndex(e);if(this.fns[r])return this.fns[r]=t,e;return!1}use(e){return this.fns.push(e),this.fns.length-1}}var pe=()=>({error:new W,request:new W,response:new W}),Le=ae({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),ze={"Content-Type":"application/json"},T=(e={})=>({...ie,headers:ze,parseAs:"auto",querySerializer:Le,...e});var H=(e={})=>{let t=F(T(),e),r=()=>({...t}),n=(c)=>(t=F(t,c),r()),o=pe(),d=async(c)=>{let i={...t,...c,fetch:c.fetch??t.fetch??globalThis.fetch,headers:G(t.headers,c.headers),serializedBody:void 0};if(i.security)await de({...i,security:i.security});if(i.requestValidator)await i.requestValidator(i);if(i.body!==void 0&&i.bodySerializer)i.serializedBody=i.bodySerializer(i.body);if(i.body===void 0||i.serializedBody==="")i.headers.delete("Content-Type");let w=i,A=B(w);return{opts:w,url:A}},s=async(c)=>{let{opts:i,url:w}=await d(c),A={redirect:"follow",...i,body:v(i)},m=new Request(w,A);for(let l of o.request.fns)if(l)m=await l(m,i);let O=i.fetch,p;try{p=await O(m)}catch(l){let f=l;for(let y of o.error.fns)if(y)f=await y(l,void 0,m,i);if(f=f||{},i.throwOnError)throw f;return i.responseStyle==="data"?void 0:{error:f,request:m,response:void 0}}for(let l of o.response.fns)if(l)p=await l(p,m,i);let h={request:m,response:p};if(p.ok){let l=(i.parseAs==="auto"?ue(p.headers.get("Content-Type")):i.parseAs)??"json";if(p.status===204||p.headers.get("Content-Length")==="0"){let y;switch(l){case"arrayBuffer":case"blob":case"text":y=await p[l]();break;case"formData":y=new FormData;break;case"stream":y=p.body;break;case"json":default:y={};break}return i.responseStyle==="data"?y:{data:y,...h}}let f;switch(l){case"arrayBuffer":case"blob":case"formData":case"text":f=await p[l]();break;case"json":{let y=await p.text();f=y?JSON.parse(y):{};break}case"stream":return i.responseStyle==="data"?p.body:{data:p.body,...h}}if(l==="json"){if(i.responseValidator)await i.responseValidator(f);if(i.responseTransformer)f=await i.responseTransformer(f)}return i.responseStyle==="data"?f:{data:f,...h}}let q=await p.text(),b;try{b=JSON.parse(q)}catch{}let E=b??q,I=E;for(let l of o.error.fns)if(l)I=await l(E,p,m,i);if(I=I||{},i.throwOnError)throw I;return i.responseStyle==="data"?void 0:{error:I,...h}},a=(c)=>(i)=>s({...i,method:c}),u=(c)=>async(i)=>{let{opts:w,url:A}=await d(i);return ne({...w,body:w.body,headers:w.headers,method:c,onRequest:async(m,O)=>{let p=new Request(m,O);for(let h of o.request.fns)if(h)p=await h(p,w);return p},serializedBody:v(w),url:A})};return{buildUrl:(c)=>B({...t,...c}),connect:a("CONNECT"),delete:a("DELETE"),get:a("GET"),getConfig:r,head:a("HEAD"),interceptors:o,options:a("OPTIONS"),patch:a("PATCH"),post:a("POST"),put:a("PUT"),request:s,setConfig:n,sse:{connect:u("CONNECT"),delete:u("DELETE"),get:u("GET"),head:u("HEAD"),options:u("OPTIONS"),patch:u("PATCH"),post:u("POST"),put:u("PUT"),trace:u("TRACE")},trace:a("TRACE")}};var R=H(T());var U=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/agent-runs",...e}),N=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/agent-runs/{runId}",...e}),Q=(e)=>(e.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}/relation-members/search",...e,headers:{"Content-Type":"application/json",...e.headers}}),K=(e)=>(e.client??R).post({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/search",...e,headers:{"Content-Type":"application/json",...e.headers}}),_=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}",...e}),J=(e)=>(e.client??R).patch({security:[{scheme:"bearer",type:"http"}],url:"/studio/apps/by-slug/{slug}/views/{viewId}/data/{instanceId}",...e,headers:{"Content-Type":"application/json",...e.headers}}),j=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/workflow-runs",...e}),X=(e)=>(e.client??R).get({security:[{scheme:"bearer",type:"http"}],url:"/studio/workflow-runs/{runId}",...e});var D=(e,t,r,n)=>{let o={_id:e,baseUrl:t?.baseUrl||(t?.client??R).getConfig().baseUrl};if(r)o._infinite=r;if(n)o.tags=n;if(t?.body)o.body=t.body;if(t?.headers)o.headers=t.headers;if(t?.path)o.path=t.path;if(t?.query)o.query=t.query;return[o]},ce=(e)=>D("studioAgentRunsList",e),We=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await U({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:ce(e)}),M=(e,t)=>{let r={...e[0]};if(t.body)r.body={...e[0].body,...t.body};if(t.headers)r.headers={...e[0].headers,...t.headers};if(t.path)r.path={...e[0].path,...t.path};if(t.query)r.query={...e[0].query,...t.query};return r},le=(e)=>D("studioAgentRunsList",e,!0),Ge=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{query:{page:t}}),{data:s}=await U({...e,...d,signal:n,throwOnError:!0});return s},queryKey:le(e)}),ye=(e)=>D("studioAgentRunsGet",e),Ue=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await N({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:ye(e)}),fe=(e)=>D("studioViewDataSearchMembers",e),Qe=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await Q({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:fe(e)}),Se=(e)=>D("studioViewDataSearchMembers",e,!0),Ke=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{body:{cursor:t}}),{data:s}=await Q({...e,...d,signal:n,throwOnError:!0});return s},queryKey:Se(e)}),we=(e)=>D("studioViewDataSearch",e),je=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await K({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:we(e)}),he=(e)=>D("studioViewDataSearch",e,!0),Pe=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{body:{cursor:t}}),{data:s}=await K({...e,...d,signal:n,throwOnError:!0});return s},queryKey:he(e)}),Re=(e)=>D("studioViewDataGetItem",e),Me=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await _({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:Re(e)}),ve=(e)=>({mutationFn:async(r)=>{let{data:n}=await J({...e,...r,throwOnError:!0});return n}}),me=(e)=>D("studioWorkflowRunsList",e),Be=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await j({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:me(e)}),ge=(e)=>D("studioWorkflowRunsList",e,!0),Fe=(e)=>P({queryFn:async({pageParam:t,queryKey:r,signal:n})=>{let d=M(r,typeof t==="object"?t:{query:{page:t}}),{data:s}=await j({...e,...d,signal:n,throwOnError:!0});return s},queryKey:ge(e)}),De=(e)=>D("studioWorkflowRunsGet",e),He=(e)=>x({queryFn:async({queryKey:t,signal:r})=>{let{data:n}=await X({...e,...t[0],signal:r,throwOnError:!0});return n},queryKey:De(e)});export{R as client,N as studioAgentRunsGet,Ue as studioAgentRunsGetOptions,ye as studioAgentRunsGetQueryKey,U as studioAgentRunsList,Ge as studioAgentRunsListInfiniteOptions,le as studioAgentRunsListInfiniteQueryKey,We as studioAgentRunsListOptions,ce as studioAgentRunsListQueryKey,_ as studioViewDataGetItem,Me as studioViewDataGetItemOptions,Re as studioViewDataGetItemQueryKey,K as studioViewDataSearch,Pe as studioViewDataSearchInfiniteOptions,he as studioViewDataSearchInfiniteQueryKey,Q as studioViewDataSearchMembers,Ke as studioViewDataSearchMembersInfiniteOptions,Se as studioViewDataSearchMembersInfiniteQueryKey,Qe as studioViewDataSearchMembersOptions,fe as studioViewDataSearchMembersQueryKey,je as studioViewDataSearchOptions,we as studioViewDataSearchQueryKey,J as studioViewDataUpdateItem,ve as studioViewDataUpdateItemMutation,X as studioWorkflowRunsGet,He as studioWorkflowRunsGetOptions,De as studioWorkflowRunsGetQueryKey,j as studioWorkflowRunsList,Fe as studioWorkflowRunsListInfiniteOptions,ge as studioWorkflowRunsListInfiniteQueryKey,Be as studioWorkflowRunsListOptions,me as studioWorkflowRunsListQueryKey};
@@ -39,6 +39,26 @@ export type EntityFileFieldConflictDiagnosticEncoded = {
39
39
  field: string;
40
40
  message: string;
41
41
  };
42
+ export type EntityRemoteFirstConflictDiagnosticEncoded = {
43
+ _tag: "EntityRemoteFirstConflictDiagnostic";
44
+ code: "remote_first_conflict";
45
+ message: string;
46
+ };
47
+ export type EntityRemoteFirstDiagnosticEncoded = {
48
+ _tag: "EntityRemoteFirstDiagnostic";
49
+ code: "remote_first_refused" | "remote_first_rejected";
50
+ field?: string;
51
+ fieldType?: string;
52
+ message: string;
53
+ refusal?: string;
54
+ remoteCode?: string;
55
+ };
56
+ export type EntityRemoteFirstUnavailableDiagnosticEncoded = {
57
+ _tag: "EntityRemoteFirstUnavailableDiagnostic";
58
+ code: "remote_first_realigning" | "remote_first_unavailable";
59
+ message: string;
60
+ remoteCode?: string;
61
+ };
42
62
  export type Suspend4 = null | boolean | number | string | Array<Suspend4> | {
43
63
  [key: string]: Suspend4;
44
64
  };
@@ -387,9 +407,9 @@ export type StudioViewDataUpdateItemData = {
387
407
  };
388
408
  export type StudioViewDataUpdateItemErrors = {
389
409
  /**
390
- * EntityValueDiagnostic | EntityFileFieldDiagnostic | EntityRelationFieldDiagnostic | KnowledgeReadLimitExceeded | KnowledgePageDepthExceeded | BadRequest
410
+ * EntityValueDiagnostic | EntityFileFieldDiagnostic | EntityRelationFieldDiagnostic | EntityRemoteFirstDiagnostic | KnowledgeReadLimitExceeded | KnowledgePageDepthExceeded | BadRequest
391
411
  */
392
- 400: EntityValueDiagnosticEncoded | EntityFileFieldDiagnosticEncoded | EntityRelationFieldDiagnosticEncoded | KnowledgeReadLimitExceededEncoded | KnowledgePageDepthExceededEncoded | EffectHttpApiErrorBadRequestEncoded;
412
+ 400: EntityValueDiagnosticEncoded | EntityFileFieldDiagnosticEncoded | EntityRelationFieldDiagnosticEncoded | EntityRemoteFirstDiagnosticEncoded | KnowledgeReadLimitExceededEncoded | KnowledgePageDepthExceededEncoded | EffectHttpApiErrorBadRequestEncoded;
393
413
  /**
394
414
  * Unauthorized
395
415
  */
@@ -403,13 +423,17 @@ export type StudioViewDataUpdateItemErrors = {
403
423
  */
404
424
  404: EffectHttpApiErrorNotFoundEncoded;
405
425
  /**
406
- * EntityUniqueFieldConflictDiagnostic | EntityFileFieldConflictDiagnostic
426
+ * EntityUniqueFieldConflictDiagnostic | EntityFileFieldConflictDiagnostic | EntityRemoteFirstConflictDiagnostic
407
427
  */
408
- 409: EntityUniqueFieldConflictDiagnosticEncoded | EntityFileFieldConflictDiagnosticEncoded;
428
+ 409: EntityUniqueFieldConflictDiagnosticEncoded | EntityFileFieldConflictDiagnosticEncoded | EntityRemoteFirstConflictDiagnosticEncoded;
409
429
  /**
410
430
  * InternalServerError
411
431
  */
412
432
  500: EffectHttpApiErrorInternalServerErrorEncoded;
433
+ /**
434
+ * EntityRemoteFirstUnavailableDiagnostic
435
+ */
436
+ 503: EntityRemoteFirstUnavailableDiagnosticEncoded;
413
437
  };
414
438
  export type StudioViewDataUpdateItemError = StudioViewDataUpdateItemErrors[keyof StudioViewDataUpdateItemErrors];
415
439
  export type StudioViewDataUpdateItemResponses = {
package/dist/workflow.js CHANGED
@@ -1 +1 @@
1
- var zn=Object.defineProperty;var Qn=(o)=>o;function Gn(o,e){this[o]=Qn.bind(null,e)}var Yn=(o,e)=>{for(var t in e)zn(o,t,{get:e[t],enumerable:!0,configurable:!0,set:Gn.bind(e,t)})};var x=(o,e,t)=>()=>{if(o)try{e=o(o=0)}catch(n){t=[n]}if(t)throw t[0];return e};var ve=(o)=>Boolean(o)===o,Zn=(o)=>Object.prototype.toString.call(o)==="[object Function]",D=(o)=>Number(o)===o,W=(o)=>o!==null&&Object(o)===o&&!Zn(o),A=(o)=>{let e=Object.prototype.toString.call(o);if(o===null||e==="[object Boolean]"||e==="[object Number]"||e==="[object String]")return!0;if(Array.isArray(o))return o.every(A);return W(o)&&Object.values(o).every(A)},P=(o)=>A(o)&&W(o)&&!Array.isArray(o),u=(o)=>String(o)===o,Ba=(o)=>o===void 0,La=(o)=>{let e=o;if(u(e))return e;if(ve(e)||D(e))return String(e);return""};var zo,Xn=(o)=>{zo=o},Qo=()=>zo;import{Archive as Yo,ArrowRight as Zo,Award as Xo,Bell as et,Box as Re,Braces as ot,Calculator as tt,Calendar as K,CheckCircle2 as nt,Clock as rt,Code2 as it,Database as ue,Edit as j,ExternalLink as at,Eye as fe,FileText as T,Folder as Ce,FolderInput as st,GitCompareArrows as lt,GitFork as dt,Globe as ct,GoogleIcon as pt,Info as ut,Layers as ft,Link2 as mt,List as We,ListFilter as gt,Mail as pe,MessageSquare as yt,MicrosoftIcon as Ie,NotionIcon as R,Pencil as Ne,Play as bt,Plus as q,RefreshCw as xt,Search as Ae,Send as lo,SendHorizontal as kt,ServerCrash as wt,Settings as ht,ShieldCheck as vt,Table as co,Terminal as Ct,Trash2 as U,TrendingUp as Wt}from"@collective-intelligence/ui-react/icons";import{jsx as I,jsxs as so,Fragment as Go}from"react/jsx-runtime";var m=(o,e,t,n=!1)=>({className:i})=>so("svg",{className:i,viewBox:"0 0 32 32",width:"24",height:"24","aria-hidden":"true",children:[I("svg",{x:"0",y:"1",width:"24",height:"24",viewBox:"0 0 24 24",children:I(o,{})}),e?so(Go,{children:[I("rect",{x:"17",y:"17",width:"15",height:"15",rx:"3",fill:"var(--card)"}),I("svg",{x:"18",y:"18",width:"14",height:"14",viewBox:"0 0 24 24",children:I(e,{})})]}):null,t?so(Go,{children:[I("rect",{x:"21",y:"0",width:"11",height:"11",rx:"2",fill:"var(--card)"}),I("svg",{x:"22",y:"0",width:"10",height:"10",viewBox:"0 0 24 24",children:I(t,{})})]}):null,n?I("svg",{x:"0",y:"22",width:"10",height:"10",viewBox:"0 0 24 24",children:I(et,{})}):null]}),Ft,Fe=(o,e)=>{for(let[t,n]of Object.entries(e))Ft.set(`${o}.${t}`,n)},St=(o)=>Ft.get(o),er,Et=(o)=>o===null?void 0:er.get(o);var Vt=x(()=>{Ft=new Map;Fe("builtin.core.workflows.nodes",{"actions.adapter":lt,"actions.approval":vt,"actions.code-block":it,"actions.http-request":ct,"actions.if":dt,"actions.invoke-workflow":at,"actions.loop":xt,"actions.merge":ft,"actions.persist-artifact":Yo,"actions.prompt":yt,"actions.set-variable":ot,"actions.skill":Xo,"actions.stop-error":wt,"actions.switch":gt,"actions.wait":rt,input:Zo,output:nt,"triggers.entity-created":m(Re,q),"triggers.entity-deleted":m(Re,U),"triggers.entity-updated":m(Re,j),"triggers.mcp-operation":Ct,"triggers.on-demand":bt,"triggers.schedule":K,"triggers.webhook":mt});Fe("builtin.core.datasets.workflows.nodes.actions",{describe:m(ue,ut),"query-aggregate":m(ue,tt),"query-records":m(ue,We),"query-time-series":m(ue,Wt)});Fe("builtin.integrations.notion.workflows.nodes",{"actions.database-list":m(ue,We,R),"actions.database-schema-read":m(co,fe,R),"actions.database-schema-update":m(co,j,R),"actions.page-create":m(T,q,R),"actions.page-delete":m(T,U,R),"actions.page-read":m(T,fe,R),"actions.page-search":m(T,Ae,R),"actions.page-update":m(T,j,R),"triggers.page-created":m(T,q,R,!0),"triggers.page-deleted":m(T,U,R,!0),"triggers.page-updated":m(T,j,R,!0)});for(let[o,e]of[["google-workspace",pt],["microsoft_365",Ie]])Fe(`builtin.integrations.${o}.workflows.nodes.actions`,{"calendar-event-create":m(K,q,e),"calendar-event-delete":m(K,U,e),"calendar-event-query":m(K,Ae,e),"calendar-event-read":m(K,fe,e),"calendar-event-update":m(K,j,e),"calendar-list":m(K,We,e),"drive-file-create":m(T,q,e),"drive-file-delete":m(T,U,e),"drive-file-read":m(T,fe,e),"drive-file-update":m(T,j,e),"drive-folder-create":m(Ce,q,e),"drive-folder-delete":m(Ce,U,e),"drive-folder-list":m(Ce,We,e),"drive-folder-move":m(st,void 0,e),"drive-folder-rename":m(Ce,j,e),"mail-delete":m(pe,U,e),"mail-draft-create":m(Ne,q,e),"mail-draft-send":m(Ne,lo,e),"mail-draft-update":m(Ne,j,e),"mail-query":m(pe,Ae,e),"mail-read":m(pe,fe,e),"mail-send":m(pe,lo,e),"mail-state-update":m(pe,ht,e)});Fe("builtin.integrations.microsoft-365.workflows.nodes",{"actions.email-send":m(kt,void 0,Ie),"triggers.drive-file-created":m(T,q,Ie,!0)});er=new Map(Object.entries({archive:Yo,"arrow-right":Zo,award:Xo,bell:et,box:Re,braces:ot,calculator:tt,calendar:K,"check-circle-2":nt,clock:rt,"code-2":it,database:ue,edit:j,"external-link":at,eye:fe,"file-text":T,folder:Ce,"folder-input":st,"git-compare-arrows":lt,"git-fork":dt,globe:ct,google:pt,info:ut,layers:ft,"link-2":mt,list:We,"list-filter":gt,mail:pe,"message-square":yt,microsoft:Ie,notion:R,pencil:Ne,play:bt,plus:q,"refresh-cw":xt,search:Ae,send:lo,"send-horizontal":kt,"server-crash":wt,settings:ht,"shield-check":vt,table:co,terminal:Ct,"trash-2":U,"trending-up":Wt}))});import{ArrowRight as or,CheckCircle2 as tr,Wrench as nr,Zap as rr}from"@collective-intelligence/ui-react/icons";var je,ir=(o)=>{let e=0;for(let t of o)e=(e*31+(t.codePointAt(0)??0))%4294967296;return je[e%je.length]??je[0]},po=function o(e){if(!u(e))return{icon:Et(e.icon)??St(e.fqn)??o(e.kind).icon,label:o(e.kind).label,tone:e.categoryId?ir(e.categoryId):je[5]};switch(e){case"trigger":case"trigger_node":return{icon:rr,label:"Trigger",tone:"bg-violet-500/12 text-violet-600 dark:text-violet-400"};case"input_node":return{icon:or,label:"Input",tone:"bg-sky-500/12 text-sky-600 dark:text-sky-400"};case"output_node":return{icon:tr,label:"Output",tone:"bg-emerald-500/12 text-emerald-600 dark:text-emerald-400"};default:return{icon:nr,label:"Action",tone:"bg-slate-500/12 text-slate-600 dark:text-slate-400"}}};var uo=x(()=>{Vt();je=["bg-[color-mix(in_oklab,var(--chart-4)_12%,var(--card))] text-sky-600 border-sky-500/30 dark:text-sky-400","bg-[color-mix(in_oklab,var(--chart-5)_12%,var(--card))] text-violet-600 border-violet-500/30 dark:text-violet-400","bg-[color-mix(in_oklab,var(--chart-2)_12%,var(--card))] text-emerald-600 border-emerald-500/30 dark:text-emerald-400","bg-[color-mix(in_oklab,var(--chart-3)_12%,var(--card))] text-amber-600 border-amber-500/30 dark:text-amber-400","bg-[color-mix(in_oklab,var(--chart-1)_12%,var(--card))] text-rose-600 border-rose-500/30 dark:text-rose-400","bg-[color-mix(in_oklab,var(--bg-surface-alt)_55%,var(--card))] text-slate-600 border-slate-500/30 dark:text-slate-400"]});import{AlertTriangle as ar,Plus as sr}from"@collective-intelligence/ui-react/icons";import{Tooltip as lr,TooltipContent as dr,TooltipTrigger as cr}from"@collective-intelligence/ui-react/ui";import{Handle as pr,Position as Tt,useNodeId as ur,useUpdateNodeInternals as fr}from"@xyflow/react";import{useEffect as mr}from"react";import{jsx as w,jsxs as M,Fragment as xr}from"react/jsx-runtime";var gr,Ot=function(e){if(u(e))return e;if(W(e)&&"kind"in e&&"text"in e){let t=e;if(t.kind==="literal"&&u(t.text))return t.text}if(W(e)&&"en"in e){let t=e.en;return u(t)?t:""}return""},yr=({issues:o,title:e})=>{let t=`${o.length} ${o.length===1?"issue":"issues"} on ${e}`;return M(lr,{children:[w(cr,{asChild:!0,children:w("button",{type:"button","aria-label":t,className:"nodrag nopan absolute -right-2 -top-2 z-20 flex size-7 items-center justify-center rounded-full border border-[color-mix(in_oklab,var(--warning)_45%,var(--border))] bg-[color-mix(in_oklab,var(--warning)_16%,var(--card))] text-[color-mix(in_oklab,var(--warning)_80%,var(--foreground))] shadow-sm transition hover:bg-[color-mix(in_oklab,var(--warning)_24%,var(--card))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",onClick:(n)=>{n.stopPropagation()},onPointerDown:(n)=>{n.stopPropagation()},children:w(ar,{"aria-hidden":"true",className:"size-4"})})}),M(dr,{side:"top",sideOffset:6,className:"max-w-72 p-3",children:[w("p",{className:"font-semibold",children:t}),w("ul",{className:"mt-1.5 space-y-1",children:o.map((n)=>w("li",{className:"leading-snug",children:n.message},`${n.code}:${n.message}`))})]})]})},Jt="pointer-events-none whitespace-nowrap rounded-full border border-border bg-card px-1.5 py-0.5 font-mono text-[10px] leading-none text-muted-foreground shadow-xs",Pt=({port:o,side:e,readOnly:t,showTag:n=!0,index:r=0,count:i=1})=>{let a=e==="left"?Tt.Left:Tt.Right,s={top:`${(r+1)/(i+1)*100}%`},l=o.maxConnections===null?"unlimited connections":`maximum ${o.maxConnections??1} connections`,d=[...Array.isArray(o.allowedTemplateKinds)?o.allowedTemplateKinds.filter(u):[],...Array.isArray(o.allowedTemplateFqns)?o.allowedTemplateFqns.filter(u):[]],c=`${o.key} — ${o.direction}, ${l}${d.length?`; accepts ${d.join(", ")}`:""}`;return M(xr,{children:[w(pr,{id:o.key,type:o.direction==="input"?"target":"source",position:a,isConnectable:!t,isConnectableStart:!t,isConnectableEnd:!t,title:c,"aria-label":c,style:s,className:o.direction==="input"?"!h-5 !w-5 !rounded-sm !border-2 !border-background !bg-primary":"!h-5 !w-5 !border-2 !border-background !bg-primary"}),n?w("span",{style:s,className:`absolute z-10 -translate-y-1/2 ${Jt} ${e==="left"?"right-full mr-6":"left-full ml-4"}`,children:o.key}):null]})},br=({signature:o})=>{let e=ur(),t=fr();return mr(()=>{if(e!==null)t(e)},[e,o,t]),null},me=({context:o,accent:e})=>{let t=o.ports.filter((f)=>f.direction==="input"),n=o.ports.filter((f)=>f.direction==="output"),r=new Set(o.chart.connectedOutputPortKeys),i=o.chart.fields??[],a=Ot(o.template.label),s=o.chart.title??a,l=o.chart.subtitle??(s===a?void 0:a),d=o.chart.description??Ot(o.template.description),{icon:c}=o.chart.presentation??po(o.template.kind),b=o.chart.presentation?.tone??gr[e],h=o.diagnostics.filter((f)=>f.severity!=="info");return M("div",{className:"relative w-[262px]",children:[h.length?w(yr,{issues:h,title:s}):null,M("button",{type:"button","aria-label":o.readOnly?`View ${s} details`:`Edit ${s}`,style:{minHeight:(Math.max(t.length,n.length)+1)*28},onClick:(f)=>{if(f.detail===0&&f.target===f.currentTarget)o.chart.onOpenDetails()},onDoubleClick:()=>{o.chart.onOpenDetails()},className:`workflow-node-drag group relative z-10 w-full cursor-pointer rounded-2xl border bg-card p-4 text-left shadow-[0_2px_10px_-4px_rgba(30,29,26,0.12)] transition-[border-color,box-shadow] hover:shadow-[0_8px_24px_-14px_rgba(30,29,26,0.24)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 ${b}`,children:[o.ports.length>0?w(br,{signature:o.ports.map((f)=>`${f.direction}:${f.key}`).join("|")}):null,t.map((f,g)=>w(Pt,{port:f,side:"left",readOnly:o.readOnly,index:g,count:t.length},f.key)),n.map((f,g)=>w(Pt,{port:f,side:"right",readOnly:o.readOnly,showTag:o.readOnly||r.has(f.key),index:g,count:n.length},f.key)),M("div",{className:"flex items-start gap-3",children:[w("div",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl ${b}`,children:w(c,{className:"size-5"})}),M("div",{className:"min-w-0",children:[w("div",{className:"truncate text-sm font-semibold text-foreground",children:s}),u(l)&&l.length>0?w("p",{className:"truncate font-mono text-[11px] text-muted-foreground",children:l}):null]})]}),(()=>{if(u(d)&&d.length>0)return M("div",{className:"mt-3 space-y-2 border-t border-border/70 pt-3",children:[u(d)&&d.length>0?w("p",{className:"line-clamp-2 text-xs leading-snug text-muted-foreground [overflow-wrap:anywhere]",children:d}):null,u(o.chart.summary)&&o.chart.summary.length>0?w("div",{className:"rounded-lg bg-muted/60 px-2.5 py-2",children:w("p",{className:"line-clamp-3 whitespace-pre-line font-mono text-[11px] leading-4 text-muted-foreground [overflow-wrap:anywhere]",children:o.chart.summary})}):null]});return null})(),i.length?w("div",{className:"mt-3 space-y-1.5 border-t border-border/70 pt-3",children:i.slice(0,4).map((f)=>w("div",{className:"truncate rounded-md bg-muted px-2.5 py-1.5 font-mono text-[11px] text-foreground",children:f},f))}):null]}),(()=>{if(!o.readOnly&&n.length)return w("div",{className:"absolute left-full top-0 h-full",children:n.map((f,g)=>r.has(f.key)?null:M("div",{className:"absolute left-0 flex w-max -translate-y-1/2 items-center",style:{top:`${(g+1)/(n.length+1)*100}%`},children:[w("div",{className:"h-px w-4 bg-foreground/40"}),w("span",{className:Jt,children:f.key}),w("div",{className:"h-px w-6 bg-foreground/40"}),r.has(f.key)?null:w("button",{type:"button",className:"flex size-6 shrink-0 items-center justify-center rounded-md border border-border-strong bg-card text-muted-foreground shadow-sm transition hover:border-primary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40","aria-label":`Add after ${s} ${f.key}`,title:`Add after ${f.key}`,onClick:(p)=>{p.stopPropagation(),o.chart.onAddFromPort?.(f)},children:w(sr,{className:"size-3.5"})})]},f.key))});return null})()]})};var fo=x(()=>{uo();gr={emerald:"bg-[color-mix(in_oklab,var(--chart-2)_12%,var(--card))] text-emerald-600 border-emerald-500/30",sky:"bg-[color-mix(in_oklab,var(--chart-4)_12%,var(--card))] text-sky-600 border-sky-500/30",slate:"bg-[color-mix(in_oklab,var(--bg-surface-alt)_55%,var(--card))] text-slate-600 border-slate-500/30",violet:"bg-[color-mix(in_oklab,var(--chart-5)_12%,var(--card))] text-violet-600 border-violet-500/30"}});var N;var mo=x(()=>{N={expression:"Expression",expressionHelp:"Calculates a value from the data available when this step runs.",fixed:"Fixed",fixedHelp:"Uses the saved value as written.",modesHelp:"Fixed uses the saved value as written. Expression calculates a value from the data available when the step runs."}});var kr=(o)=>o.trim().replaceAll(/[^a-zA-Z0-9]+/gu,"_").toUpperCase(),wr=(o)=>{if(typeof o.module==="string")return{exportName:o.exportName,module:o.module};return{exportName:o.exportName,module:o.module.pathname.split("/").pop()??"unknown-module"}},Se=(o)=>{let{declaration:e,phase:t,message:n,cause:r,sourceMap:i}=o,{target:a}=e,s=["FE",t.toUpperCase(),a.packageFqn,a.fqn,a.version,a.role].map(kr).join("-");return{componentFqn:a.fqn,diagnosticId:s,message:n,packageFqn:a.packageFqn,phase:t,role:a.role,source:wr(e.implementation.render),version:a.version,...i===void 0?void 0:{sourceMap:i},...r===void 0?void 0:{cause:String(r instanceof Error?r.message:r)}}};var Dt=()=>{};import{Component as hr,createContext as vr,createElement as Cr,useContext as Wr,useEffect as Fr,useLayoutEffect as Sr,useRef as Er,useState as Vr}from"react";import"react";import{jsx as $e,jsxs as Pr}from"react/jsx-runtime";var Tr=(o)=>Pr("div",{role:"alert","data-diagnostic-id":o.diagnosticId,children:["Hosted extension failed. Diagnostic ID: ",o.diagnosticId]}),Nt,It,At,jt=({diagnostic:o})=>Wr(At)(o),Rt=(o,e)=>{console.error(`Hosted extension ${o.diagnosticId}: ${o.message}`,e)},$t,Or,ge=({componentProps:o,declaration:e,fallback:t=Or,implementationRole:n="render",load:r,onDiagnostic:i})=>{let[a,s]=Vr(null),l=Er({load:r,onDiagnostic:i});Sr(()=>{l.current={load:r,onDiagnostic:i}},[r,i]),Fr(()=>{let b=!0;return(async()=>{try{let f=await l.current.load();if(!b)return;let g=e.implementation[n]??e.implementation.render,p=f[g.exportName];if(p===void 0){let v=Se({declaration:e,message:`Export "${g.exportName}" was not a React component.`,phase:"load"});Rt(v,v),l.current.onDiagnostic?.(v),s({declaration:e,diagnostic:v,implementationRole:n,kind:"failed"});return}s({component:p,declaration:e,implementationRole:n,kind:"ready"})}catch(f){if(!b)return;let g=Se({cause:f,declaration:e,message:"The hosted component could not be loaded.",phase:"load"});Rt(g,f),l.current.onDiagnostic?.(g),s({declaration:e,diagnostic:g,implementationRole:n,kind:"failed"})}})(),()=>{b=!1}},[e,n]);let d=a?.declaration===e&&a.implementationRole===n?a:null;if(d===null)return t;if(d.kind==="failed")return $e(jt,{diagnostic:d.diagnostic});let c={children:Cr(d.component,o),declaration:e,...i===void 0?void 0:{onDiagnostic:i}};return $e($t,{...c})};var qe=x(()=>{Dt();Nt=Symbol.for("@collective-intelligence/extensions-sdk-frontend-react/hosted-extension-failure"),It=globalThis,At=It[Nt]??vr(Tr);It[Nt]=At;$t=class $t extends hr{constructor(o){super(o);this.state={error:null}}static getDerivedStateFromError(o){return{error:o}}componentDidCatch(o,e){let t=Se({cause:o,declaration:this.props.declaration,message:"The hosted component threw while rendering.",phase:"render"});this.props.onDiagnostic?.(t)}render(){if(this.state.error!==null){let o=Se({cause:this.state.error,declaration:this.props.declaration,message:"The hosted component threw while rendering.",phase:"render"});return $e(jt,{diagnostic:o})}return this.props.children}};Or=$e("output",{children:"Loading extension…"})});import{useEffect as Jr,useSyncExternalStore as Dr}from"react";var Y=()=>{let o=ye();return Dr(o.subscribe,o.snapshot,o.snapshot),o},Z=(o,e)=>{Jr(()=>e===void 0?void 0:o.acquireEntry(e),[o,e])};var Ee=x(()=>{Me()});import{infiniteQueryOptions as Rr,queryOptions as Nr}from"@tanstack/react-query";var qt,ws=(o)=>{qt=o},Mt=(o)=>{let{optionsProvider:e,...t}=o;return t},_t=(o)=>["workflow-field-options",Mt(o)],Ht=(o,e)=>{let t=o.optionsProvider??qt;return t===void 0?Promise.resolve({options:[]}):t(Mt(o),e.signal)},Ve=(o)=>Nr({queryFn:async(e)=>await Ht(o,e),queryKey:_t(o)}),hs=(o)=>Rr({getNextPageParam:(e)=>e.nextCursor,initialPageParam:null,queryFn:async({pageParam:e,signal:t})=>await Ht({...o,cursor:e},{signal:t}),queryKey:_t({...o,cursor:null})});var go=()=>{};import{Combobox as Ir,Label as Ar}from"@collective-intelligence/ui-react/ui";import{useQuery as jr}from"@tanstack/react-query";import{jsx as Bt,jsxs as qr}from"react/jsx-runtime";var $r=(o)=>{if(o?.kind==="literal")return o.text;return o?.kind==="translation"?o.default:void 0},Lt=({context:o})=>{let{remoteOptions:e}=o,t={catalogTemplateId:e?.catalogTemplateId??"",dependencies:e?.dependencies??{},limit:50,organizationId:e?.organizationId??""},n=e?.config===void 0?Ve(t):Ve({...t,config:e.config}),r=(()=>{if(e?.optionsProvider===void 0)return n;if(e.config===void 0)return Ve({...t,optionsProvider:e.optionsProvider});return Ve({...t,config:e.config,optionsProvider:e.optionsProvider})})(),i=jr({...r,enabled:Boolean(e)}),a=i.data?.options??o.options,s=$r(o.field.placeholder);return qr("div",{className:"space-y-2",children:[Bt(Ar,{htmlFor:`workflow-field-${o.field.key}`,children:o.field.label.kind==="literal"?o.field.label.text:o.field.label.default}),Bt(Ir,{className:"w-full",disabled:o.readOnly||Boolean(e&&i.isPending),emptyMessage:"No options are available.",id:`workflow-field-${o.field.key}`,modal:!0,onChange:(l)=>o.onValueChange(l),options:a.map((l)=>({label:l.label,value:String(l.value)})),placeholder:s??"Select an option",searchPlaceholder:"Search options...",value:o.value===null||!u(o.value)&&!D(o.value)?"":String(o.value),width:"100%"})]})};var Kt=x(()=>{go()});var X;var yo=x(()=>{X={field:"Field",unavailableConfiguration:(o)=>`${o} has configuration that this Dashboard cannot edit. Its saved configuration is preserved.`,unavailableControl:(o,e)=>`${o} uses an unavailable ${e} control. Its saved value is preserved.`}});import{Alert as Mr,AlertDescription as _r}from"@collective-intelligence/ui-react/ui";import{jsx as _,jsxs as xo,Fragment as Br}from"react/jsx-runtime";var bo=({diagnostics:o})=>_(Br,{children:o.map((e)=>_(Mr,{variant:"destructive",children:_(_r,{children:e.message})},`${e.code}:${e.message}`))}),Hr=(o)=>{if(u(o))return o;if(o!==null&&W(o)&&"text"in o){let{text:e}=o;return u(e)?e:X.field}if(o!==null&&W(o)&&"default"in o){let{default:e}=o;return u(e)?e:X.field}return X.field},ko=({context:o})=>{let e={widget:o.field.widget};if(o.field.fieldFqn!==void 0&&o.field.fieldFqn!==null)e.fqn=o.field.fieldFqn;if(o.field.fieldVersion!==void 0&&o.field.fieldVersion!==null)e.version=o.field.fieldVersion;let t=Y(),n=t.resolveField(e),r=n.kind==="resolved"?n.entry:void 0;Z(t,r);let i=o.mode??(o.readOnly?"read_only":"value"),a={...o,readOnly:i==="read_only"||o.readOnly};if(n.kind==="resolved"&&n.source==="fallback"&&o.field.optionSource?.kind==="remote")return xo("div",{className:"space-y-2",children:[_(Lt,{context:a}),_(bo,{diagnostics:o.diagnostics})]});if(n.kind==="resolved")return xo("div",{className:"space-y-2",children:[_(ge,{componentProps:a,declaration:n.entry.declaration,load:()=>t.loadModule(n.entry.declaration)}),Ut(n.entry).handlesDiagnostics===!0?null:_(bo,{diagnostics:o.diagnostics})]});return xo("div",{className:"space-y-2",children:[_("div",{className:"rounded-lg border border-dashed border-border px-3 py-2 text-sm text-muted-foreground",children:X.unavailableControl(Hr(o.field.label),o.field.fieldFqn??o.field.widget)}),_(bo,{diagnostics:o.diagnostics})]})};var wo=x(()=>{qe();Me();Ee();Kt();yo()});var zt;var Qt=x(()=>{zt={noEditableFields:"This template does not expose editable fields."}});import{jsx as _e,jsxs as Yt}from"react/jsx-runtime";var Lr=function(e){if(u(e))return e;if(W(e)&&!Array.isArray(e)&&"en"in e){let t=e.en;return u(t)?t:""}return""},Gt=function(e){return[...e].sort((t,n)=>(t.order??0)-(n.order??0))},Kr=function(e){return Gt(e).map((t)=>({...t,fields:Gt(t.fields??[])}))},ee=({context:o})=>{let e=Kr("editor"in o.template.contract?o.template.contract.editor?.form?.sections??[]:[]);return Yt("div",{className:"space-y-5",children:[e.length>0?_e("p",{className:"text-xs leading-relaxed text-muted-foreground",children:N.modesHelp}):null,e.map((t)=>Yt("section",{className:"space-y-3 rounded-xl border border-border p-4",children:[_e("h3",{className:"text-sm font-semibold text-foreground",children:Lr(t.label)}),(t.fields??[]).filter((n)=>o.isFieldVisible?.(n)??!0).map((n)=>o.getFieldContext?_e(ko,{context:o.getFieldContext(n)},n.key):null)]},t.key)),e.length?null:_e("p",{className:"rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground",children:zt.noEditableFields})]})};var He=x(()=>{mo();wo();Qt()});var Ur,Zt=(o)=>Ur.has(o),oe=(o)=>P(o)?o:void 0,Le=(o)=>{let e=o.anyOf??o.oneOf;return Array.isArray(e)?e.flatMap((t)=>{let n=oe(t);return n===void 0?[]:Le(n)}):[o]},Xt=(o)=>{if(o===null)return"null";if(Array.isArray(o))return"array";if(P(o))return"object";if(u(o))return"string";if(D(o))return Number.isInteger(o)?"integer":"number";return"boolean"},on=(o)=>{let{type:e}=o;if(u(e))return Zt(e)?new Set([e]):void 0;if(Array.isArray(e))return new Set(e.filter(u).filter(Zt));if(o.const!==void 0)return new Set([Xt(o.const)]);if(Array.isArray(o.enum))return new Set(o.enum.map(Xt));if(o.properties!==void 0)return new Set(["object"]);if(o.items!==void 0)return new Set(["array"]);return},H=(o)=>{let e=new Set;for(let t of Le(o)){let n=on(t);if(n===void 0)return;for(let r of n)e.add(r)}return e},tn=(o)=>{let[e]=o;if(e===void 0)return{};return o.length===1?e:{anyOf:[...o]}},Te=(o,e)=>Le(o).filter((t)=>{let n=on(t);return n===void 0||n.has(e)}),Be=(o)=>tn(Te(o,"array").map((e)=>oe(e.items)??{})),zr=(o,e)=>o.has(e)||e==="integer"&&o.has("number"),Qr=(o,e)=>{let[t]=Te(o,"object"),n=oe(t?.properties);if(n===void 0)return!0;let r=Array.isArray(t?.required)?t.required.filter(u):[];return Te(e,"object").every((i)=>{let a=oe(i.properties);if(a===void 0)return!0;return r.every((s)=>(s in a))&&Object.entries(n).every(([s,l])=>{let d=oe(a[s]),c=oe(l);return d===void 0||c===void 0?!0:te(c,d)})})},te=(o,e)=>{let t=H(o),n=H(e);if(t===void 0||n===void 0)return!0;for(let r of n)if(!zr(t,r))return!1;if(n.has("array")&&!te(Be(o),Be(e)))return!1;return!n.has("object")||Qr(o,e)},Gr=(o)=>tn(Le(o).flatMap((e)=>{let{type:t}=e;if(t==="null")return[];if(Array.isArray(t)){let n=t.filter((r)=>r!=="null");return n.length===0?[]:[{...e,type:n}]}return[e]})),Yr=(o)=>{let e=H(o);if(e?.has("string")===!0)return'""';if(e?.has("number")===!0||e?.has("integer")===!0)return"0";if(e?.has("boolean")===!0)return"false";return},Zr=(o)=>{let e=Te(o,"array").every((n)=>D(n.minItems)&&n.minItems>=1),t=Be(o);return e||H(t)?.has("null")===!0?t:{anyOf:[t,{type:"null"}]}},ho=(o,e)=>{if(e===void 0||H(e)===void 0||H(o)===void 0)return{status:"unknown"};if(te(e,o))return{status:"compatible"};let t=Yr(e),n=(l,d)=>{if(te(e,l))return d;return t!==void 0&&te(e,Gr(l))?[...d,`coalesce(${t})`]:void 0},r=n(o,[]),i=H(o),a=r===void 0&&i?.has("array")===!0?n(Zr(o),["first"]):void 0,s=r??a;return s===void 0||s.length===0?{status:"incompatible"}:{pipes:s.map((l)=>`| ${l}`).join(" "),status:"fixable"}},en=4,Xr=(o)=>{let e=Te(o,"object").flatMap((n)=>Object.keys(oe(n.properties)??{}));if(e.length===0)return"object";return`{${e.slice(0,en).join(", ")}${e.length>en?", …":""}}`},vo=(o)=>{let e=H(o);if(e===void 0)return"any";return["string","integer","number","boolean","object","array","null"].filter((n)=>e.has(n)).map((n)=>{if(n==="array"){let r=Be(o),i=H(r);return`array of ${i?.size===1&&i.has("object")?Xr(r):vo(r)}`}return n}).join(" | ")};var Ke=x(()=>{Ur=new Set(["array","boolean","integer","null","number","object","string"])});var Qs=function(e){let t=e.mode==="fixed"?e.value:null;return{expression:e.mode==="expression"?e.source:"",fixed:t,mode:e.mode}},Gs=function(e){return e.mode==="fixed"?{mode:"fixed",value:e.fixed}:{languageVersion:1,mode:"expression",source:e.expression}},nn=function(e,t){return{availability:t.availability,id:t.id,label:t.label,path:t.path??[],schema:t.schema,sourceId:e}},ei=(o,e)=>o.length===e.length&&o.every((t,n)=>t===e[n]),oi=function(e,t,n){let r=n.path??[];if(r.length===0){e.children.push(nn(t,n));return}let i=e;for(let[a,s]of r.entries()){let l=r.slice(0,a+1),d=i.children.findIndex((h)=>ei(h.path,l)),c=i.children[d];if(a===r.length-1){if(!c)i.children.push(nn(t,n));return}if(c&&"children"in c){i=c;continue}let b=c?{...c,children:[],conditional:c.availability==="conditional",selectors:[]}:{availability:n.availability,children:[],conditional:n.availability==="conditional",id:`${t}:${l.join(".")}`,label:String(s),path:l,schema:{},selectors:[],sourceId:t};if(c)i.children[d]=b;else i.children.push(b);i=b}},ti=function o(e){return e.flatMap((t)=>[t,...o(t.children??[])])},ni=function(e){let t=e.availability??"guaranteed",n={availability:t,children:[],conditional:t==="conditional",id:e.id,label:e.label,path:[],schema:e.schema,selectors:(e.selectors??[]).map((r)=>r.kind),sourceId:e.id};if(e.nodeKey!==void 0&&e.nodeKey!==null)n.nodeKey=e.nodeKey;for(let r of ti(e.fields??[]))oi(n,e.id,r);return n},ri=function(e){return{compatibility:e.targetCompatibility??[],language:e.languageManifest,sources:(e.availableSources??[]).map(ni)}},ii=function(e){return{canonicalSource:e.canonicalSource??null,diagnostics:(e.diagnostics??[]).map((t)=>({actualSchema:t.actualSchema,code:t.code,expectedSchema:t.expectedSchema,message:t.message,remediation:t.remediation,severity:t.severity,span:t.span})),inferredSchema:e.inferredSchema,references:e.references??[]}},Ys=function(e,t){return te(t,e)},rn=function(e,t,n){let r=Math.max(0,Math.min(t,e.length));return{cursor:r+n.length,source:`${e.slice(0,r)}${n}${e.slice(r)}`}};var Ue=x(()=>{Ke()});var ai=function(e){if(e.id==="trigger")return"trigger";if(e.id==="workflow_input")return"input";let[,t]=e.id.split(":port:");return`nodes[${JSON.stringify(e.nodeKey??e.label)}]${t?`.${t}`:""}`},si=function(e){return e.map((t)=>(()=>{if(D(t))return`[${t}]`;if(/^[A-Za-z_$][\w$]*$/u.test(t))return`.${t}`;return`[${JSON.stringify(t)}]`})()).join("")},li=function(e){if(e.id==="trigger")return{id:"trigger",label:"Trigger data"};if(e.id==="workflow_input")return{id:"workflow_input",label:"Workflow input"};return{id:e.id,label:e.label}},di=function o(e){let{source:t}=e;return e.nodes.flatMap((n)=>{let r=`${t.id}:${n.id}`,i=[...e.parentLabels,n.label],a="children"in n?n.children:[],s=`${ai(t)}${si(n.path)}`;return[{conditional:n.availability==="conditional",depth:e.depth,expandable:a.length>0,group:e.group,id:r,insertion:`{{ ${s} }}`,label:`${t.label} · ${i.join(".")}`,name:n.label,parentId:e.parentId,pathLabel:i.join("."),reference:s,schema:n.schema,selectors:t.selectors},...o({depth:e.depth+1,group:e.group,nodes:a,parentId:r,parentLabels:i,source:t})]})},ci=function(e){let t=e.children.length?e.children:[{availability:e.availability,id:e.id,label:"Output",path:[],schema:e.schema,sourceId:e.id}];return di({depth:0,group:li(e),nodes:t,parentId:null,parentLabels:[],source:e})},Co=function(e){return e.sources.flatMap((t)=>ci(t))},ne=function(e){return vo(e)};var ze=x(()=>{Ke()});import{jsx as S,jsxs as sn,Fragment as pi}from"react/jsx-runtime";var O=({title:o,values:e})=>sn("section",{"aria-label":o,children:[S("h3",{className:"font-medium",children:o}),e.length>0?S("ul",{className:"mt-1 list-disc pl-5 font-mono text-xs",children:e.map((t,n)=>S("li",{children:t},`${t}-${n}`))}):S("p",{className:"text-muted-foreground",children:"No entries in this language manifest."})]}),an=function(e){return e.map((t)=>t.example??t.name)},Wo=({manifest:o})=>sn(pi,{children:[S(O,{title:"Syntax overview",values:[o.grammar]}),S(O,{title:"Interpolation",values:[`Whole value preserves type: ${o.interpolation.wholeValuePreservesType}`,`Mixed text returns: ${o.interpolation.mixedTextReturns}`]}),S(O,{title:"References",values:[o.grammar]}),S(O,{title:"Selectors",values:o.selectors.map(({kind:e})=>e)}),S(O,{title:"Unavailable-value policies",values:o.availabilityPolicies}),S(O,{title:"Operators",values:o.operators}),S(O,{title:"Functions",values:an(o.functions)}),S(O,{title:"Casts and pipes",values:o.pipes}),S(O,{title:"Strings",values:o.pipes}),S(O,{title:"Collections",values:o.pipes}),S(O,{title:"Objects",values:o.pipes}),S(O,{title:"Dates",values:o.pipes}),S(O,{title:"If conditions",values:o.ifExamples}),S(O,{title:"Comparators",values:an(o.comparators)})]});var Fo=()=>{};var re;var ln=x(()=>{re={applyPipes:(o)=>`Append ${o}`,expectedType:"Field expects",incompatibleType:"Incompatible type",insertWithPipes:"Insert with the pipes that make this value fit the field",validationFailed:(o)=>`We couldn't validate this expression: ${o}`,validationUnavailable:"We couldn't validate this expression right now. Check its syntax and referenced values, then try again."}});import{ChevronRight as ui}from"@collective-intelligence/ui-react/icons";import{Badge as fi,Button as ae,Input as dn,Popover as mi,PopoverAnchor as gi,PopoverContent as yi,Textarea as bi}from"@collective-intelligence/ui-react/ui";import{Fragment as xi,useEffect as ki,useRef as wi,useState as ie}from"react";import{jsx as k,jsxs as E}from"react/jsx-runtime";var cn=(o)=>o!==null&&W(o)&&!Array.isArray(o),B=(o)=>o!==null&&o!==void 0&&o!=="",hi=function o(e){if(u(e))return e;if(Array.isArray(e)){let t=e.map(o).filter((n)=>B(n));return t.length?t.join("; "):void 0}if(!cn(e))return;if(u(e.msg))return e.msg;if(u(e.message))return e.message;if(u(e.detail))return e.detail;return},vi=function(e){if(e instanceof Error&&B(e.message))return e.message;if(!A(e))return;if(!cn(e))return;return[e.detail,e.body,e.error,e.message].map(hi).find((t)=>B(t))},Ci=function(e){let t=vi(e);return B(t)?re.validationFailed(t):re.validationUnavailable},pn,Wi,un=function(e,t){return Wi.flatMap((n)=>e.filter((r)=>t(r)===n))},Fi=function(e){let t=new Map;for(let i of e){let a=t.get(i.option.parentId)??[];a.push(i),t.set(i.option.parentId,a)}let n=new Map,r=(i)=>{let a=n.get(i.option.id);if(a!==void 0)return a;let s=Math.min(pn[i.compatibility.status],...(t.get(i.option.id)??[]).map(r));return n.set(i.option.id,s),s};for(let[i,a]of t)t.set(i,un(a,r));return t},fn=({entry:o,expanded:e,onInsert:t,onToggle:n})=>{let{compatibility:r,option:i}=o,a=n===void 0,s=r.status==="incompatible";return E("div",{className:"mt-1 flex items-start gap-1",style:{paddingInlineStart:a?0:`${i.depth*1.25}rem`},children:[!a&&i.expandable?k(ae,{"aria-expanded":e,"aria-label":`${e?"Collapse":"Expand"} ${i.label}`,className:"mt-1 size-7 shrink-0",onClick:n,size:"icon",type:"button",variant:"ghost",children:k(ui,{"aria-hidden":!0,className:e?"size-4 rotate-90":"size-4"})}):k("span",{"aria-hidden":!0,className:"size-7 shrink-0"}),E(ae,{"aria-label":`Insert ${i.label}`,className:`block h-auto min-w-0 flex-1 whitespace-normal px-2 py-1.5 text-left ${s?"opacity-60":""}`,onClick:()=>{t(i.insertion)},type:"button",variant:"ghost",children:[k("span",{className:"block text-sm",children:a?i.pathLabel:i.name}),E("span",{className:"flex flex-wrap items-center gap-1.5 font-mono text-xs text-muted-foreground",children:[ne(i.schema),s?k(fi,{className:"font-sans",variant:"outline",children:re.incompatibleType}):null]})]}),r.status==="fixable"?k(ae,{"aria-label":`Insert ${i.label} with ${r.pipes}`,className:"mt-1 h-auto shrink-0 px-1.5 py-0.5 font-mono text-xs",onClick:()=>{t(`{{ ${i.reference} ${r.pipes} }}`)},size:"sm",title:re.insertWithPipes,type:"button",variant:"outline",children:r.pipes}):null]})},mn=({tree:o,expanded:e,onInsert:t,onToggle:n,parentId:r})=>(o.get(r)??[]).map((i)=>{let a=e.has(i.option.id);return E(xi,{children:[k(fn,{entry:i,expanded:a,onInsert:t,onToggle:()=>{n(i.option.id)}}),a?k(mn,{expanded:e,onInsert:t,onToggle:n,parentId:i.option.id,tree:o}):null]},i.option.id)}),Si=({environment:o,onInsert:e,onQueryChange:t,options:n,query:r,targetSchema:i})=>{let[a,s]=ie(new Set),l=new Map(n.map(({group:p})=>[p.id,p])),d=["trigger","workflow_input"],c=[...d.flatMap((p)=>l.get(p)??[]),...[...l.values()].filter(({id:p})=>!d.includes(p))],b=n.map((p)=>({compatibility:ho(p.schema,i),option:p})),h=r.trim()!=="",f=b.filter(({option:p})=>[p.label,p.insertion,ne(p.schema)].join(" ").toLowerCase().includes(r.trim().toLowerCase())),g=(p)=>{s((v)=>{let C=new Set(v);if(C.has(p))C.delete(p);else C.add(p);return C})};return E("div",{className:"grid h-96 max-h-[calc(100dvh-3rem)] grid-cols-[minmax(0,1fr)_14rem] overflow-hidden",children:[E("div",{className:"min-h-0 touch-pan-y overflow-y-auto overscroll-y-contain border-r p-2",onWheel:(p)=>{p.stopPropagation()},children:[k(dn,{"aria-label":"Search expression suggestions",onChange:(p)=>{t(p.target.value)},placeholder:"Search available values",value:r}),c.map((p)=>{let v=(h?f:b).filter(({option:C})=>C.group.id===p.id);if(v.length===0)return null;return E("section",{"aria-label":p.label,className:"mt-3",children:[k("h3",{className:"px-2 text-xs font-semibold text-muted-foreground",children:p.label}),h?un(v,(C)=>pn[C.compatibility.status]).map((C)=>k(fn,{entry:C,expanded:!1,onInsert:e},C.option.id)):k(mn,{expanded:a,onInsert:e,onToggle:g,parentId:null,tree:Fi(v)})]},p.id)}),(h?f:b).length===0?k("p",{className:"p-3 text-sm text-muted-foreground",children:"No matching workflow sources."}):null]}),E("aside",{className:"space-y-3 p-3","aria-label":"Expression helper",children:[i===void 0?null:E("p",{className:"text-xs",children:[E("span",{className:"text-muted-foreground",children:[re.expectedType," "]}),k("span",{className:"font-mono",children:ne(i)})]}),k("p",{className:"text-xs text-muted-foreground",children:"Select a typed source. Expand an object to pick one of its fields, or insert the whole object."}),k("h3",{className:"text-xs font-semibold",children:"Pipes"}),o.language.pipes.map((p)=>E(ae,{className:"mr-1 mb-1 h-auto px-1.5 py-0.5 font-mono text-xs",onClick:()=>{e(` | ${p}`)},size:"sm",type:"button",variant:"outline",children:["| ",p]},p))]})]})},Ei,Vi=function(e,t){let n=Ei.exec(e)?.groups?.body;return n===void 0||n.includes("{{")?void 0:`{{ ${n.trim()} ${t} }}`},Ti=({diagnostic:o,onApplyFix:e,source:t,targetSchema:n})=>{let r=o.expectedSchema??n,i=o.code==="incompatible_expression_type"&&o.actualSchema!==null?ho(o.actualSchema,r??void 0):void 0,a=i?.status==="fixable"?Vi(t,i.pipes):void 0;return E("div",{className:"space-y-1 text-sm text-destructive",role:"alert",children:[E("p",{children:[o.message," (characters ",o.span.start,"–",o.span.end,")"]}),B(o.remediation)?k("p",{className:"text-xs text-muted-foreground",children:o.remediation}):null,i?.status==="fixable"&&a!==void 0&&e!==void 0?k(ae,{className:"h-auto px-1.5 py-0.5 font-mono text-xs",onClick:()=>{e(a)},size:"sm",type:"button",variant:"outline",children:re.applyPipes(i.pipes)}):null]})},So=({describedBy:o,environment:e,inputLabel:t="Expression",source:n,onChange:r,validate:i,multiline:a=!1,readOnly:s=!1,targetSchema:l})=>{let d=wi(null),c=(y)=>{d.current=y},[b,h]=ie(n.length),[f,g]=ie(!1),[p,v]=ie("suggestions"),[C,se]=ie(""),[no,ro]=ie(null),[G,le]=ie(null),we=i===void 0||n===""?null:no,F=i===void 0||n===""?null:G,J=[o,B(F)?"expression-validation":void 0].filter(Boolean).join(" ")||void 0;ki(()=>{let y=new AbortController;if(!i||n==="");else{let io=async()=>{try{let ao=await i(n,y.signal);if(!y.signal.aborted)ro(ao),le(null)}catch(ao){if(!y.signal.aborted)le(Ci(ao))}},ce=window.setTimeout(()=>{io()},300);return()=>{y.abort(),window.clearTimeout(ce)}}return()=>{y.abort()}},[n,i]);let L=Co(e),de=(y)=>{let io=d.current?.selectionStart??b,ce=rn(n,io,y);h(ce.cursor),r(ce.source),queueMicrotask(()=>{d.current?.focus(),d.current?.setSelectionRange(ce.cursor,ce.cursor)})};return E("div",{className:"space-y-2",children:[E(mi,{onOpenChange:(y)=>{if(g(y),!y)se(""),v("suggestions")},open:f,children:[k(gi,{asChild:!0,children:k("div",{children:(()=>{if(a)return k(bi,{"aria-describedby":J,"aria-invalid":B(F)||(we?.diagnostics.length??0)>0,"aria-label":t,className:"min-h-24 text-sm",disabled:s,onChange:(y)=>{r(y.target.value),h(y.currentTarget.selectionStart??n.length)},onFocus:()=>{g(!0)},onKeyDown:(y)=>{if(y.key==="Escape")g(!1)},onSelect:(y)=>{h(y.currentTarget.selectionStart??n.length)},placeholder:"Choose a source or start typing",ref:c,value:n});return k(dn,{"aria-describedby":J,"aria-invalid":B(F)||(we?.diagnostics.length??0)>0,"aria-label":t,className:"text-sm",disabled:s,onChange:(y)=>{r(y.target.value),h(y.currentTarget.selectionStart??n.length)},onFocus:()=>{g(!0)},onKeyDown:(y)=>{if(y.key==="Escape")g(!1)},onSelect:(y)=>{h(y.currentTarget.selectionStart??n.length)},placeholder:"Choose a source or start typing",ref:c,value:n})})()})}),E(yi,{align:"start",className:"w-[min(48rem,calc(100vw-3rem))] p-0",onOpenAutoFocus:(y)=>{y.preventDefault()},children:[E("div",{className:"flex border-b p-1",role:"tablist",children:[k(ae,{"aria-selected":p==="suggestions",onClick:()=>{v("suggestions")},role:"tab",size:"sm",type:"button",variant:p==="suggestions"?"secondary":"ghost",children:"Suggestions"}),k(ae,{"aria-selected":p==="syntax",onClick:()=>{v("syntax")},role:"tab",size:"sm",type:"button",variant:p==="syntax"?"secondary":"ghost",children:"Syntax reference"})]}),p==="suggestions"?k(Si,{environment:e,onInsert:de,onQueryChange:se,options:L,query:C,targetSchema:l}):k("div",{className:"max-h-96 touch-pan-y overflow-y-auto overscroll-y-contain p-4 text-sm",onWheel:(y)=>{y.stopPropagation()},children:k(Wo,{manifest:e.language})})]})]}),B(F)?k("p",{id:"expression-validation",role:"alert",children:F}):null,we?.diagnostics.map((y)=>k(Ti,{diagnostic:y,onApplyFix:s?void 0:r,source:n,targetSchema:l},`${y.code}-${y.span.start}`))]})};var gn=x(()=>{Ue();Ke();ze();Fo();ln();pn={compatible:0,fixable:1,incompatible:3,unknown:2},Wi=[0,1,2,3],Ei=/^\s*\{\{(?<body>[\s\S]*?)\}\}\s*$/u});var Qe=x(()=>{gn();Fo();ze()});import{Alert as Oi,AlertDescription as Pi,Label as Ji,ToggleGroup as Di,ToggleGroupItem as yn}from"@collective-intelligence/ui-react/ui";import{useId as Ri,useState as bn}from"react";import{jsx as V,jsxs as Ge}from"react/jsx-runtime";var Ni,xn=function(e){return e.mode==="expression"?{expression:e.source,fixed:null,mode:"expression"}:{expression:"",fixed:e.value,mode:"fixed"}},Ii=({mode:o})=>V("span",{className:"shrink-0 text-xs text-muted-foreground",title:o==="expression"?N.expressionHelp:N.fixedHelp,children:o==="expression"?N.expression:N.fixed}),Oe=({allowExpression:o=!1,allowFixed:e=!0,controlId:t,diagnostics:n=Ni,expressionEditor:r,expressionMultiline:i=!1,help:a,label:s,onValueChange:l,readOnly:d=!1,renderExpression:c,renderFixed:b,required:h=!1,sensitive:f=!1,value:g})=>{let p=Ri(),[v,C]=bn(()=>xn(g)),se=JSON.stringify(g),[no,ro]=bn(se),G=t===void 0?void 0:`${t}-label`;if(se!==no)ro(se),C(xn(g));let le=(()=>{if(o&&!e)return"expression";if(e&&!o)return"fixed";return v.mode})(),we=d;return Ge("section",{className:"space-y-2",children:[Ge("div",{className:"flex items-center justify-between gap-3",children:[V("div",{className:"min-w-0",children:Ge("div",{className:"flex items-center gap-1",children:[V(Ji,{htmlFor:t,id:G,children:s}),h?V("span",{"aria-label":"Required",children:"*"}):null,f?V("span",{className:"ml-1 text-xs text-muted-foreground",children:"Sensitive"}):null]})}),o&&d?V(Ii,{mode:le}):null,o&&e&&!d?V("div",{"aria-label":`${s} mode controls`,className:"flex shrink-0 items-center gap-1",children:Ge(Di,{"aria-label":`${s} mode`,className:"gap-0",disabled:we,onValueChange:(F)=>{if(F==="fixed"||F==="expression")C((J)=>({...J,mode:F}))},size:"sm",type:"single",value:le,variant:"outline",children:[V(yn,{className:"h-7 px-4 text-xs",title:N.fixedHelp,value:"fixed",children:N.fixed}),V(yn,{className:"h-7 px-4 text-xs",title:N.expressionHelp,value:"expression",children:N.expression})]})}):null]}),a!==void 0&&a!==""?V("p",{id:p,className:"text-xs leading-relaxed text-muted-foreground",children:a}):null,(()=>{if(le==="expression"){if(r?.environment){let L=r.validate===void 0?{}:{validate:r.validate};return V(So,{...a?{describedBy:p}:{},environment:r.environment,multiline:i,onChange:(de)=>{C((y)=>({...y,expression:de})),l({languageVersion:1,mode:"expression",source:de})},readOnly:d,source:v.expression,targetSchema:r.targetSchema,...L})}if(r?.loading===!0)return V("output",{children:"Loading expression editor…"});if(r?.error!==void 0&&r.error!=="")return V("p",{role:"alert",children:r.error});let J={disabled:d,onChange:(L)=>{C((de)=>({...de,expression:L})),l({languageVersion:1,mode:"expression",source:L})},value:v.expression};if(a)J.describedBy=p;if(t!==void 0)J.controlId=`${t}-expression`;if(G!==void 0)J.labelledBy=G;return c?.(J)}let F={disabled:d,onChange:(J)=>{C((L)=>({...L,fixed:J})),l({mode:"fixed",value:J})},value:v.fixed};if(a)F.describedBy=p;if(t!==void 0)F.controlId=t;if(G!==void 0)F.labelledBy=G;return b(F)})(),n.map((F)=>V(Oi,{variant:"destructive",children:V(Pi,{children:F.message})},`${F.code}:${F.message}`))]})};var Eo=x(()=>{Qe();mo();Ni=[]});var Vo=x(()=>{Eo()});var Ye;var kn=x(()=>{Ye={inputBindingsDescription:"Choose the value passed into each workflow input when this trigger starts a run. Fixed uses a saved value; Expression calculates it from the trigger data.",inputBindingsTitle:"Workflow input mapping",noInputs:"This workflow has no declared input fields to map."}});var Pe=function(e){return P(e)?e:{}},To=function(e){return Pe(e)},Ai=function(e,t,n){let r=e.anyOf;if(!Array.isArray(r))return;let i=r.filter((d)=>Pe(d).type!=="null");if(i.length!==1||i.length===r.length)return;let a=To(n(i[0],t)),{type:s}=a,l={...a,...Object.fromEntries(Object.entries(e).filter(([d])=>d!=="anyOf"&&d!=="$defs"))};if(u(s))l.type=[s,"null"];return l},ji=function(e){let t=Pe(e.$defs),n=(r,i=new Set)=>{if(Array.isArray(r))return r.map((c)=>n(c,i));if(!P(r))return r;let a=Pe(r),s=a.$ref,l=u(s)?s:void 0;if(l!==void 0&&l.startsWith("#/$defs/")){let c=l.slice(8),b=t[c];if(b!==void 0&&!i.has(c))return n(b,new Set(i).add(c))}let d=Ai(a,i,n);if(d)return d;return Object.fromEntries(Object.entries(a).filter(([c])=>c!=="$defs").map(([c,b])=>[c,n(b,i)]))};return To(n(e))},$i=function(e){let{type:t}=e;return t==="null"||Array.isArray(t)&&t.includes("null")},qi=function(e){let{type:t}=e;if(u(t))return t==="null"?e:{...e,type:[t,"null"]};if(Array.isArray(t))return t.includes("null")?e:{...e,type:[...t,"null"]};return e},Mi=function o(e,t=[],n=!1){return Object.entries(Pe(e.properties)).map(([r,i])=>{let a=To(i),s=n?qi(a):a,l=[...t,r],d=o(a,l,n||$i(a)),c={availability:"guaranteed",id:`trigger:${l.join(".")}`,label:r,path:l,schema:s,sourceId:"trigger"};return d.length?{...c,children:d,conditional:!1,selectors:[]}:c})},wn=function(e){let{triggerInput:t}=e;if(!t)return;let n=ji(t.schema);return{compatibility:[],language:t.languageManifest,sources:[{availability:"guaranteed",children:Mi(n),conditional:!1,id:"trigger",label:"Trigger data",path:[],schema:n,selectors:[],sourceId:"trigger"}]}};var hn=()=>{};import{Input as _i}from"@collective-intelligence/ui-react/ui";import{jsx as xe,jsxs as vn}from"react/jsx-runtime";var Hi=(o)=>{if(o===null||o===void 0||u(o)||D(o)||ve(o))return String(o??"");return JSON.stringify(o)??""},be=function(e){return P(e)?e:{}},Bi=function(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])},Li=function(e,t){if(t==="number"||t==="integer"){let n=Number(e);return Number.isFinite(n)?n:e}if(t==="boolean")return e==="true";return e},Ki=function(e){if(!P(e))return{mode:"fixed",value:e??null};if(e.mode==="expression"&&u(e.source))return{languageVersion:1,mode:"expression",source:e.source};if(e.mode==="fixed"&&A(e.value))return{mode:"fixed",value:e.value};return{mode:"fixed",value:e}},Cn=({context:o})=>{let e=be(o.workflowContracts?.inputContract.jsonSchema.properties),t=o.trigger?.inputBindings??{},n=wn(o.template.contract);return vn("div",{className:"space-y-5",children:[xe(ee,{context:o}),vn("section",{className:"space-y-2 rounded-xl border border-border p-4",children:[xe("h3",{className:"text-sm font-semibold",children:Ye.inputBindingsTitle}),xe("p",{className:"text-xs text-muted-foreground",children:Ye.inputBindingsDescription}),Object.keys(e).length===0?xe("p",{className:"text-xs text-muted-foreground",children:Ye.noInputs}):null,Object.entries(e).map(([r,i])=>{let a=be(t[r]),s=Ki(a?.value),{description:l}=be(i),d=o.triggerInputExpressionValidator?.(r),c=n===void 0?void 0:{environment:n,targetSchema:be(i)};if(c!==void 0&&d!==void 0)c.validate=d;return xe(Oe,{allowExpression:!0,...c===void 0?{}:{expressionEditor:c},diagnostics:o.diagnostics.filter((b)=>Bi(b.path,["inputBindings",r])),controlId:`workflow-trigger-input-${r}`,...u(l)?{help:l}:{},label:`${r} (${ne(be(i))})`,readOnly:o.readOnly,value:s,onValueChange:(b)=>o.commands.updateTriggerConfiguration?.({inputBindings:{...t,[r]:{overridePolicy:"locked",value:b}}}),renderFixed:({value:b,onChange:h,controlId:f,describedBy:g,disabled:p})=>xe(_i,{"aria-describedby":g,id:f,disabled:p,value:Hi(b),onChange:(v)=>{h(Li(v.target.value,be(i)?.type))}})},r)})]})]})};var Wn=x(()=>{Qe();Vo();He();kn();hn()});var Dn={};Yn(Dn,{renderDefaultActionChart:()=>Fn,renderDefaultActionDetails:()=>Sn,renderDefaultInputChart:()=>Tn,renderDefaultInputDetails:()=>On,renderDefaultOutputChart:()=>Pn,renderDefaultOutputDetails:()=>Jn,renderDefaultTriggerChart:()=>En,renderDefaultTriggerDetails:()=>Vn});import{jsx as z}from"react/jsx-runtime";var Fn=(o)=>z(me,{context:o,accent:"slate"}),Sn=(o)=>z(ee,{context:o}),En=(o)=>z(me,{context:o,accent:"violet"}),Vn=(o)=>z(Cn,{context:o}),Tn=(o)=>z(me,{context:o,accent:"sky"}),On=(o)=>z(ee,{context:o}),Pn=(o)=>z(me,{context:o,accent:"emerald"}),Jn=(o)=>z(ee,{context:o});var Oo=x(()=>{fo();He();Wn()});import{declareFrontendComponent as Ui}from"@collective-intelligence/extensions-sdk-frontend";var Po=(o)=>({exportName:o,load:async()=>await Promise.resolve().then(() => (Oo(),Dn)),module:import.meta.url}),Ze=(o,e,t)=>Ui({implementation:{chart:Po(e),details:Po(t),render:Po(t)},metadata:{kind:o,mode:"default"},target:{fqn:`builtin.core.workflows.nodes.${o.replace(/_node$/u,"")}`,packageFqn:"builtin.core",role:"workflow_template_default",version:"1.0.0"}}),Jo;var Do=x(()=>{Jo=[Ze("action_node","renderDefaultActionChart","renderDefaultActionDetails"),Ze("trigger_node","renderDefaultTriggerChart","renderDefaultTriggerDetails"),Ze("input_node","renderDefaultInputChart","renderDefaultInputDetails"),Ze("output_node","renderDefaultOutputChart","renderDefaultOutputDetails")]});var Rn=async(o,e="render")=>{let t=o.implementation[e]??o.implementation.render;if(t.load===void 0)throw Error(`Workflow contribution "${o.target.fqn}" requires a retained module loader for "${e}".`);return await t.load()};import{WorkflowTemplateKinds as zi}from"@collective-intelligence/extensions-sdk";var Je=(o)=>zi.find((e)=>e===o);var Ro=()=>{};import{createFrontendCatalog as Qi,declareFrontendPackage as Gi}from"@collective-intelligence/extensions-sdk-frontend";var Ao,Xe,jo=(o)=>{let{declaration:{metadata:e}}=o;if(!P(e))return{};let t=u(e.kind)?Je(e.kind):void 0,n;if(u(e.mode)){if(e.mode==="default")n="default";else if(e.mode==="override")n="override"}let r={};if(u(e.fqn))r.fqn=e.fqn;if(ve(e.handlesDiagnostics))r.handlesDiagnostics=e.handlesDiagnostics;if(t!==void 0)r.kind=t;if(n!==void 0)r.mode=n;if(u(e.widget))r.widget=e.widget;return r},eo=(o)=>{let e=o?.trim().toLowerCase();return e===void 0||e===""?void 0:e},Nn=()=>Ao.snapshot().entries,In=(o,e,t)=>{let n=eo(o),r=eo(e);if(n===void 0||r===void 0)return;return Nn().find((i)=>i.target.toLowerCase()===n&&i.version.toLowerCase()===r&&i.role===t)},No=(o,e,t)=>{let n=eo(e);return Nn().find((r)=>{let i=jo(r);return eo(i[o])===n&&r.role===t})},An=(o)=>{Xe=[...Xe.filter((n)=>!o.some((r)=>r.manifest.fqn===n.manifest.fqn)),...o];let t=Ao.activate(Xe);if(t.kind==="invalid")throw Error(t.errors.map((n)=>n.message).join("; "));if(t.kind!=="activated")throw Error(`Workflow catalog activation became stale (${t.reason}).`)},Io,Yi=()=>{if(Xe.some((o)=>o.manifest.fqn===Io.manifest.fqn))return;An([Io])},Zi=()=>Ao.snapshot(),Xi=(o)=>{let e=u(o)?{widget:o}:o,t=e.fqn??void 0,n=e.version??void 0,r=In(t,n,"workflow_field");if(r!==void 0)return{entry:r,kind:"resolved",source:"exact"};if(t!==void 0&&n!==void 0){let s=No("widget",e.widget??"","workflow_field_fallback");if(s!==void 0&&t.toLowerCase().startsWith("builtin."))return{entry:s,kind:"resolved",source:"fallback"};let l={fqn:t,kind:"unavailable"};if(e.widget!==void 0)l.widget=e.widget;return l}let i=No("widget",e.widget??"","workflow_field_fallback");if(i!==void 0)return{entry:i,kind:"resolved",source:"fallback"};let a={kind:"unavailable"};if(e.fqn!==void 0&&e.fqn!==null)a.fqn=e.fqn;if(e.widget!==void 0)a.widget=e.widget;return a},ea=(o)=>{let e=Je(o.kind);if(e===void 0)return{fqn:o.fqn,kind:"unavailable",templateKind:o.kind};let t=In(o.fqn,o.version??"1.0.0","workflow_template_override");if(t!==void 0&&jo(t).kind===e)return{entry:t,kind:"resolved",source:"override"};let n=No("kind",e,"workflow_template_default");if(n!==void 0)return{entry:n,kind:"resolved",source:"default"};return{fqn:o.fqn,kind:"unavailable",templateKind:o.kind}},Ut,jn=()=>{},oa=()=>jn,ta,ye=()=>Qo()??ta,na=()=>ye().snapshot(),ra=(o)=>ye().resolveField(o),ia=(o)=>ye().resolveTemplate(o);var Me=x(()=>{Do();Ro();Ro();Ao=Qi(),Xe=[],Io=Gi({components:Jo,manifest:{fqn:"builtin.core",name:"Dashboard Workflow UI",version:"1.0.0"}}),Ut=jo,ta={acquireEntry:()=>jn,loadModule:Rn,resolveField:Xi,resolveTemplate:ea,snapshot:Zi,subscribe:oa}});Me();Ee();qe();Ee();yo();import{jsx as $n}from"react/jsx-runtime";var aa=({context:o})=>{let e=Y(),t=e.resolveField(o.field),n=t.kind==="resolved"&&t.entry.declaration.implementation.configuration!==void 0?t.entry:void 0;if(Z(e,n),t.kind==="resolved"&&n!==void 0)return $n(ge,{componentProps:o,declaration:t.entry.declaration,implementationRole:"configuration",load:()=>e.loadModule(t.entry.declaration,"configuration")});return $n("div",{className:"rounded-md border border-dashed border-border p-2 text-xs text-muted-foreground",children:X.unavailableConfiguration(o.field.label)})};wo();Ue();Vo();Eo();import{Textarea as sa}from"@collective-intelligence/ui-react/ui";import{jsx as qn}from"react/jsx-runtime";import{createElement as da}from"react";var pd=({help:o,label:e,onValueChange:t,expressionEditor:n,readOnly:r,renderFixed:i,resetKey:a,slotId:s,value:l})=>qn("div",{"data-expression-slot":s,children:da(Oe,{allowExpression:!0,...o===void 0?{}:{help:o},...n===void 0?{}:{expressionEditor:n},key:`${s}:${a??"current"}`,label:e,onValueChange:t,...r===void 0?{}:{readOnly:r},renderExpression:({describedBy:d,disabled:c,onChange:b,value:h})=>qn(sa,{"aria-describedby":d,"aria-label":`${e} expression`,disabled:c,onChange:(f)=>{b(f.target.value)},placeholder:"{{ input.value }}",value:h}),renderFixed:i,value:l})}),la=function(e){if(!P(e))return!1;if(e.mode==="fixed")return A(e.value);return e.mode==="expression"&&D(e.languageVersion)&&e.languageVersion===1&&u(e.source)},ud=function(e){if(la(e))return e;return{mode:"fixed",value:e}};var $o=function(e,t){let n=[...e];for(let r=0;r<n.length;r+=1)for(let i=r+1;i<n.length;i+=1){let a=n[r],s=n[i];if(a!==void 0&&s!==void 0&&t(a,s)>0)n[r]=s,n[i]=a}return n};var _n=function(e){return W(e)&&!Array.isArray(e)},ca=function o(e){return e.flatMap((t)=>[...t.templates??[],...o(t.children??[])])},qo=function(e){return e.kind==="field_collection"&&"collection"in e.contract},Mo=function(e){return`${e.fqn}@${e.version}`},Mn=function(e){return e.kind==="literal"?e.text:e.default},pa=function(e){return e.kind==="field"&&"field"in e.contract},ua=function(e,t){if(!e.enabled||e.state!=="available")return!1;return t==="input"?e.contract.field.availableForInput!==!1:e.contract.field.availableForOutput!==!1},fa=function(e,t){let n=e.find((r)=>qo(r)&&Mo(r.contract.collection)===t);return n&&qo(n)?n.contract.collection.weight??0:0},oo=function(e){return e!==void 0&&_n(e)?e:{}},kd=function(e,t){let n=ca(e?.categories??[]),r=new Map;for(let a of n){if(!qo(a))continue;r.set(Mo(a.contract.collection),Mn(a.label))}let i=new Map;for(let a of n){if(!pa(a)||!ua(a,t))continue;let s=a.contract.field,l=Mo({fqn:s.collectionFqn,version:s.collectionVersion}),d=i.get(l)??{fields:[],key:l,label:r.get(l)??s.collectionFqn,weight:fa(n,l)},c={catalogTemplateId:a.id,collectionKey:l,configSchema:oo(s.configSchema),fqn:s.fqn,label:Mn(a.label),schema:oo(s.valueSchema),version:s.version};if(s.user!==void 0)c.user=s.user;d.fields.push(c),i.set(l,d)}return $o([...i.values()].map((a)=>({...a,fields:$o(a.fields,(s,l)=>s.label.localeCompare(l.label)||s.fqn.localeCompare(l.fqn))})),(a,s)=>a.weight-s.weight||a.label.localeCompare(s.label)||a.key.localeCompare(s.key))},wd=function(e){return{key:e.key,label:e.label,options:e.fields.map((t)=>({fqn:t.fqn,label:t.label,searchTerms:[t.fqn],version:t.version}))}},ma=function(e){let t=oo(e.$defs),n=(r,i=new Set)=>{if(Array.isArray(r))return r.map((d)=>n(d,i));if(r===null||!_n(r))return r;let a=r,s=a.$ref,l=u(s)?s:void 0;if(l!==void 0&&l.startsWith("#/$defs/")){let d=l.slice(8),c=t[d];if(c!==void 0&&c!==null&&!i.has(d))return n(c,new Set(i).add(d))}return Object.fromEntries(Object.entries(a).filter(([d])=>d!=="$defs").map(([d,c])=>[d,n(c,i)]))};return oo(n(e))},hd=function(e,t){let{title:n,...r}=ma(t.schema),i={...r};if(u(e.title))i.title=e.title;return i};import{useDebouncedCallback as ga}from"@collective-intelligence/ui-react/hooks";import{Check as ya,ChevronsUpDown as ba}from"@collective-intelligence/ui-react/icons";import{Button as xa,Command as ka,CommandGroup as wa,CommandInput as ha,CommandItem as va,CommandList as Ca,Popover as Wa,PopoverContent as Fa,PopoverTrigger as Sa}from"@collective-intelligence/ui-react/ui";import{useMemo as Ea,useState as _o}from"react";import{jsx as Q,jsxs as De}from"react/jsx-runtime";var Va=250,Ho=function(e){return`${e.fqn}@${e.version}`},Ta=function(e,t){let n=t.trim().toLocaleLowerCase();if(!n)return e;return e.flatMap((r)=>{let i=r.options.filter((a)=>[a.label,a.fqn,...a.searchTerms??[]].join(" ").toLocaleLowerCase().includes(n));return i.length?[{...r,options:i}]:[]})},Ed=({collections:o,value:e,onChange:t,ariaLabel:n="Field type"})=>{let[r,i]=_o(!1),[a,s]=_o(""),[l,d]=_o(""),c=ga(d,Va),b=o.flatMap((g)=>g.options).find((g)=>Ho(g)===e),h=Ea(()=>Ta(o,l),[o,l]),f=h.some((g)=>g.options.length>0);return De(Wa,{modal:!0,open:r,onOpenChange:(g)=>{if(i(g),!g)c.cancel(),s(""),d("")},children:[Q(Sa,{asChild:!0,children:De(xa,{type:"button",variant:"outline","aria-label":n,"aria-expanded":r,className:"mt-1 w-full justify-between font-normal",children:[Q("span",{className:"truncate",children:b?.label??"Select a field type"}),Q(ba,{className:"ml-2 size-4 shrink-0 opacity-50"})]})}),Q(Fa,{align:"start",className:"w-[var(--radix-popover-trigger-width)] p-0",children:De(ka,{shouldFilter:!1,children:[Q(ha,{placeholder:"Search field types...",value:a,onValueChange:(g)=>{s(g),c(g)}}),De(Ca,{children:[f?null:Q("p",{className:"py-6 text-center text-sm",children:"No field type found."}),h.map((g)=>Q(wa,{heading:g.label,children:g.options.map((p)=>{let v=Ho(p);return De(va,{value:Ho(p),onSelect:()=>{t(p),i(!1)},children:[Q(ya,{className:e===v?"mr-2 size-4 opacity-100":"mr-2 size-4 opacity-0"}),p.label]},v)})},g.key))]})]})})]})};fo();He();Do();Oo();qe();Ee();import{jsx as Hn,jsxs as Pa}from"react/jsx-runtime";var Oa=({context:o})=>{let e=Y(),t=e.resolveTemplate(o.template);if(Z(e,t.kind==="resolved"?t.entry:void 0),t.kind==="resolved")return Hn(ge,{componentProps:o,declaration:t.entry.declaration,implementationRole:"details",load:()=>e.loadModule(t.entry.declaration,"details")});return Pa("div",{className:"rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground",children:["No dashboard editor is available for template kind"," ",Hn("code",{children:t.templateKind}),". The workflow draft has not been changed."]})};uo();var Bo=(o)=>o!==void 0&&o!==null&&W(o)&&!Array.isArray(o),Bn=function(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>n!==t))},Ln=function(e){if(e==="input_binding")return"inputs";if(e==="setting")return"settings";if(e==="metadata")return"metadata";return"config"},ke=function(e){return Bo(e)?e:void 0},Lo=function(e){let t=ke(e);if(t===void 0||!("value"in t))return e;return t.mode==="fixed"||t.kind==="literal"?t.value:e},to=function(e,t){let n=e[Ln(t.target)];for(let r of t.path){let i=ke(Lo(n));if(i===void 0)return;n=i[r]}return Lo(n)},Ja=function(e,t){return to(e,t.binding)},Da=function o(e,t,n){let[r,...i]=t;if(r===void 0)return e??{};let a=e??{};if(!i.length)return{...a,[r]:n};let s=ke(a[r]),l=ke(Lo(s));if(s?.mode==="fixed")return{...a,[r]:{...s,value:o(l,i,n)}};return{...a,[r]:o(l,i,n)}},Ko=function(e,t){return[e==="input_binding"?"inputBinding":e,...t].map((n)=>encodeURIComponent(String(n))).join("/")},Ra=function(e,t,n){let r={...ke(e?.fieldDisplayValues)},i=Ko(t.binding.target,t.binding.path);if(n)r[i]=n;else return{...e,fieldDisplayValues:Bn(r,i)};return{...e,fieldDisplayValues:r}},Na=function(e,t,n,r){let i=Ln(t.binding.target),a={[i]:Da(e[i],t.binding.path,n)};if(r!==void 0)a.metadata=Ra(i==="metadata"?a.metadata:e.metadata,t,r);return a},Kn=function(e,t,n){let r=e.metadata?.fieldDisplayValues;if(r===void 0||r===null||!Bo(r))return;let i=r[Ko(t.binding.target,n)];if(i===void 0||i===null||!Bo(i))return;return u(i.label)&&"value"in i?{label:i.label,value:i.value}:void 0},Ia=function(e,t){return Kn(e,t,t.binding.path)},Aa=function(e,t,n){return Kn(e,t,[...t.binding.path,...n])},ja=function(e,t,n,r){let i={...ke(e?.fieldDisplayValues)},a=Ko(t,n);if(r)i[a]=r;else return{...e,fieldDisplayValues:Bn(i,a)};return{...e,fieldDisplayValues:i}},$a=function(e,t,n,r){return{metadata:ja(e.metadata,t.binding.target,[...t.binding.path,...n],r)}};var Uo=function o(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>o(n,t[r]));if(e!==null&&t!==null&&e!==void 0&&t!==void 0&&W(e)&&W(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((r)=>o(e[r],t[r]))}return e===t},Un=function(e){return e!==void 0&&e!==null&&e!==""},qa=function(e,t){if(!Array.isArray(t)||e===void 0)return!1;return(Array.isArray(e)?e:[e]).some((r)=>t.some((i)=>Uo(r,i)))},Ma=function(e,t){return(e.visibleWhen??[]).every((n)=>{let r=to(t,n.binding);switch(n.operator){case"equals":return Uo(r,n.value);case"not_equals":return!Uo(r,n.value);case"is_set":return Un(r);case"is_not_set":return!Un(r);case"in":return qa(r,n.value);default:return!1}})};var _a=function(e){if(!e)return"";return e.kind==="literal"?e.text:e.default};Ue();Qe();ze();go();export{me as CatalogNodeChartBlock,ee as CatalogNodeDetailsEditor,So as ExpressionEditor,pd as ExpressionSlot,Wo as ExpressionSyntaxReference,Ed as FieldTypeSelect,aa as WorkflowFieldConfigurationResolver,Oe as WorkflowFieldFrame,ko as WorkflowFieldResolver,Oa as WorkflowTemplateDetails,Yi as activateDashboardWorkflowCatalog,An as activateWorkflowCatalog,ud as asExpressionSlotValue,_a as catalogText,ws as configureWorkflowFieldOptionsProvider,Qs as createExpressionDraft,Io as dashboardWorkflowPackage,Jo as defaultWorkflowTemplateDeclarations,Co as expressionSourceOptions,kd as fieldCollectionsFromCatalog,Ho as fieldTypeIdentity,rn as insertExpressionAtCursor,Xn as installWorkflowCatalogHost,ve as isBoolean,Zn as isFunction,A as isJsonValue,D as isNumber,W as isObject,P as isRecord,Ys as isSchemaCompatible,u as isString,Ba as isUndefined,Ma as isWorkflowFieldVisible,ri as normalizeExpressionEnvironment,ii as normalizeExpressionValidation,Je as parseWorkflowTemplateKind,$a as patchWorkflowFieldPartDisplayValue,Na as patchWorkflowFieldValue,to as readWorkflowBindingValue,Ia as readWorkflowFieldDisplayValue,Aa as readWorkflowFieldPartDisplayValue,Ja as readWorkflowFieldValue,Fn as renderDefaultActionChart,Sn as renderDefaultActionDetails,Tn as renderDefaultInputChart,On as renderDefaultInputDetails,Pn as renderDefaultOutputChart,Jn as renderDefaultOutputDetails,En as renderDefaultTriggerChart,Vn as renderDefaultTriggerDetails,ra as resolveWorkflowField,ia as resolveWorkflowTemplate,hd as schemaForWorkflowField,ne as schemaLabel,Gs as serializeExpressionDraft,La as toDisplayString,wd as toFieldTypeCollection,Z as useCatalogEntryLease,Y as useWorkflowCatalogHost,ye as workflowCatalogHost,na as workflowCatalogSnapshot,Ve as workflowFieldOptions,hs as workflowFieldOptionsInfinite,po as workflowNodePresentation};
1
+ var Pn=Object.defineProperty;var On=(o)=>o;function Rn(o,e){this[o]=On.bind(null,e)}var Dn=(o,e)=>{for(var t in e)Pn(o,t,{get:e[t],enumerable:!0,configurable:!0,set:Rn.bind(e,t)})};var b=(o,e,t)=>()=>{if(o)try{e=o(o=0)}catch(n){t=[n]}if(t)throw t[0];return e};var pe=(o)=>Boolean(o)===o,Jn=(o)=>Object.prototype.toString.call(o)==="[object Function]",R=(o)=>Number(o)===o,W=(o)=>o!==null&&Object(o)===o&&!Jn(o),J=(o)=>{let e=Object.prototype.toString.call(o);if(o===null||e==="[object Boolean]"||e==="[object Number]"||e==="[object String]")return!0;if(Array.isArray(o))return o.every(J);return W(o)&&Object.values(o).every(J)},P=(o)=>J(o)&&W(o)&&!Array.isArray(o),p=(o)=>String(o)===o,Pc=(o)=>o===void 0,Oc=(o)=>{let e=o;if(p(e))return e;if(pe(e)||R(e))return String(e);return""};var To,Nn=(o)=>{To=o},Vo=()=>To;import{AppWindow as In,Archive as Po,ArchiveRestore as An,ArchiveX as jn,ArrowRight as Oo,AtSign as qn,AudioLines as Mn,Award as Ro,Bell as $n,BellDot as Bn,BellMinus as Ln,BellPlus as Hn,BellRing as _n,Binoculars as Un,BookMarked as zn,BookOpen as Kn,BookOpenText as Qn,BookPlus as Gn,BookSearch as Xn,BookUser as Yn,BookX as Zn,Box as Do,BoxSelect as er,Braces as Jo,Brain as or,BrainCircuit as tr,BrainCog as nr,Briefcase as rr,BriefcaseBusiness as ir,BriefcaseConveyorBelt as ar,BriefcaseMedical as sr,Building as lr,Building2 as dr,Calculator as cr,Calendar as No,Calendar1 as ur,CalendarCheck as pr,CalendarCheck2 as fr,CalendarClock as mr,CalendarCog as gr,CalendarDays as kr,CalendarFold as br,CalendarPlus as yr,CalendarPlus2 as wr,CalendarRange as hr,CalendarSearch as xr,CalendarX as vr,CalendarX2 as Cr,ChartColumn as Wr,ChartLine as Fr,CheckCircle2 as Io,CirclePause as Sr,CirclePlay as Er,Clipboard as Tr,ClipboardCheck as Vr,ClipboardList as Pr,ClipboardMinus as Or,ClipboardPen as Rr,ClipboardPlus as Dr,ClipboardType as Jr,Clock as Ao,Cloud as Nr,CloudAlert as Ir,CloudBackup as Ar,CloudCheck as jr,CloudCog as qr,CloudOff as Mr,CloudSync as $r,CloudUpload as Br,Code2 as jo,Coins as Lr,Contact as Hr,ContactRound as _r,Crosshair as Ur,Database as qo,Edit as Mo,ExternalLink as $o,Eye as zr,Factory as Kr,FileDown as Qr,FileInput as Gr,FilePen as Xr,FilePenLine as Yr,FilePlus as Zr,FilePlus2 as ei,FileSearch as oi,FileText as Bo,FileType as ti,FileX as ni,FileX2 as ri,Filter as ii,Flag as ai,Folder as si,FolderArchive as li,FolderCog as di,FolderDown as ci,FolderInput as Lo,FolderMinus as ui,FolderOpen as pi,FolderOutput as fi,FolderPen as mi,FolderPlus as gi,FolderTree as ki,FolderX as bi,Forward as yi,Gauge as wi,GaugeCircle as hi,GitBranch as xi,GitCompareArrows as Ho,GitFork as _o,Globe as Uo,GoogleIcon as vi,Handshake as Ci,HardDriveDownload as Wi,Hash as Fi,History as Si,Hourglass as Ei,IdCard as Ti,ImagePlus as Vi,Inbox as Pi,Info as Oi,Landmark as Ri,Layers as zo,LayersPlus as Di,LayoutTemplate as Ji,LetterText as Ni,Library as Ii,LibraryBig as Ai,Link as ji,Link2 as Ko,List as qi,ListChecks as Mi,ListEnd as $i,ListFilter as Qo,ListFilterPlus as Bi,ListOrdered as Li,ListPlus as Hi,ListTodo as _i,ListVideo as Ui,Mail as Go,MailCheck as zi,MailMinus as Ki,MailOpen as Qi,MailPlus as Gi,MailQuestionMark as Xi,MailSearch as Yi,MailWarning as Zi,MailX as ea,Mailbox as oa,Mails as ta,Megaphone as na,MessageCircle as ra,MessageCircleMore as ia,MessageCircleReply as aa,MessageSquare as Xo,MessageSquareDot as sa,MessageSquareMore as la,MessageSquareQuote as da,MessageSquareShare as ca,MessageSquareText as ua,Mic as pa,MicrosoftIcon as fa,Milestone as ma,Network as ga,Newspaper as ka,Notebook as ba,NotebookPen as ya,NotebookTabs as wa,NotebookText as ha,NotepadText as xa,NotionIcon as va,PackageCheck as Ca,PackageOpen as Wa,PackagePlus as Fa,PackageSearch as Sa,PackageX as Ea,PenLine as Ta,PenTool as Va,Pencil as Yo,PencilLine as Pa,Phone as Oa,PhoneForwarded as Ra,PhoneIncoming as Da,PhoneOutgoing as Ja,Play as Zo,PlugZap as Na,Plus as Ia,ReceiptText as Aa,RefreshCw as et,Rss as ja,Scale as qa,ScanSearch as Ma,ScanText as $a,Search as ot,SearchCheck as Ba,Send as tt,SendHorizontal as nt,SendToBack as La,ServerCrash as rt,Settings as Ha,Share2 as _a,ShieldCheck as it,Sigma as Ua,Signpost as za,SkipForward as Ka,SlidersHorizontal as Qa,SlidersVertical as Ga,Smartphone as Xa,SmartphoneNfc as Ya,Sparkles as Za,SquareCheck as es,SquareCheckBig as os,SquarePlus as ts,SquareUser as ns,StickyNote as rs,Store as is,Table as as,Table2 as ss,TableConfig as ls,TableOfContents as ds,TableProperties as cs,Tag as us,Tags as ps,Target as fs,Telescope as ms,Terminal as at,TextQuote as gs,TextSearch as ks,TextSelect as bs,Trash2 as ys,TrendingUp as ws,Unlink as hs,User as xs,UserCheck as vs,UserCircleIcon as Cs,UserCog as Ws,UserMinus as Fs,UserPen as Ss,UserPlus as Es,UserRoundCheck as Ts,UserRoundCog as Vs,UserRoundPen as Ps,UserRoundPlus as Os,UserRoundSearch as Rs,UserSearch as Ds,UserStar as Js,Users as Ns,UsersRound as Is,Warehouse as As,Waypoints as js,Webhook as qs}from"@collective-intelligence/ui-react/icons";var st,v=(o,e)=>{for(let[t,n]of Object.entries(e))st.set(`${o}.${t}`,n)},lt=(o)=>st.get(o),Ms,dt=(o)=>o===null?void 0:Ms.get(o);var ct=b(()=>{st=new Map;v("builtin.core.datasets.workflows.nodes",{"actions.describe":cs,"actions.query-aggregate":Ua,"actions.query-records":qo,"actions.query-time-series":Fr});v("builtin.core.decisions.workflows.nodes",{"actions.decide":qa});v("builtin.core.documents.workflows.nodes",{"connected.create-collection":Br,"connected.delete-collection":Mr,"connected.expand-passage":da,"connected.get-collection":Nr,"connected.get-sync-status":jr,"connected.list-collections":Ai,"connected.read-document-range":bs,"connected.restore-collection":Ar,"connected.search-documents":oi,"connected.search-within-document":Ma,"connected.set-sync-settings":qr,"connected.start-sync":$r,"connected.update-collection":Ir,"connected.wait-sync":Ei,"local.create-collection":Gn,"local.delete-collection":Zn,"local.expand-passage":gs,"local.get-collection":Kn,"local.list-collections":Ii,"local.read-document-range":Qn,"local.restore-collection":An,"local.search-documents":Xn,"local.search-within-document":ks,"local.update-collection":zn});v("builtin.core.external-apps.workflows.nodes",{"actions.operation":Na});v("builtin.core.knowledge.workflows.nodes",{"actions.add-account":Os,"actions.create-entity":or,"actions.list-entities":tr,"actions.save-file":Qr,"actions.update-entity":nr});v("builtin.core.messaging.workflows.nodes",{"actions.send-email":Go,"actions.send-template-email":Ji});v("builtin.core.notifications.workflows.nodes",{"actions.send-notification":_n});v("builtin.core.ocr.workflows.nodes",{"actions.extract-document":$a});v("builtin.core.speech.workflows.nodes",{"actions.synthesize-speech":Mn,"actions.transcribe-audio":pa});v("builtin.core.utilities.workflows.nodes",{"actions.generate-image":Vi,"actions.websearch":ot});v("builtin.core.workflows.nodes",{"actions.adapter":Ho,"actions.approval":it,"actions.code-block":jo,"actions.file-content":Wi,"actions.file-url":ji,"actions.http-request":Uo,"actions.if":_o,"actions.invoke-workflow":$o,"actions.loop":et,"actions.merge":zo,"actions.persist-artifact":Po,"actions.prompt":Xo,"actions.set-variable":Jo,"actions.skill":Ro,"actions.stop-error":rt,"actions.stored-file-link":_a,"actions.switch":Qo,"actions.wait":Ao,input:Oo,output:Io,"triggers.entity-created":Fa,"triggers.entity-deleted":Ea,"triggers.entity-updated":Wa,"triggers.external-application":In,"triggers.mcp-operation":at,"triggers.on-demand":Zo,"triggers.schedule":mr,"triggers.webhook":Ko});v("builtin.integrations.apollo.workflows.nodes",{"actions.activate-sequence":Er,"actions.add-contacts-to-sequence":Hi,"actions.add-list-records":Dr,"actions.archive-sequence":li,"actions.bulk-create-accounts":ir,"actions.bulk-create-contacts":_r,"actions.bulk-create-tasks":_i,"actions.bulk-enrich-organizations":Kr,"actions.bulk-enrich-people":Is,"actions.bulk-update-accounts":ar,"actions.bulk-update-contacts":Yn,"actions.check-outreach-email-send-status":Xi,"actions.check-outreach-email-stats":Wr,"actions.complete-task":os,"actions.convert-person-to-contact":Ps,"actions.create-account":rr,"actions.create-contact":Hr,"actions.create-list":Pr,"actions.create-outreach-email-draft":xa,"actions.create-sequence":Li,"actions.create-task":ts,"actions.deactivate-sequence":Sr,"actions.enrich-organization":lr,"actions.enrich-person":Js,"actions.get-account":Ti,"actions.get-contact":ns,"actions.get-contact-sequence-activity":Si,"actions.get-current-user-profile":Cs,"actions.get-organization":Ri,"actions.get-outreach-email-content":Aa,"actions.get-person":xs,"actions.get-task":es,"actions.list-account-stages":ma,"actions.list-contact-stages":za,"actions.list-email-accounts":qn,"actions.list-email-schedules":gr,"actions.list-lists":Tr,"actions.list-organization-job-postings":ka,"actions.poll-webhook-result":qs,"actions.remove-list-records":Or,"actions.search-accounts":Ba,"actions.search-contacts":Ds,"actions.search-organization-news":ja,"actions.search-organizations":dr,"actions.search-outreach-emails":la,"actions.search-people":Ns,"actions.search-sequences":Ui,"actions.search-tasks":Mi,"actions.send-outreach-email":na,"actions.skip-task":Ka,"actions.start-phone-reveal":Oa,"actions.start-waterfall-email":js,"actions.start-waterfall-phone":Ra,"actions.update-account":sr,"actions.update-account-owner":Ws,"actions.update-contact":Ss,"actions.update-contact-owner":Vs,"actions.update-contact-sequence-status":Ts,"actions.update-contact-stage":ai,"actions.update-list":Rr,"actions.update-sequence":$i,"actions.update-task":Mo,"actions.view-api-usage":wi,"actions.view-credit-usage":Lr});v("builtin.integrations.google-workspace.workflows.nodes",{"actions.calendar-event-create":yr,"actions.calendar-event-delete":vr,"actions.calendar-event-query":xr,"actions.calendar-event-read":kr,"actions.calendar-event-update":pr,"actions.calendar-list":No,"actions.drive-file-create":Zr,"actions.drive-file-delete":ni,"actions.drive-file-read":Bo,"actions.drive-file-update":Xr,"actions.drive-folder-create":gi,"actions.drive-folder-delete":bi,"actions.drive-folder-list":pi,"actions.drive-folder-move":Lo,"actions.drive-folder-rename":mi,"actions.mail-delete":ea,"actions.mail-draft-create":Yo,"actions.mail-draft-send":tt,"actions.mail-draft-update":Ta,"actions.mail-query":Yi,"actions.mail-read":Qi,"actions.mail-send":Gi,"actions.mail-state-update":zi});v("builtin.integrations.hubspot.workflows.nodes",{"actions.add-list-members":Es,"actions.archive-object":jn,"actions.create-association":Ci,"actions.create-list":Di,"actions.create-object":Do,"actions.delete-association":hs,"actions.get-list":Vr,"actions.get-object":er,"actions.list-association-types":ps,"actions.list-associations":ga,"actions.list-owners":vs,"actions.list-pipelines":xi,"actions.list-properties":Qa,"actions.remove-list-members":Fs,"actions.search-lists":Jr,"actions.search-objects":Sa,"actions.update-object":Ca});v("builtin.integrations.lusha.workflows.nodes",{"actions.enrich-companies":is,"actions.enrich-contacts":Za,"actions.get-company-prospecting-filter-values":ii,"actions.get-contact-prospecting-filter-values":us,"actions.list-company-prospecting-filters":Bi,"actions.list-contact-prospecting-filters":Ga,"actions.prospect-companies":fs,"actions.prospect-contacts":Ur,"actions.search-and-enrich-companies":ms,"actions.search-and-enrich-contacts":Un,"actions.search-companies":As,"actions.search-contacts":Rs,"actions.view-account-usage":hi});v("builtin.integrations.microsoft-365.workflows.nodes",{"actions.calendar-event-create":wr,"actions.calendar-event-delete":Cr,"actions.calendar-event-query":hr,"actions.calendar-event-read":ur,"actions.calendar-event-update":fr,"actions.calendar-list":br,"actions.drive-file-create":ei,"actions.drive-file-delete":ri,"actions.drive-file-read":ti,"actions.drive-file-update":Yr,"actions.drive-folder-create":ci,"actions.drive-folder-delete":ui,"actions.drive-folder-list":ki,"actions.drive-folder-move":fi,"actions.drive-folder-rename":di,"actions.email-send":nt,"actions.mail-delete":Ki,"actions.mail-draft-create":Pa,"actions.mail-draft-send":yi,"actions.mail-draft-update":Va,"actions.mail-query":Pi,"actions.mail-read":Ni,"actions.mail-send":ta,"actions.mail-state-update":Zi,"actions.teams-message-send":ca,"triggers.drive-file-created":Gr,"triggers.email-received":oa,"triggers.teams-message-received":sa});v("builtin.integrations.notion.workflows.nodes",{"actions.database-list":ss,"actions.database-schema-read":ds,"actions.database-schema-update":ls,"actions.page-create":rs,"actions.page-delete":ba,"actions.page-read":ha,"actions.page-search":wa,"actions.page-update":ya,"triggers.page-created":Hn,"triggers.page-deleted":Ln,"triggers.page-updated":Bn});v("builtin.integrations.slack.workflows.nodes",{"actions.send-message":Fi,"triggers.message-received":ua});v("builtin.integrations.telegram.workflows.nodes",{"actions.send-message":La,"triggers.message-received":aa});v("builtin.integrations.twilio.workflows.nodes",{"actions.send-sms":Xa,"actions.send-whatsapp-message":Ja,"triggers.sms-received":Ya,"triggers.whatsapp-message-received":Da});v("builtin.integrations.whatsapp.workflows.nodes",{"actions.send-message":ra,"triggers.message-received":ia});Ms=new Map(Object.entries({archive:Po,"arrow-right":Oo,award:Ro,bell:$n,box:Do,braces:Jo,calculator:cr,calendar:No,"check-circle-2":Io,clock:Ao,"code-2":jo,database:qo,edit:Mo,"external-link":$o,eye:zr,"file-text":Bo,folder:si,"folder-input":Lo,"git-compare-arrows":Ho,"git-fork":_o,globe:Uo,google:vi,info:Oi,layers:zo,"link-2":Ko,list:qi,"list-filter":Qo,mail:Go,"message-square":Xo,microsoft:fa,notion:va,pencil:Yo,play:Zo,plus:Ia,"refresh-cw":et,search:ot,send:tt,"send-horizontal":nt,"server-crash":rt,settings:Ha,"shield-check":it,table:as,terminal:at,"trash-2":ys,"trending-up":ws}))});import{ArrowRight as $s,CheckCircle2 as Bs,Wrench as Ls,Zap as Hs}from"@collective-intelligence/ui-react/icons";var xe,_s=(o)=>{let e=0;for(let t of o)e=(e*31+(t.codePointAt(0)??0))%4294967296;return xe[e%xe.length]??xe[0]},He=function o(e){if(!p(e))return{icon:dt(e.icon)??lt(e.fqn)??o(e.kind).icon,label:o(e.kind).label,tone:e.categoryId?_s(e.categoryId):xe[5]};switch(e){case"trigger":case"trigger_node":return{icon:Hs,label:"Trigger",tone:"bg-violet-500/12 text-violet-600 dark:text-violet-400"};case"input_node":return{icon:$s,label:"Input",tone:"bg-sky-500/12 text-sky-600 dark:text-sky-400"};case"output_node":return{icon:Bs,label:"Output",tone:"bg-emerald-500/12 text-emerald-600 dark:text-emerald-400"};default:return{icon:Ls,label:"Action",tone:"bg-slate-500/12 text-slate-600 dark:text-slate-400"}}};var _e=b(()=>{ct();xe=["bg-[color-mix(in_oklab,var(--chart-4)_12%,var(--card))] text-sky-600 border-sky-500/30 dark:text-sky-400","bg-[color-mix(in_oklab,var(--chart-5)_12%,var(--card))] text-violet-600 border-violet-500/30 dark:text-violet-400","bg-[color-mix(in_oklab,var(--chart-2)_12%,var(--card))] text-emerald-600 border-emerald-500/30 dark:text-emerald-400","bg-[color-mix(in_oklab,var(--chart-3)_12%,var(--card))] text-amber-600 border-amber-500/30 dark:text-amber-400","bg-[color-mix(in_oklab,var(--chart-1)_12%,var(--card))] text-rose-600 border-rose-500/30 dark:text-rose-400","bg-[color-mix(in_oklab,var(--bg-surface-alt)_55%,var(--card))] text-slate-600 border-slate-500/30 dark:text-slate-400"]});import{AlertTriangle as Us,Plus as zs}from"@collective-intelligence/ui-react/icons";import{Tooltip as Ks,TooltipContent as Qs,TooltipTrigger as Gs}from"@collective-intelligence/ui-react/ui";import{Handle as Xs,Position as ut,useNodeId as Ys,useUpdateNodeInternals as Zs}from"@xyflow/react";import{useEffect as el}from"react";import{jsx as w,jsxs as N,Fragment as rl}from"react/jsx-runtime";var ol,pt=function(e){if(p(e))return e;if(W(e)&&"kind"in e&&"text"in e){let t=e;if(t.kind==="literal"&&p(t.text))return t.text}if(W(e)&&"en"in e){let t=e.en;return p(t)?t:""}return""},tl=({issues:o,title:e})=>{let t=`${o.length} ${o.length===1?"issue":"issues"} on ${e}`;return N(Ks,{children:[w(Gs,{asChild:!0,children:w("button",{type:"button","aria-label":t,className:"nodrag nopan absolute -right-2 -top-2 z-20 flex size-7 items-center justify-center rounded-full border border-[color-mix(in_oklab,var(--warning)_45%,var(--border))] bg-[color-mix(in_oklab,var(--warning)_16%,var(--card))] text-[color-mix(in_oklab,var(--warning)_80%,var(--foreground))] shadow-sm transition hover:bg-[color-mix(in_oklab,var(--warning)_24%,var(--card))] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40",onClick:(n)=>{n.stopPropagation()},onPointerDown:(n)=>{n.stopPropagation()},children:w(Us,{"aria-hidden":"true",className:"size-4"})})}),N(Qs,{side:"top",sideOffset:6,className:"max-w-72 p-3",children:[w("p",{className:"font-semibold",children:t}),w("ul",{className:"mt-1.5 space-y-1",children:o.map((n)=>w("li",{className:"leading-snug",children:n.message},`${n.code}:${n.message}`))})]})]})},mt="pointer-events-none whitespace-nowrap rounded-full border border-border bg-card px-1.5 py-0.5 font-mono text-[10px] leading-none text-muted-foreground shadow-xs",ft=({port:o,side:e,readOnly:t,showTag:n=!0,index:r=0,count:i=1})=>{let a=e==="left"?ut.Left:ut.Right,s={top:`${(r+1)/(i+1)*100}%`},l=o.maxConnections===null?"unlimited connections":`maximum ${o.maxConnections??1} connections`,d=[...Array.isArray(o.allowedTemplateKinds)?o.allowedTemplateKinds.filter(p):[],...Array.isArray(o.allowedTemplateFqns)?o.allowedTemplateFqns.filter(p):[]],c=`${o.key} — ${o.direction}, ${l}${d.length?`; accepts ${d.join(", ")}`:""}`;return N(rl,{children:[w(Xs,{id:o.key,type:o.direction==="input"?"target":"source",position:a,isConnectable:!t,isConnectableStart:!t,isConnectableEnd:!t,title:c,"aria-label":c,style:s,className:o.direction==="input"?"!h-5 !w-5 !rounded-sm !border-2 !border-background !bg-primary":"!h-5 !w-5 !border-2 !border-background !bg-primary"}),n?w("span",{style:s,className:`absolute z-10 -translate-y-1/2 ${mt} ${e==="left"?"right-full mr-6":"left-full ml-4"}`,children:o.key}):null]})},nl=({signature:o})=>{let e=Ys(),t=Zs();return el(()=>{if(e!==null)t(e)},[e,o,t]),null},re=({context:o,accent:e})=>{let t=o.ports.filter((f)=>f.direction==="input"),n=o.ports.filter((f)=>f.direction==="output"),r=new Set(o.chart.connectedOutputPortKeys),i=o.chart.fields??[],a=pt(o.template.label),s=o.chart.title??a,l=o.chart.subtitle??(s===a?void 0:a),d=o.chart.description??pt(o.template.description),{icon:c}=o.chart.presentation??He(o.template.kind),k=o.chart.presentation?.tone??ol[e],h=o.diagnostics.filter((f)=>f.severity!=="info");return N("div",{className:"relative w-[262px]",children:[h.length?w(tl,{issues:h,title:s}):null,N("button",{type:"button","aria-label":o.readOnly?`View ${s} details`:`Edit ${s}`,style:{minHeight:(Math.max(t.length,n.length)+1)*28},onClick:(f)=>{if(f.detail===0&&f.target===f.currentTarget)o.chart.onOpenDetails()},onDoubleClick:()=>{o.chart.onOpenDetails()},className:`workflow-node-drag group relative z-10 w-full cursor-pointer rounded-2xl border bg-card p-4 text-left shadow-[0_2px_10px_-4px_rgba(30,29,26,0.12)] transition-[border-color,box-shadow] hover:shadow-[0_8px_24px_-14px_rgba(30,29,26,0.24)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40 ${k}`,children:[o.ports.length>0?w(nl,{signature:o.ports.map((f)=>`${f.direction}:${f.key}`).join("|")}):null,t.map((f,m)=>w(ft,{port:f,side:"left",readOnly:o.readOnly,index:m,count:t.length},f.key)),n.map((f,m)=>w(ft,{port:f,side:"right",readOnly:o.readOnly,showTag:o.readOnly||r.has(f.key),index:m,count:n.length},f.key)),N("div",{className:"flex items-start gap-3",children:[w("div",{className:`flex size-10 shrink-0 items-center justify-center rounded-xl ${k}`,children:w(c,{className:"size-5"})}),N("div",{className:"min-w-0",children:[w("div",{className:"truncate text-sm font-semibold text-foreground",children:s}),p(l)&&l.length>0?w("p",{className:"truncate font-mono text-[11px] text-muted-foreground",children:l}):null]})]}),(()=>{if(p(d)&&d.length>0)return N("div",{className:"mt-3 space-y-2 border-t border-border/70 pt-3",children:[p(d)&&d.length>0?w("p",{className:"line-clamp-2 text-xs leading-snug text-muted-foreground [overflow-wrap:anywhere]",children:d}):null,p(o.chart.summary)&&o.chart.summary.length>0?w("div",{className:"rounded-lg bg-muted/60 px-2.5 py-2",children:w("p",{className:"line-clamp-3 whitespace-pre-line font-mono text-[11px] leading-4 text-muted-foreground [overflow-wrap:anywhere]",children:o.chart.summary})}):null]});return null})(),i.length?w("div",{className:"mt-3 space-y-1.5 border-t border-border/70 pt-3",children:i.slice(0,4).map((f)=>w("div",{className:"truncate rounded-md bg-muted px-2.5 py-1.5 font-mono text-[11px] text-foreground",children:f},f))}):null]}),(()=>{if(!o.readOnly&&n.length)return w("div",{className:"absolute left-full top-0 h-full",children:n.map((f,m)=>r.has(f.key)?null:N("div",{className:"absolute left-0 flex w-max -translate-y-1/2 items-center",style:{top:`${(m+1)/(n.length+1)*100}%`},children:[w("div",{className:"h-px w-4 bg-foreground/40"}),w("span",{className:mt,children:f.key}),w("div",{className:"h-px w-6 bg-foreground/40"}),r.has(f.key)?null:w("button",{type:"button",className:"flex size-6 shrink-0 items-center justify-center rounded-md border border-border-strong bg-card text-muted-foreground shadow-sm transition hover:border-primary hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40","aria-label":`Add after ${s} ${f.key}`,title:`Add after ${f.key}`,onClick:(u)=>{u.stopPropagation(),o.chart.onAddFromPort?.(f)},children:w(zs,{className:"size-3.5"})})]},f.key))});return null})()]})};var Ue=b(()=>{_e();ol={emerald:"bg-[color-mix(in_oklab,var(--chart-2)_12%,var(--card))] text-emerald-600 border-emerald-500/30",sky:"bg-[color-mix(in_oklab,var(--chart-4)_12%,var(--card))] text-sky-600 border-sky-500/30",slate:"bg-[color-mix(in_oklab,var(--bg-surface-alt)_55%,var(--card))] text-slate-600 border-slate-500/30",violet:"bg-[color-mix(in_oklab,var(--chart-5)_12%,var(--card))] text-violet-600 border-violet-500/30"}});var D;var ze=b(()=>{D={expression:"Expression",expressionHelp:"Calculates a value from the data available when this step runs.",fixed:"Fixed",fixedHelp:"Uses the saved value as written.",modesHelp:"Fixed uses the saved value as written. Expression calculates a value from the data available when the step runs."}});var il=(o)=>o.trim().replaceAll(/[^a-zA-Z0-9]+/gu,"_").toUpperCase(),al=(o)=>{if(typeof o.module==="string")return{exportName:o.exportName,module:o.module};return{exportName:o.exportName,module:o.module.pathname.split("/").pop()??"unknown-module"}},fe=(o)=>{let{declaration:e,phase:t,message:n,cause:r,sourceMap:i}=o,{target:a}=e,s=["FE",t.toUpperCase(),a.packageFqn,a.fqn,a.version,a.role].map(il).join("-");return{componentFqn:a.fqn,diagnosticId:s,message:n,packageFqn:a.packageFqn,phase:t,role:a.role,source:al(e.implementation.render),version:a.version,...i===void 0?void 0:{sourceMap:i},...r===void 0?void 0:{cause:String(r instanceof Error?r.message:r)}}};var gt=()=>{};import{Component as sl,createContext as ll,createElement as dl,useContext as cl,useEffect as ul,useLayoutEffect as pl,useRef as fl,useState as ml}from"react";import"react";import{jsx as ve,jsxs as bl}from"react/jsx-runtime";var gl=(o)=>bl("div",{role:"alert","data-diagnostic-id":o.diagnosticId,children:["Hosted extension failed. Diagnostic ID: ",o.diagnosticId]}),bt,yt,wt,ht=({diagnostic:o})=>cl(wt)(o),kt=(o,e)=>{console.error(`Hosted extension ${o.diagnosticId}: ${o.message}`,e)},xt,kl,ie=({componentProps:o,declaration:e,fallback:t=kl,implementationRole:n="render",load:r,onDiagnostic:i})=>{let[a,s]=ml(null),l=fl({load:r,onDiagnostic:i});pl(()=>{l.current={load:r,onDiagnostic:i}},[r,i]),ul(()=>{let k=!0;return(async()=>{try{let f=await l.current.load();if(!k)return;let m=e.implementation[n]??e.implementation.render,u=f[m.exportName];if(u===void 0){let x=fe({declaration:e,message:`Export "${m.exportName}" was not a React component.`,phase:"load"});kt(x,x),l.current.onDiagnostic?.(x),s({declaration:e,diagnostic:x,implementationRole:n,kind:"failed"});return}s({component:u,declaration:e,implementationRole:n,kind:"ready"})}catch(f){if(!k)return;let m=fe({cause:f,declaration:e,message:"The hosted component could not be loaded.",phase:"load"});kt(m,f),l.current.onDiagnostic?.(m),s({declaration:e,diagnostic:m,implementationRole:n,kind:"failed"})}})(),()=>{k=!1}},[e,n]);let d=a?.declaration===e&&a.implementationRole===n?a:null;if(d===null)return t;if(d.kind==="failed")return ve(ht,{diagnostic:d.diagnostic});let c={children:dl(d.component,o),declaration:e,...i===void 0?void 0:{onDiagnostic:i}};return ve(xt,{...c})};var Ce=b(()=>{gt();bt=Symbol.for("@collective-intelligence/extensions-sdk-frontend-react/hosted-extension-failure"),yt=globalThis,wt=yt[bt]??ll(gl);yt[bt]=wt;xt=class xt extends sl{constructor(o){super(o);this.state={error:null}}static getDerivedStateFromError(o){return{error:o}}componentDidCatch(o,e){let t=fe({cause:o,declaration:this.props.declaration,message:"The hosted component threw while rendering.",phase:"render"});this.props.onDiagnostic?.(t)}render(){if(this.state.error!==null){let o=fe({cause:this.state.error,declaration:this.props.declaration,message:"The hosted component threw while rendering.",phase:"render"});return ve(ht,{diagnostic:o})}return this.props.children}};kl=ve("output",{children:"Loading extension…"})});import{useEffect as yl,useSyncExternalStore as wl}from"react";var H=()=>{let o=ae();return wl(o.subscribe,o.snapshot,o.snapshot),o},_=(o,e)=>{yl(()=>e===void 0?void 0:o.acquireEntry(e),[o,e])};var me=b(()=>{We()});import{infiniteQueryOptions as hl,queryOptions as xl}from"@tanstack/react-query";var vt,iu=(o)=>{vt=o},Ct=(o)=>{let{optionsProvider:e,...t}=o;return t},Wt=(o)=>["workflow-field-options",Ct(o)],Ft=(o,e)=>{let t=o.optionsProvider??vt;return t===void 0?Promise.resolve({options:[]}):t(Ct(o),e.signal)},ge=(o)=>xl({queryFn:async(e)=>await Ft(o,e),queryKey:Wt(o)}),au=(o)=>hl({getNextPageParam:(e)=>e.nextCursor,initialPageParam:null,queryFn:async({pageParam:e,signal:t})=>await Ft({...o,cursor:e},{signal:t}),queryKey:Wt({...o,cursor:null})});var Ke=()=>{};import{Combobox as vl,Label as Cl}from"@collective-intelligence/ui-react/ui";import{useQuery as Wl}from"@tanstack/react-query";import{jsx as St,jsxs as Sl}from"react/jsx-runtime";var Fl=(o)=>{if(o?.kind==="literal")return o.text;return o?.kind==="translation"?o.default:void 0},Et=({context:o})=>{let{remoteOptions:e}=o,t={catalogTemplateId:e?.catalogTemplateId??"",dependencies:e?.dependencies??{},limit:50,organizationId:e?.organizationId??""},n=e?.config===void 0?ge(t):ge({...t,config:e.config}),r=(()=>{if(e?.optionsProvider===void 0)return n;if(e.config===void 0)return ge({...t,optionsProvider:e.optionsProvider});return ge({...t,config:e.config,optionsProvider:e.optionsProvider})})(),i=Wl({...r,enabled:Boolean(e)}),a=i.data?.options??o.options,s=Fl(o.field.placeholder);return Sl("div",{className:"space-y-2",children:[St(Cl,{htmlFor:`workflow-field-${o.field.key}`,children:o.field.label.kind==="literal"?o.field.label.text:o.field.label.default}),St(vl,{className:"w-full",disabled:o.readOnly||Boolean(e&&i.isPending),emptyMessage:"No options are available.",id:`workflow-field-${o.field.key}`,modal:!0,onChange:(l)=>o.onValueChange(l),options:a.map((l)=>({label:l.label,value:String(l.value)})),placeholder:s??"Select an option",searchPlaceholder:"Search options...",value:o.value===null||!p(o.value)&&!R(o.value)?"":String(o.value),width:"100%"})]})};var Tt=b(()=>{Ke()});var U;var Qe=b(()=>{U={field:"Field",unavailableConfiguration:(o)=>`${o} has configuration that this Dashboard cannot edit. Its saved configuration is preserved.`,unavailableControl:(o,e)=>`${o} uses an unavailable ${e} control. Its saved value is preserved.`}});import{Alert as El,AlertDescription as Tl}from"@collective-intelligence/ui-react/ui";import{jsx as I,jsxs as Xe,Fragment as Pl}from"react/jsx-runtime";var Ge=({diagnostics:o})=>I(Pl,{children:o.map((e)=>I(El,{variant:"destructive",children:I(Tl,{children:e.message})},`${e.code}:${e.message}`))}),Vl=(o)=>{if(p(o))return o;if(o!==null&&W(o)&&"text"in o){let{text:e}=o;return p(e)?e:U.field}if(o!==null&&W(o)&&"default"in o){let{default:e}=o;return p(e)?e:U.field}return U.field},Ye=({context:o})=>{let e={widget:o.field.widget};if(o.field.fieldFqn!==void 0&&o.field.fieldFqn!==null)e.fqn=o.field.fieldFqn;if(o.field.fieldVersion!==void 0&&o.field.fieldVersion!==null)e.version=o.field.fieldVersion;let t=H(),n=t.resolveField(e),r=n.kind==="resolved"?n.entry:void 0;_(t,r);let i=o.mode??(o.readOnly?"read_only":"value"),a={...o,readOnly:i==="read_only"||o.readOnly};if(n.kind==="resolved"&&n.source==="fallback"&&o.field.optionSource?.kind==="remote")return Xe("div",{className:"space-y-2",children:[I(Et,{context:a}),I(Ge,{diagnostics:o.diagnostics})]});if(n.kind==="resolved")return Xe("div",{className:"space-y-2",children:[I(ie,{componentProps:a,declaration:n.entry.declaration,load:()=>t.loadModule(n.entry.declaration)}),Vt(n.entry).handlesDiagnostics===!0?null:I(Ge,{diagnostics:o.diagnostics})]});return Xe("div",{className:"space-y-2",children:[I("div",{className:"rounded-lg border border-dashed border-border px-3 py-2 text-sm text-muted-foreground",children:U.unavailableControl(Vl(o.field.label),o.field.fieldFqn??o.field.widget)}),I(Ge,{diagnostics:o.diagnostics})]})};var Ze=b(()=>{Ce();We();me();Tt();Qe()});var Pt;var Ot=b(()=>{Pt={noEditableFields:"This template does not expose editable fields."}});import{jsx as Fe,jsxs as Dt}from"react/jsx-runtime";var Ol=function(e){if(p(e))return e;if(W(e)&&!Array.isArray(e)&&"en"in e){let t=e.en;return p(t)?t:""}return""},Rt=function(e){return[...e].sort((t,n)=>(t.order??0)-(n.order??0))},Rl=function(e){return Rt(e).map((t)=>({...t,fields:Rt(t.fields??[])}))},z=({context:o})=>{let e=Rl("editor"in o.template.contract?o.template.contract.editor?.form?.sections??[]:[]);return Dt("div",{className:"space-y-5",children:[e.length>0?Fe("p",{className:"text-xs leading-relaxed text-muted-foreground",children:D.modesHelp}):null,e.map((t)=>Dt("section",{className:"space-y-3 rounded-xl border border-border p-4",children:[Fe("h3",{className:"text-sm font-semibold text-foreground",children:Ol(t.label)}),(t.fields??[]).filter((n)=>o.isFieldVisible?.(n)??!0).map((n)=>o.getFieldContext?Fe(Ye,{context:o.getFieldContext(n)},n.key):null)]},t.key)),e.length?null:Fe("p",{className:"rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground",children:Pt.noEditableFields})]})};var Se=b(()=>{ze();Ze();Ot()});var Dl,Jt=(o)=>Dl.has(o),K=(o)=>P(o)?o:void 0,Te=(o)=>{let e=o.anyOf??o.oneOf;return Array.isArray(e)?e.flatMap((t)=>{let n=K(t);return n===void 0?[]:Te(n)}):[o]},Nt=(o)=>{if(o===null)return"null";if(Array.isArray(o))return"array";if(P(o))return"object";if(p(o))return"string";if(R(o))return Number.isInteger(o)?"integer":"number";return"boolean"},At=(o)=>{let{type:e}=o;if(p(e))return Jt(e)?new Set([e]):void 0;if(Array.isArray(e))return new Set(e.filter(p).filter(Jt));if(o.const!==void 0)return new Set([Nt(o.const)]);if(Array.isArray(o.enum))return new Set(o.enum.map(Nt));if(o.properties!==void 0)return new Set(["object"]);if(o.items!==void 0)return new Set(["array"]);return},A=(o)=>{let e=new Set;for(let t of Te(o)){let n=At(t);if(n===void 0)return;for(let r of n)e.add(r)}return e},jt=(o)=>{let[e]=o;if(e===void 0)return{};return o.length===1?e:{anyOf:[...o]}},ke=(o,e)=>Te(o).filter((t)=>{let n=At(t);return n===void 0||n.has(e)}),Ee=(o)=>jt(ke(o,"array").map((e)=>K(e.items)??{})),Jl=(o,e)=>o.has(e)||e==="integer"&&o.has("number"),Nl=(o,e)=>{let[t]=ke(o,"object"),n=K(t?.properties);if(n===void 0)return!0;let r=Array.isArray(t?.required)?t.required.filter(p):[];return ke(e,"object").every((i)=>{let a=K(i.properties);if(a===void 0)return!0;return r.every((s)=>(s in a))&&Object.entries(n).every(([s,l])=>{let d=K(a[s]),c=K(l);return d===void 0||c===void 0?!0:Q(c,d)})})},Q=(o,e)=>{let t=A(o),n=A(e);if(t===void 0||n===void 0)return!0;for(let r of n)if(!Jl(t,r))return!1;if(n.has("array")&&!Q(Ee(o),Ee(e)))return!1;return!n.has("object")||Nl(o,e)},Il=(o)=>jt(Te(o).flatMap((e)=>{let{type:t}=e;if(t==="null")return[];if(Array.isArray(t)){let n=t.filter((r)=>r!=="null");return n.length===0?[]:[{...e,type:n}]}return[e]})),Al=(o)=>{let e=A(o);if(e?.has("string")===!0)return'""';if(e?.has("number")===!0||e?.has("integer")===!0)return"0";if(e?.has("boolean")===!0)return"false";return},jl=(o)=>{let e=ke(o,"array").every((n)=>R(n.minItems)&&n.minItems>=1),t=Ee(o);return e||A(t)?.has("null")===!0?t:{anyOf:[t,{type:"null"}]}},eo=(o,e)=>{if(e===void 0||A(e)===void 0||A(o)===void 0)return{status:"unknown"};if(Q(e,o))return{status:"compatible"};let t=Al(e),n=(l,d)=>{if(Q(e,l))return d;return t!==void 0&&Q(e,Il(l))?[...d,`coalesce(${t})`]:void 0},r=n(o,[]),i=A(o),a=r===void 0&&i?.has("array")===!0?n(jl(o),["first"]):void 0,s=r??a;return s===void 0||s.length===0?{status:"incompatible"}:{pipes:s.map((l)=>`| ${l}`).join(" "),status:"fixable"}},It=4,ql=(o)=>{let e=ke(o,"object").flatMap((n)=>Object.keys(K(n.properties)??{}));if(e.length===0)return"object";return`{${e.slice(0,It).join(", ")}${e.length>It?", …":""}}`},oo=(o)=>{let e=A(o);if(e===void 0)return"any";return["string","integer","number","boolean","object","array","null"].filter((n)=>e.has(n)).map((n)=>{if(n==="array"){let r=Ee(o),i=A(r);return`array of ${i?.size===1&&i.has("object")?ql(r):oo(r)}`}return n}).join(" | ")};var Ve=b(()=>{Dl=new Set(["array","boolean","integer","null","number","object","string"])});var Ju=function(e){let t=e.mode==="fixed"?e.value:null;return{expression:e.mode==="expression"?e.source:"",fixed:t,mode:e.mode}},Nu=function(e){return e.mode==="fixed"?{mode:"fixed",value:e.fixed}:{languageVersion:1,mode:"expression",source:e.expression}},qt=function(e,t){return{availability:t.availability,id:t.id,label:t.label,path:t.path??[],schema:t.schema,sourceId:e}},Ml=(o,e)=>o.length===e.length&&o.every((t,n)=>t===e[n]),$l=function(e,t,n){let r=n.path??[];if(r.length===0){e.children.push(qt(t,n));return}let i=e;for(let[a,s]of r.entries()){let l=r.slice(0,a+1),d=i.children.findIndex((h)=>Ml(h.path,l)),c=i.children[d];if(a===r.length-1){if(!c)i.children.push(qt(t,n));return}if(c&&"children"in c){i=c;continue}let k=c?{...c,children:[],conditional:c.availability==="conditional",selectors:[]}:{availability:n.availability,children:[],conditional:n.availability==="conditional",id:`${t}:${l.join(".")}`,label:String(s),path:l,schema:{},selectors:[],sourceId:t};if(c)i.children[d]=k;else i.children.push(k);i=k}},Bl=function o(e){return e.flatMap((t)=>[t,...o(t.children??[])])},Ll=function(e){let t=e.availability??"guaranteed",n={availability:t,children:[],conditional:t==="conditional",id:e.id,label:e.label,path:[],schema:e.schema,selectors:(e.selectors??[]).map((r)=>r.kind),sourceId:e.id};if(e.nodeKey!==void 0&&e.nodeKey!==null)n.nodeKey=e.nodeKey;for(let r of Bl(e.fields??[]))$l(n,e.id,r);return n},Hl=function(e){return{compatibility:e.targetCompatibility??[],language:e.languageManifest,sources:(e.availableSources??[]).map(Ll)}},_l=function(e){return{canonicalSource:e.canonicalSource??null,diagnostics:(e.diagnostics??[]).map((t)=>({actualSchema:t.actualSchema,code:t.code,expectedSchema:t.expectedSchema,message:t.message,remediation:t.remediation,severity:t.severity,span:t.span})),inferredSchema:e.inferredSchema,references:e.references??[]}},Iu=function(e,t){return Q(t,e)},Mt=function(e,t,n){let r=Math.max(0,Math.min(t,e.length));return{cursor:r+n.length,source:`${e.slice(0,r)}${n}${e.slice(r)}`}};var Pe=b(()=>{Ve()});var Ul=function(e){if(e.id==="trigger")return"trigger";if(e.id==="workflow_input")return"input";let[,t]=e.id.split(":port:");return`nodes[${JSON.stringify(e.nodeKey??e.label)}]${t?`.${t}`:""}`},zl=function(e){return e.map((t)=>(()=>{if(R(t))return`[${t}]`;if(/^[A-Za-z_$][\w$]*$/u.test(t))return`.${t}`;return`[${JSON.stringify(t)}]`})()).join("")},Kl=function(e){if(e.id==="trigger")return{id:"trigger",label:"Trigger data"};if(e.id==="workflow_input")return{id:"workflow_input",label:"Workflow input"};return{id:e.id,label:e.label}},Ql=function o(e){let{source:t}=e;return e.nodes.flatMap((n)=>{let r=`${t.id}:${n.id}`,i=[...e.parentLabels,n.label],a="children"in n?n.children:[],s=`${Ul(t)}${zl(n.path)}`;return[{conditional:n.availability==="conditional",depth:e.depth,expandable:a.length>0,group:e.group,id:r,insertion:`{{ ${s} }}`,label:`${t.label} · ${i.join(".")}`,name:n.label,parentId:e.parentId,pathLabel:i.join("."),reference:s,schema:n.schema,selectors:t.selectors},...o({depth:e.depth+1,group:e.group,nodes:a,parentId:r,parentLabels:i,source:t})]})},Gl=function(e){let t=e.children.length?e.children:[{availability:e.availability,id:e.id,label:"Output",path:[],schema:e.schema,sourceId:e.id}];return Ql({depth:0,group:Kl(e),nodes:t,parentId:null,parentLabels:[],source:e})},to=function(e){return e.sources.flatMap((t)=>Gl(t))},G=function(e){return oo(e)};var Oe=b(()=>{Ve()});import{jsx as S,jsxs as Bt,Fragment as Xl}from"react/jsx-runtime";var V=({title:o,values:e})=>Bt("section",{"aria-label":o,children:[S("h3",{className:"font-medium",children:o}),e.length>0?S("ul",{className:"mt-1 list-disc pl-5 font-mono text-xs",children:e.map((t,n)=>S("li",{children:t},`${t}-${n}`))}):S("p",{className:"text-muted-foreground",children:"No entries in this language manifest."})]}),$t=function(e){return e.map((t)=>t.example??t.name)},no=({manifest:o})=>Bt(Xl,{children:[S(V,{title:"Syntax overview",values:[o.grammar]}),S(V,{title:"Interpolation",values:[`Whole value preserves type: ${o.interpolation.wholeValuePreservesType}`,`Mixed text returns: ${o.interpolation.mixedTextReturns}`]}),S(V,{title:"References",values:[o.grammar]}),S(V,{title:"Selectors",values:o.selectors.map(({kind:e})=>e)}),S(V,{title:"Unavailable-value policies",values:o.availabilityPolicies}),S(V,{title:"Operators",values:o.operators}),S(V,{title:"Functions",values:$t(o.functions)}),S(V,{title:"Casts and pipes",values:o.pipes}),S(V,{title:"Strings",values:o.pipes}),S(V,{title:"Collections",values:o.pipes}),S(V,{title:"Objects",values:o.pipes}),S(V,{title:"Dates",values:o.pipes}),S(V,{title:"If conditions",values:o.ifExamples}),S(V,{title:"Comparators",values:$t(o.comparators)})]});var ro=()=>{};var X;var Lt=b(()=>{X={applyPipes:(o)=>`Append ${o}`,expectedType:"Field expects",incompatibleType:"Incompatible type",insertWithPipes:"Insert with the pipes that make this value fit the field",validationFailed:(o)=>`We couldn't validate this expression: ${o}`,validationUnavailable:"We couldn't validate this expression right now. Check its syntax and referenced values, then try again."}});import{ChevronRight as Yl}from"@collective-intelligence/ui-react/icons";import{Badge as Zl,Button as Z,Input as Ht,Popover as ed,PopoverAnchor as od,PopoverContent as td,Textarea as nd}from"@collective-intelligence/ui-react/ui";import{Fragment as rd,useEffect as id,useRef as ad,useState as Y}from"react";import{jsx as y,jsxs as E}from"react/jsx-runtime";var _t=(o)=>o!==null&&W(o)&&!Array.isArray(o),j=(o)=>o!==null&&o!==void 0&&o!=="",sd=function o(e){if(p(e))return e;if(Array.isArray(e)){let t=e.map(o).filter((n)=>j(n));return t.length?t.join("; "):void 0}if(!_t(e))return;if(p(e.msg))return e.msg;if(p(e.message))return e.message;if(p(e.detail))return e.detail;return},ld=function(e){if(e instanceof Error&&j(e.message))return e.message;if(!J(e))return;if(!_t(e))return;return[e.detail,e.body,e.error,e.message].map(sd).find((t)=>j(t))},dd=function(e){let t=ld(e);return j(t)?X.validationFailed(t):X.validationUnavailable},Ut,cd,zt=function(e,t){return cd.flatMap((n)=>e.filter((r)=>t(r)===n))},ud=function(e){let t=new Map;for(let i of e){let a=t.get(i.option.parentId)??[];a.push(i),t.set(i.option.parentId,a)}let n=new Map,r=(i)=>{let a=n.get(i.option.id);if(a!==void 0)return a;let s=Math.min(Ut[i.compatibility.status],...(t.get(i.option.id)??[]).map(r));return n.set(i.option.id,s),s};for(let[i,a]of t)t.set(i,zt(a,r));return t},Kt=({entry:o,expanded:e,onInsert:t,onToggle:n})=>{let{compatibility:r,option:i}=o,a=n===void 0,s=r.status==="incompatible";return E("div",{className:"mt-1 flex items-start gap-1",style:{paddingInlineStart:a?0:`${i.depth*1.25}rem`},children:[!a&&i.expandable?y(Z,{"aria-expanded":e,"aria-label":`${e?"Collapse":"Expand"} ${i.label}`,className:"mt-1 size-7 shrink-0",onClick:n,size:"icon",type:"button",variant:"ghost",children:y(Yl,{"aria-hidden":!0,className:e?"size-4 rotate-90":"size-4"})}):y("span",{"aria-hidden":!0,className:"size-7 shrink-0"}),E(Z,{"aria-label":`Insert ${i.label}`,className:`block h-auto min-w-0 flex-1 whitespace-normal px-2 py-1.5 text-left ${s?"opacity-60":""}`,onClick:()=>{t(i.insertion)},type:"button",variant:"ghost",children:[y("span",{className:"block text-sm",children:a?i.pathLabel:i.name}),E("span",{className:"flex flex-wrap items-center gap-1.5 font-mono text-xs text-muted-foreground",children:[G(i.schema),s?y(Zl,{className:"font-sans",variant:"outline",children:X.incompatibleType}):null]})]}),r.status==="fixable"?y(Z,{"aria-label":`Insert ${i.label} with ${r.pipes}`,className:"mt-1 h-auto shrink-0 px-1.5 py-0.5 font-mono text-xs",onClick:()=>{t(`{{ ${i.reference} ${r.pipes} }}`)},size:"sm",title:X.insertWithPipes,type:"button",variant:"outline",children:r.pipes}):null]})},Qt=({tree:o,expanded:e,onInsert:t,onToggle:n,parentId:r})=>(o.get(r)??[]).map((i)=>{let a=e.has(i.option.id);return E(rd,{children:[y(Kt,{entry:i,expanded:a,onInsert:t,onToggle:()=>{n(i.option.id)}}),a?y(Qt,{expanded:e,onInsert:t,onToggle:n,parentId:i.option.id,tree:o}):null]},i.option.id)}),pd=({environment:o,onInsert:e,onQueryChange:t,options:n,query:r,targetSchema:i})=>{let[a,s]=Y(new Set),l=new Map(n.map(({group:u})=>[u.id,u])),d=["trigger","workflow_input"],c=[...d.flatMap((u)=>l.get(u)??[]),...[...l.values()].filter(({id:u})=>!d.includes(u))],k=n.map((u)=>({compatibility:eo(u.schema,i),option:u})),h=r.trim()!=="",f=k.filter(({option:u})=>[u.label,u.insertion,G(u.schema)].join(" ").toLowerCase().includes(r.trim().toLowerCase())),m=(u)=>{s((x)=>{let C=new Set(x);if(C.has(u))C.delete(u);else C.add(u);return C})};return E("div",{className:"grid h-96 max-h-[calc(100dvh-3rem)] grid-cols-[minmax(0,1fr)_14rem] overflow-hidden",children:[E("div",{className:"min-h-0 touch-pan-y overflow-y-auto overscroll-y-contain border-r p-2",onWheel:(u)=>{u.stopPropagation()},children:[y(Ht,{"aria-label":"Search expression suggestions",onChange:(u)=>{t(u.target.value)},placeholder:"Search available values",value:r}),c.map((u)=>{let x=(h?f:k).filter(({option:C})=>C.group.id===u.id);if(x.length===0)return null;return E("section",{"aria-label":u.label,className:"mt-3",children:[y("h3",{className:"px-2 text-xs font-semibold text-muted-foreground",children:u.label}),h?zt(x,(C)=>Ut[C.compatibility.status]).map((C)=>y(Kt,{entry:C,expanded:!1,onInsert:e},C.option.id)):y(Qt,{expanded:a,onInsert:e,onToggle:m,parentId:null,tree:ud(x)})]},u.id)}),(h?f:k).length===0?y("p",{className:"p-3 text-sm text-muted-foreground",children:"No matching workflow sources."}):null]}),E("aside",{className:"space-y-3 p-3","aria-label":"Expression helper",children:[i===void 0?null:E("p",{className:"text-xs",children:[E("span",{className:"text-muted-foreground",children:[X.expectedType," "]}),y("span",{className:"font-mono",children:G(i)})]}),y("p",{className:"text-xs text-muted-foreground",children:"Select a typed source. Expand an object to pick one of its fields, or insert the whole object."}),y("h3",{className:"text-xs font-semibold",children:"Pipes"}),o.language.pipes.map((u)=>E(Z,{className:"mr-1 mb-1 h-auto px-1.5 py-0.5 font-mono text-xs",onClick:()=>{e(` | ${u}`)},size:"sm",type:"button",variant:"outline",children:["| ",u]},u))]})]})},fd,md=function(e,t){let n=fd.exec(e)?.groups?.body;return n===void 0||n.includes("{{")?void 0:`{{ ${n.trim()} ${t} }}`},gd=({diagnostic:o,onApplyFix:e,source:t,targetSchema:n})=>{let r=o.expectedSchema??n,i=o.code==="incompatible_expression_type"&&o.actualSchema!==null?eo(o.actualSchema,r??void 0):void 0,a=i?.status==="fixable"?md(t,i.pipes):void 0;return E("div",{className:"space-y-1 text-sm text-destructive",role:"alert",children:[E("p",{children:[o.message," (characters ",o.span.start,"–",o.span.end,")"]}),j(o.remediation)?y("p",{className:"text-xs text-muted-foreground",children:o.remediation}):null,i?.status==="fixable"&&a!==void 0&&e!==void 0?y(Z,{className:"h-auto px-1.5 py-0.5 font-mono text-xs",onClick:()=>{e(a)},size:"sm",type:"button",variant:"outline",children:X.applyPipes(i.pipes)}):null]})},io=({describedBy:o,environment:e,inputLabel:t="Expression",source:n,onChange:r,validate:i,multiline:a=!1,readOnly:s=!1,targetSchema:l})=>{let d=ad(null),c=(g)=>{d.current=g},[k,h]=Y(n.length),[f,m]=Y(!1),[u,x]=Y("suggestions"),[C,ee]=Y(""),[Me,$e]=Y(null),[L,oe]=Y(null),ce=i===void 0||n===""?null:Me,F=i===void 0||n===""?null:L,O=[o,j(F)?"expression-validation":void 0].filter(Boolean).join(" ")||void 0;id(()=>{let g=new AbortController;if(!i||n==="");else{let Be=async()=>{try{let Le=await i(n,g.signal);if(!g.signal.aborted)$e(Le),oe(null)}catch(Le){if(!g.signal.aborted)oe(dd(Le))}},ne=window.setTimeout(()=>{Be()},300);return()=>{g.abort(),window.clearTimeout(ne)}}return()=>{g.abort()}},[n,i]);let q=to(e),te=(g)=>{let Be=d.current?.selectionStart??k,ne=Mt(n,Be,g);h(ne.cursor),r(ne.source),queueMicrotask(()=>{d.current?.focus(),d.current?.setSelectionRange(ne.cursor,ne.cursor)})};return E("div",{className:"space-y-2",children:[E(ed,{onOpenChange:(g)=>{if(m(g),!g)ee(""),x("suggestions")},open:f,children:[y(od,{asChild:!0,children:y("div",{children:(()=>{if(a)return y(nd,{"aria-describedby":O,"aria-invalid":j(F)||(ce?.diagnostics.length??0)>0,"aria-label":t,className:"min-h-24 text-sm",disabled:s,onChange:(g)=>{r(g.target.value),h(g.currentTarget.selectionStart??n.length)},onFocus:()=>{m(!0)},onKeyDown:(g)=>{if(g.key==="Escape")m(!1)},onSelect:(g)=>{h(g.currentTarget.selectionStart??n.length)},placeholder:"Choose a source or start typing",ref:c,value:n});return y(Ht,{"aria-describedby":O,"aria-invalid":j(F)||(ce?.diagnostics.length??0)>0,"aria-label":t,className:"text-sm",disabled:s,onChange:(g)=>{r(g.target.value),h(g.currentTarget.selectionStart??n.length)},onFocus:()=>{m(!0)},onKeyDown:(g)=>{if(g.key==="Escape")m(!1)},onSelect:(g)=>{h(g.currentTarget.selectionStart??n.length)},placeholder:"Choose a source or start typing",ref:c,value:n})})()})}),E(td,{align:"start",className:"w-[min(48rem,calc(100vw-3rem))] p-0",onOpenAutoFocus:(g)=>{g.preventDefault()},children:[E("div",{className:"flex border-b p-1",role:"tablist",children:[y(Z,{"aria-selected":u==="suggestions",onClick:()=>{x("suggestions")},role:"tab",size:"sm",type:"button",variant:u==="suggestions"?"secondary":"ghost",children:"Suggestions"}),y(Z,{"aria-selected":u==="syntax",onClick:()=>{x("syntax")},role:"tab",size:"sm",type:"button",variant:u==="syntax"?"secondary":"ghost",children:"Syntax reference"})]}),u==="suggestions"?y(pd,{environment:e,onInsert:te,onQueryChange:ee,options:q,query:C,targetSchema:l}):y("div",{className:"max-h-96 touch-pan-y overflow-y-auto overscroll-y-contain p-4 text-sm",onWheel:(g)=>{g.stopPropagation()},children:y(no,{manifest:e.language})})]})]}),j(F)?y("p",{id:"expression-validation",role:"alert",children:F}):null,ce?.diagnostics.map((g)=>y(gd,{diagnostic:g,onApplyFix:s?void 0:r,source:n,targetSchema:l},`${g.code}-${g.span.start}`))]})};var Gt=b(()=>{Pe();Ve();Oe();ro();Lt();Ut={compatible:0,fixable:1,incompatible:3,unknown:2},cd=[0,1,2,3],fd=/^\s*\{\{(?<body>[\s\S]*?)\}\}\s*$/u});var Re=b(()=>{Gt();ro();Oe()});import{Alert as kd,AlertDescription as bd,Label as yd,ToggleGroup as wd,ToggleGroupItem as Xt}from"@collective-intelligence/ui-react/ui";import{useId as hd,useState as Yt}from"react";import{jsx as T,jsxs as De}from"react/jsx-runtime";var xd,Zt=function(e){return e.mode==="expression"?{expression:e.source,fixed:null,mode:"expression"}:{expression:"",fixed:e.value,mode:"fixed"}},vd=({mode:o})=>T("span",{className:"shrink-0 text-xs text-muted-foreground",title:o==="expression"?D.expressionHelp:D.fixedHelp,children:o==="expression"?D.expression:D.fixed}),be=({allowExpression:o=!1,allowFixed:e=!0,controlId:t,diagnostics:n=xd,expressionEditor:r,expressionMultiline:i=!1,help:a,label:s,onValueChange:l,readOnly:d=!1,renderExpression:c,renderFixed:k,required:h=!1,sensitive:f=!1,value:m})=>{let u=hd(),[x,C]=Yt(()=>Zt(m)),ee=JSON.stringify(m),[Me,$e]=Yt(ee),L=t===void 0?void 0:`${t}-label`;if(ee!==Me)$e(ee),C(Zt(m));let oe=(()=>{if(o&&!e)return"expression";if(e&&!o)return"fixed";return x.mode})(),ce=d;return De("section",{className:"space-y-2",children:[De("div",{className:"flex items-center justify-between gap-3",children:[T("div",{className:"min-w-0",children:De("div",{className:"flex items-center gap-1",children:[T(yd,{htmlFor:t,id:L,children:s}),h?T("span",{"aria-label":"Required",children:"*"}):null,f?T("span",{className:"ml-1 text-xs text-muted-foreground",children:"Sensitive"}):null]})}),o&&d?T(vd,{mode:oe}):null,o&&e&&!d?T("div",{"aria-label":`${s} mode controls`,className:"flex shrink-0 items-center gap-1",children:De(wd,{"aria-label":`${s} mode`,className:"gap-0",disabled:ce,onValueChange:(F)=>{if(F==="fixed"||F==="expression")C((O)=>({...O,mode:F}))},size:"sm",type:"single",value:oe,variant:"outline",children:[T(Xt,{className:"h-7 px-4 text-xs",title:D.fixedHelp,value:"fixed",children:D.fixed}),T(Xt,{className:"h-7 px-4 text-xs",title:D.expressionHelp,value:"expression",children:D.expression})]})}):null]}),a!==void 0&&a!==""?T("p",{id:u,className:"text-xs leading-relaxed text-muted-foreground",children:a}):null,(()=>{if(oe==="expression"){if(r?.environment){let q=r.validate===void 0?{}:{validate:r.validate};return T(io,{...a?{describedBy:u}:{},environment:r.environment,multiline:i,onChange:(te)=>{C((g)=>({...g,expression:te})),l({languageVersion:1,mode:"expression",source:te})},readOnly:d,source:x.expression,targetSchema:r.targetSchema,...q})}if(r?.loading===!0)return T("output",{children:"Loading expression editor…"});if(r?.error!==void 0&&r.error!=="")return T("p",{role:"alert",children:r.error});let O={disabled:d,onChange:(q)=>{C((te)=>({...te,expression:q})),l({languageVersion:1,mode:"expression",source:q})},value:x.expression};if(a)O.describedBy=u;if(t!==void 0)O.controlId=`${t}-expression`;if(L!==void 0)O.labelledBy=L;return c?.(O)}let F={disabled:d,onChange:(O)=>{C((q)=>({...q,fixed:O})),l({mode:"fixed",value:O})},value:x.fixed};if(a)F.describedBy=u;if(t!==void 0)F.controlId=t;if(L!==void 0)F.labelledBy=L;return k(F)})(),n.map((F)=>T(kd,{variant:"destructive",children:T(bd,{children:F.message})},`${F.code}:${F.message}`))]})};var ao=b(()=>{Re();ze();xd=[]});var so=b(()=>{ao()});var Je;var en=b(()=>{Je={inputBindingsDescription:"Choose the value passed into each workflow input when this trigger starts a run. Fixed uses a saved value; Expression calculates it from the trigger data.",inputBindingsTitle:"Workflow input mapping",noInputs:"This workflow has no declared input fields to map."}});var ye=function(e){return P(e)?e:{}},lo=function(e){return ye(e)},Cd=function(e,t,n){let r=e.anyOf;if(!Array.isArray(r))return;let i=r.filter((d)=>ye(d).type!=="null");if(i.length!==1||i.length===r.length)return;let a=lo(n(i[0],t)),{type:s}=a,l={...a,...Object.fromEntries(Object.entries(e).filter(([d])=>d!=="anyOf"&&d!=="$defs"))};if(p(s))l.type=[s,"null"];return l},Wd=function(e){let t=ye(e.$defs),n=(r,i=new Set)=>{if(Array.isArray(r))return r.map((c)=>n(c,i));if(!P(r))return r;let a=ye(r),s=a.$ref,l=p(s)?s:void 0;if(l!==void 0&&l.startsWith("#/$defs/")){let c=l.slice(8),k=t[c];if(k!==void 0&&!i.has(c))return n(k,new Set(i).add(c))}let d=Cd(a,i,n);if(d)return d;return Object.fromEntries(Object.entries(a).filter(([c])=>c!=="$defs").map(([c,k])=>[c,n(k,i)]))};return lo(n(e))},Fd=function(e){let{type:t}=e;return t==="null"||Array.isArray(t)&&t.includes("null")},Sd=function(e){let{type:t}=e;if(p(t))return t==="null"?e:{...e,type:[t,"null"]};if(Array.isArray(t))return t.includes("null")?e:{...e,type:[...t,"null"]};return e},Ed=function o(e,t=[],n=!1){return Object.entries(ye(e.properties)).map(([r,i])=>{let a=lo(i),s=n?Sd(a):a,l=[...t,r],d=o(a,l,n||Fd(a)),c={availability:"guaranteed",id:`trigger:${l.join(".")}`,label:r,path:l,schema:s,sourceId:"trigger"};return d.length?{...c,children:d,conditional:!1,selectors:[]}:c})},on=function(e){let{triggerInput:t}=e;if(!t)return;let n=Wd(t.schema);return{compatibility:[],language:t.languageManifest,sources:[{availability:"guaranteed",children:Ed(n),conditional:!1,id:"trigger",label:"Trigger data",path:[],schema:n,selectors:[],sourceId:"trigger"}]}};var tn=()=>{};import{Input as Td}from"@collective-intelligence/ui-react/ui";import{jsx as le,jsxs as nn}from"react/jsx-runtime";var Vd=(o)=>{if(o===null||o===void 0||p(o)||R(o)||pe(o))return String(o??"");return JSON.stringify(o)??""},se=function(e){return P(e)?e:{}},Pd=function(e,t){return e?.length===t.length&&e.every((n,r)=>n===t[r])},Od=function(e,t){if(t==="number"||t==="integer"){let n=Number(e);return Number.isFinite(n)?n:e}if(t==="boolean")return e==="true";return e},Rd=function(e){if(!P(e))return{mode:"fixed",value:e??null};if(e.mode==="expression"&&p(e.source))return{languageVersion:1,mode:"expression",source:e.source};if(e.mode==="fixed"&&J(e.value))return{mode:"fixed",value:e.value};return{mode:"fixed",value:e}},rn=({context:o})=>{let e=se(o.workflowContracts?.inputContract.jsonSchema.properties),t=o.trigger?.inputBindings??{},n=on(o.template.contract);return nn("div",{className:"space-y-5",children:[le(z,{context:o}),nn("section",{className:"space-y-2 rounded-xl border border-border p-4",children:[le("h3",{className:"text-sm font-semibold",children:Je.inputBindingsTitle}),le("p",{className:"text-xs text-muted-foreground",children:Je.inputBindingsDescription}),Object.keys(e).length===0?le("p",{className:"text-xs text-muted-foreground",children:Je.noInputs}):null,Object.entries(e).map(([r,i])=>{let a=se(t[r]),s=Rd(a?.value),{description:l}=se(i),d=o.triggerInputExpressionValidator?.(r),c=n===void 0?void 0:{environment:n,targetSchema:se(i)};if(c!==void 0&&d!==void 0)c.validate=d;return le(be,{allowExpression:!0,...c===void 0?{}:{expressionEditor:c},diagnostics:o.diagnostics.filter((k)=>Pd(k.path,["inputBindings",r])),controlId:`workflow-trigger-input-${r}`,...p(l)?{help:l}:{},label:`${r} (${G(se(i))})`,readOnly:o.readOnly,value:s,onValueChange:(k)=>o.commands.updateTriggerConfiguration?.({inputBindings:{...t,[r]:{overridePolicy:"locked",value:k}}}),renderFixed:({value:k,onChange:h,controlId:f,describedBy:m,disabled:u})=>le(Td,{"aria-describedby":m,id:f,disabled:u,value:Vd(k),onChange:(x)=>{h(Od(x.target.value,se(i)?.type))}})},r)})]})]})};var an=b(()=>{Re();so();Se();en();tn()});var gn={};Dn(gn,{renderDefaultActionChart:()=>sn,renderDefaultActionDetails:()=>ln,renderDefaultInputChart:()=>un,renderDefaultInputDetails:()=>pn,renderDefaultOutputChart:()=>fn,renderDefaultOutputDetails:()=>mn,renderDefaultTriggerChart:()=>dn,renderDefaultTriggerDetails:()=>cn});import{jsx as M}from"react/jsx-runtime";var sn=(o)=>M(re,{context:o,accent:"slate"}),ln=(o)=>M(z,{context:o}),dn=(o)=>M(re,{context:o,accent:"violet"}),cn=(o)=>M(rn,{context:o}),un=(o)=>M(re,{context:o,accent:"sky"}),pn=(o)=>M(z,{context:o}),fn=(o)=>M(re,{context:o,accent:"emerald"}),mn=(o)=>M(z,{context:o});var co=b(()=>{Ue();Se();an()});import{declareFrontendComponent as Dd}from"@collective-intelligence/extensions-sdk-frontend";var uo=(o)=>({exportName:o,load:async()=>await Promise.resolve().then(() => (co(),gn)),module:import.meta.url}),Ne=(o,e,t)=>Dd({implementation:{chart:uo(e),details:uo(t),render:uo(t)},metadata:{kind:o,mode:"default"},target:{fqn:`builtin.core.workflows.nodes.${o.replace(/_node$/u,"")}`,packageFqn:"builtin.core",role:"workflow_template_default",version:"1.0.0"}}),po;var fo=b(()=>{po=[Ne("action_node","renderDefaultActionChart","renderDefaultActionDetails"),Ne("trigger_node","renderDefaultTriggerChart","renderDefaultTriggerDetails"),Ne("input_node","renderDefaultInputChart","renderDefaultInputDetails"),Ne("output_node","renderDefaultOutputChart","renderDefaultOutputDetails")]});var kn=async(o,e="render")=>{let t=o.implementation[e]??o.implementation.render;if(t.load===void 0)throw Error(`Workflow contribution "${o.target.fqn}" requires a retained module loader for "${e}".`);return await t.load()};import{WorkflowTemplateKinds as Jd}from"@collective-intelligence/extensions-sdk";var we=(o)=>Jd.find((e)=>e===o);var mo=()=>{};import{createFrontendCatalog as Nd,declareFrontendPackage as Id}from"@collective-intelligence/extensions-sdk-frontend";var bo,Ie,yo=(o)=>{let{declaration:{metadata:e}}=o;if(!P(e))return{};let t=p(e.kind)?we(e.kind):void 0,n;if(p(e.mode)){if(e.mode==="default")n="default";else if(e.mode==="override")n="override"}let r={};if(p(e.fqn))r.fqn=e.fqn;if(pe(e.handlesDiagnostics))r.handlesDiagnostics=e.handlesDiagnostics;if(t!==void 0)r.kind=t;if(n!==void 0)r.mode=n;if(p(e.widget))r.widget=e.widget;return r},Ae=(o)=>{let e=o?.trim().toLowerCase();return e===void 0||e===""?void 0:e},bn=()=>bo.snapshot().entries,yn=(o,e,t)=>{let n=Ae(o),r=Ae(e);if(n===void 0||r===void 0)return;return bn().find((i)=>i.target.toLowerCase()===n&&i.version.toLowerCase()===r&&i.role===t)},go=(o,e,t)=>{let n=Ae(e);return bn().find((r)=>{let i=yo(r);return Ae(i[o])===n&&r.role===t})},wn=(o)=>{Ie=[...Ie.filter((n)=>!o.some((r)=>r.manifest.fqn===n.manifest.fqn)),...o];let t=bo.activate(Ie);if(t.kind==="invalid")throw Error(t.errors.map((n)=>n.message).join("; "));if(t.kind!=="activated")throw Error(`Workflow catalog activation became stale (${t.reason}).`)},ko,Ad=()=>{if(Ie.some((o)=>o.manifest.fqn===ko.manifest.fqn))return;wn([ko])},jd=()=>bo.snapshot(),qd=(o)=>{let e=p(o)?{widget:o}:o,t=e.fqn??void 0,n=e.version??void 0,r=yn(t,n,"workflow_field");if(r!==void 0)return{entry:r,kind:"resolved",source:"exact"};if(t!==void 0&&n!==void 0){let s=go("widget",e.widget??"","workflow_field_fallback");if(s!==void 0&&t.toLowerCase().startsWith("builtin."))return{entry:s,kind:"resolved",source:"fallback"};let l={fqn:t,kind:"unavailable"};if(e.widget!==void 0)l.widget=e.widget;return l}let i=go("widget",e.widget??"","workflow_field_fallback");if(i!==void 0)return{entry:i,kind:"resolved",source:"fallback"};let a={kind:"unavailable"};if(e.fqn!==void 0&&e.fqn!==null)a.fqn=e.fqn;if(e.widget!==void 0)a.widget=e.widget;return a},Md=(o)=>{let e=we(o.kind);if(e===void 0)return{fqn:o.fqn,kind:"unavailable",templateKind:o.kind};let t=yn(o.fqn,o.version??"1.0.0","workflow_template_override");if(t!==void 0&&yo(t).kind===e)return{entry:t,kind:"resolved",source:"override"};let n=go("kind",e,"workflow_template_default");if(n!==void 0)return{entry:n,kind:"resolved",source:"default"};return{fqn:o.fqn,kind:"unavailable",templateKind:o.kind}},Vt,hn=()=>{},$d=()=>hn,Bd,ae=()=>Vo()??Bd,Ld=()=>ae().snapshot(),Hd=(o)=>ae().resolveField(o),_d=(o)=>ae().resolveTemplate(o);var We=b(()=>{fo();mo();mo();bo=Nd(),Ie=[],ko=Id({components:po,manifest:{fqn:"builtin.core",name:"Dashboard Workflow UI",version:"1.0.0"}}),Vt=yo,Bd={acquireEntry:()=>hn,loadModule:kn,resolveField:qd,resolveTemplate:Md,snapshot:jd,subscribe:$d}});We();me();Ce();me();Qe();import{jsx as xn}from"react/jsx-runtime";var Ud=({context:o})=>{let e=H(),t=e.resolveField(o.field),n=t.kind==="resolved"&&t.entry.declaration.implementation.configuration!==void 0?t.entry:void 0;if(_(e,n),t.kind==="resolved"&&n!==void 0)return xn(ie,{componentProps:o,declaration:t.entry.declaration,implementationRole:"configuration",load:()=>e.loadModule(t.entry.declaration,"configuration")});return xn("div",{className:"rounded-md border border-dashed border-border p-2 text-xs text-muted-foreground",children:U.unavailableConfiguration(o.field.label)})};Ze();Pe();so();ao();import{Textarea as zd}from"@collective-intelligence/ui-react/ui";import{jsx as vn}from"react/jsx-runtime";import{createElement as Qd}from"react";var Gp=({help:o,label:e,onValueChange:t,expressionEditor:n,readOnly:r,renderFixed:i,resetKey:a,slotId:s,value:l})=>vn("div",{"data-expression-slot":s,children:Qd(be,{allowExpression:!0,...o===void 0?{}:{help:o},...n===void 0?{}:{expressionEditor:n},key:`${s}:${a??"current"}`,label:e,onValueChange:t,...r===void 0?{}:{readOnly:r},renderExpression:({describedBy:d,disabled:c,onChange:k,value:h})=>vn(zd,{"aria-describedby":d,"aria-label":`${e} expression`,disabled:c,onChange:(f)=>{k(f.target.value)},placeholder:"{{ input.value }}",value:h}),renderFixed:i,value:l})}),Kd=function(e){if(!P(e))return!1;if(e.mode==="fixed")return J(e.value);return e.mode==="expression"&&R(e.languageVersion)&&e.languageVersion===1&&p(e.source)},Xp=function(e){if(Kd(e))return e;return{mode:"fixed",value:e}};var wo=function(e,t){let n=[...e];for(let r=0;r<n.length;r+=1)for(let i=r+1;i<n.length;i+=1){let a=n[r],s=n[i];if(a!==void 0&&s!==void 0&&t(a,s)>0)n[r]=s,n[i]=a}return n};var Wn=function(e){return W(e)&&!Array.isArray(e)},Gd=function o(e){return e.flatMap((t)=>[...t.templates??[],...o(t.children??[])])},ho=function(e){return e.kind==="field_collection"&&"collection"in e.contract},xo=function(e){return`${e.fqn}@${e.version}`},Cn=function(e){return e.kind==="literal"?e.text:e.default},Xd=function(e){return e.kind==="field"&&"field"in e.contract},Yd=function(e,t){if(!e.enabled||e.state!=="available")return!1;return t==="input"?e.contract.field.availableForInput!==!1:e.contract.field.availableForOutput!==!1},Zd=function(e,t){let n=e.find((r)=>ho(r)&&xo(r.contract.collection)===t);return n&&ho(n)?n.contract.collection.weight??0:0},je=function(e){return e!==void 0&&Wn(e)?e:{}},rf=function(e,t){let n=Gd(e?.categories??[]),r=new Map;for(let a of n){if(!ho(a))continue;r.set(xo(a.contract.collection),Cn(a.label))}let i=new Map;for(let a of n){if(!Xd(a)||!Yd(a,t))continue;let s=a.contract.field,l=xo({fqn:s.collectionFqn,version:s.collectionVersion}),d=i.get(l)??{fields:[],key:l,label:r.get(l)??s.collectionFqn,weight:Zd(n,l)},c={catalogTemplateId:a.id,collectionKey:l,configSchema:je(s.configSchema),fqn:s.fqn,label:Cn(a.label),schema:je(s.valueSchema),version:s.version};if(s.user!==void 0)c.user=s.user;d.fields.push(c),i.set(l,d)}return wo([...i.values()].map((a)=>({...a,fields:wo(a.fields,(s,l)=>s.label.localeCompare(l.label)||s.fqn.localeCompare(l.fqn))})),(a,s)=>a.weight-s.weight||a.label.localeCompare(s.label)||a.key.localeCompare(s.key))},af=function(e){return{key:e.key,label:e.label,options:e.fields.map((t)=>({fqn:t.fqn,label:t.label,searchTerms:[t.fqn],version:t.version}))}},ec=function(e){let t=je(e.$defs),n=(r,i=new Set)=>{if(Array.isArray(r))return r.map((d)=>n(d,i));if(r===null||!Wn(r))return r;let a=r,s=a.$ref,l=p(s)?s:void 0;if(l!==void 0&&l.startsWith("#/$defs/")){let d=l.slice(8),c=t[d];if(c!==void 0&&c!==null&&!i.has(d))return n(c,new Set(i).add(d))}return Object.fromEntries(Object.entries(a).filter(([d])=>d!=="$defs").map(([d,c])=>[d,n(c,i)]))};return je(n(e))},sf=function(e,t){let{title:n,...r}=ec(t.schema),i={...r};if(p(e.title))i.title=e.title;return i};import{useDebouncedCallback as oc}from"@collective-intelligence/ui-react/hooks";import{Check as tc,ChevronsUpDown as nc}from"@collective-intelligence/ui-react/icons";import{Button as rc,Command as ic,CommandGroup as ac,CommandInput as sc,CommandItem as lc,CommandList as dc,Popover as cc,PopoverContent as uc,PopoverTrigger as pc}from"@collective-intelligence/ui-react/ui";import{useMemo as fc,useState as vo}from"react";import{jsx as B,jsxs as he}from"react/jsx-runtime";var mc=250,Co=function(e){return`${e.fqn}@${e.version}`},gc=function(e,t){let n=t.trim().toLocaleLowerCase();if(!n)return e;return e.flatMap((r)=>{let i=r.options.filter((a)=>[a.label,a.fqn,...a.searchTerms??[]].join(" ").toLocaleLowerCase().includes(n));return i.length?[{...r,options:i}]:[]})},ff=({collections:o,value:e,onChange:t,ariaLabel:n="Field type"})=>{let[r,i]=vo(!1),[a,s]=vo(""),[l,d]=vo(""),c=oc(d,mc),k=o.flatMap((m)=>m.options).find((m)=>Co(m)===e),h=fc(()=>gc(o,l),[o,l]),f=h.some((m)=>m.options.length>0);return he(cc,{modal:!0,open:r,onOpenChange:(m)=>{if(i(m),!m)c.cancel(),s(""),d("")},children:[B(pc,{asChild:!0,children:he(rc,{type:"button",variant:"outline","aria-label":n,"aria-expanded":r,className:"mt-1 w-full justify-between font-normal",children:[B("span",{className:"truncate",children:k?.label??"Select a field type"}),B(nc,{className:"ml-2 size-4 shrink-0 opacity-50"})]})}),B(uc,{align:"start",className:"w-[var(--radix-popover-trigger-width)] p-0",children:he(ic,{shouldFilter:!1,children:[B(sc,{placeholder:"Search field types...",value:a,onValueChange:(m)=>{s(m),c(m)}}),he(dc,{children:[f?null:B("p",{className:"py-6 text-center text-sm",children:"No field type found."}),h.map((m)=>B(ac,{heading:m.label,children:m.options.map((u)=>{let x=Co(u);return he(lc,{value:Co(u),onSelect:()=>{t(u),i(!1)},children:[B(tc,{className:e===x?"mr-2 size-4 opacity-100":"mr-2 size-4 opacity-0"}),u.label]},x)})},m.key))]})]})})]})};Ue();Se();fo();co();Ce();me();import{jsx as Fn,jsxs as bc}from"react/jsx-runtime";var kc=({context:o})=>{let e=H(),t=e.resolveTemplate(o.template);if(_(e,t.kind==="resolved"?t.entry:void 0),t.kind==="resolved")return Fn(ie,{componentProps:o,declaration:t.entry.declaration,implementationRole:"details",load:()=>e.loadModule(t.entry.declaration,"details")});return bc("div",{className:"rounded-xl border border-dashed border-border p-4 text-sm text-muted-foreground",children:["No dashboard editor is available for template kind"," ",Fn("code",{children:t.templateKind}),". The workflow draft has not been changed."]})};_e();var Wo=(o)=>o!==void 0&&o!==null&&W(o)&&!Array.isArray(o),Sn=function(e,t){return Object.fromEntries(Object.entries(e).filter(([n])=>n!==t))},En=function(e){if(e==="input_binding")return"inputs";if(e==="setting")return"settings";if(e==="metadata")return"metadata";return"config"},de=function(e){return Wo(e)?e:void 0},Fo=function(e){let t=de(e);if(t===void 0||!("value"in t))return e;return t.mode==="fixed"||t.kind==="literal"?t.value:e},qe=function(e,t){let n=e[En(t.target)];for(let r of t.path){let i=de(Fo(n));if(i===void 0)return;n=i[r]}return Fo(n)},yc=function(e,t){return qe(e,t.binding)},wc=function o(e,t,n){let[r,...i]=t;if(r===void 0)return e??{};let a=e??{};if(!i.length)return{...a,[r]:n};let s=de(a[r]),l=de(Fo(s));if(s?.mode==="fixed")return{...a,[r]:{...s,value:o(l,i,n)}};return{...a,[r]:o(l,i,n)}},So=function(e,t){return[e==="input_binding"?"inputBinding":e,...t].map((n)=>encodeURIComponent(String(n))).join("/")},hc=function(e,t,n){let r={...de(e?.fieldDisplayValues)},i=So(t.binding.target,t.binding.path);if(n)r[i]=n;else return{...e,fieldDisplayValues:Sn(r,i)};return{...e,fieldDisplayValues:r}},xc=function(e,t,n,r){let i=En(t.binding.target),a={[i]:wc(e[i],t.binding.path,n)};if(r!==void 0)a.metadata=hc(i==="metadata"?a.metadata:e.metadata,t,r);return a},Tn=function(e,t,n){let r=e.metadata?.fieldDisplayValues;if(r===void 0||r===null||!Wo(r))return;let i=r[So(t.binding.target,n)];if(i===void 0||i===null||!Wo(i))return;return p(i.label)&&"value"in i?{label:i.label,value:i.value}:void 0},vc=function(e,t){return Tn(e,t,t.binding.path)},Cc=function(e,t,n){return Tn(e,t,[...t.binding.path,...n])},Wc=function(e,t,n,r){let i={...de(e?.fieldDisplayValues)},a=So(t,n);if(r)i[a]=r;else return{...e,fieldDisplayValues:Sn(i,a)};return{...e,fieldDisplayValues:i}},Fc=function(e,t,n,r){return{metadata:Wc(e.metadata,t.binding.target,[...t.binding.path,...n],r)}};var Eo=function o(e,t){if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((n,r)=>o(n,t[r]));if(e!==null&&t!==null&&e!==void 0&&t!==void 0&&W(e)&&W(t)){let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every((r)=>o(e[r],t[r]))}return e===t},Vn=function(e){return e!==void 0&&e!==null&&e!==""},Sc=function(e,t){if(!Array.isArray(t)||e===void 0)return!1;return(Array.isArray(e)?e:[e]).some((r)=>t.some((i)=>Eo(r,i)))},Ec=function(e,t){return(e.visibleWhen??[]).every((n)=>{let r=qe(t,n.binding);switch(n.operator){case"equals":return Eo(r,n.value);case"not_equals":return!Eo(r,n.value);case"is_set":return Vn(r);case"is_not_set":return!Vn(r);case"in":return Sc(r,n.value);default:return!1}})};var Tc=function(e){if(!e)return"";return e.kind==="literal"?e.text:e.default};Pe();Re();Oe();Ke();export{re as CatalogNodeChartBlock,z as CatalogNodeDetailsEditor,io as ExpressionEditor,Gp as ExpressionSlot,no as ExpressionSyntaxReference,ff as FieldTypeSelect,Ud as WorkflowFieldConfigurationResolver,be as WorkflowFieldFrame,Ye as WorkflowFieldResolver,kc as WorkflowTemplateDetails,Ad as activateDashboardWorkflowCatalog,wn as activateWorkflowCatalog,Xp as asExpressionSlotValue,Tc as catalogText,iu as configureWorkflowFieldOptionsProvider,Ju as createExpressionDraft,ko as dashboardWorkflowPackage,po as defaultWorkflowTemplateDeclarations,to as expressionSourceOptions,rf as fieldCollectionsFromCatalog,Co as fieldTypeIdentity,Mt as insertExpressionAtCursor,Nn as installWorkflowCatalogHost,pe as isBoolean,Jn as isFunction,J as isJsonValue,R as isNumber,W as isObject,P as isRecord,Iu as isSchemaCompatible,p as isString,Pc as isUndefined,Ec as isWorkflowFieldVisible,Hl as normalizeExpressionEnvironment,_l as normalizeExpressionValidation,we as parseWorkflowTemplateKind,Fc as patchWorkflowFieldPartDisplayValue,xc as patchWorkflowFieldValue,qe as readWorkflowBindingValue,vc as readWorkflowFieldDisplayValue,Cc as readWorkflowFieldPartDisplayValue,yc as readWorkflowFieldValue,sn as renderDefaultActionChart,ln as renderDefaultActionDetails,un as renderDefaultInputChart,pn as renderDefaultInputDetails,fn as renderDefaultOutputChart,mn as renderDefaultOutputDetails,dn as renderDefaultTriggerChart,cn as renderDefaultTriggerDetails,Hd as resolveWorkflowField,_d as resolveWorkflowTemplate,sf as schemaForWorkflowField,G as schemaLabel,Nu as serializeExpressionDraft,Oc as toDisplayString,af as toFieldTypeCollection,_ as useCatalogEntryLease,H as useWorkflowCatalogHost,ae as workflowCatalogHost,Ld as workflowCatalogSnapshot,ge as workflowFieldOptions,au as workflowFieldOptionsInfinite,He as workflowNodePresentation};
@@ -49,51 +49,56 @@ A package that declares Agents or Skills needs a person to install it; an instal
49
49
  ```mermaid
50
50
  flowchart TD
51
51
  ext["apps/extensions (@acme/extensions)<br/>index.ts: declarePackage, deploy order<br/>studio.ts: loadFrontendCatalog"]
52
- org["@acme/organization<br/>package identity, VERSION, domain,<br/>Sales group, external application,<br/>profiles, grants, Studio app"]
53
- lead["@acme/lead/ci<br/>Lead schema, capabilities, policies"]
54
- opp["@acme/opportunity/ci<br/>Opportunity schema, capabilities, policies"]
55
- qual["@acme/lead-qualification/ci<br/>tool, Skill, Agent, widget"]
56
- conv["@acme/lead-conversion/ci<br/>convert-lead workflow"]
57
- ext --> org
52
+ idci["products/acme/identity/ci<br/>domain, Sales group, external application,<br/>profiles, grants, Studio app"]
53
+ idm["products/acme/identity/model<br/>package identity, VERSION"]
54
+ lead["features/lead/ci<br/>Lead schema, capabilities, policies"]
55
+ opp["features/opportunity/ci<br/>Opportunity schema, capabilities, policies"]
56
+ qual["features/lead-qualification/ci<br/>tool, Skill, Agent, widget"]
57
+ conv["features/lead-conversion/ci<br/>convert-lead workflow"]
58
+ models["model parts<br/>schema FQNs, capability codes, component FQNs"]
59
+ ext --> idci
60
+ ext --> idm
58
61
  ext --> lead
59
62
  ext --> opp
60
63
  ext --> qual
61
64
  ext --> conv
62
- org --> lead
63
- org --> opp
64
- org --> qual
65
+ idci --> idm
66
+ idci -->|"grants by name"| models
67
+ lead --> models
68
+ opp --> models
69
+ qual --> models
65
70
  ```
66
71
 
67
- The template keeps its CI code in three layers. `apps/extensions` is the composition root. It imports the components of `@acme/organization` and the factory of each package `./ci`, and lists every component in deploy order. `@acme/organization` holds the package identity and everything shared across features: the domain, the Sales Group, the external application, the profiles that grant the package capabilities, their grants and the Max Privileges. Each entity or feature package exports a factory from its `./ci` subpath, for example `leadQualificationComponents({ application, audience, version })`, which takes the organization handles and the package version and returns its components in deploy order. A lower layer never imports `@acme/organization`.
72
+ The template keeps its CI code in three places. `apps/extensions` is the CI Extension Package app and the composition root. It imports the Identity Domain components and the factory of each domain's `ci` part, and lists every component in deploy order. The Identity Domain `products/acme/identity` holds everything the product shares. Its `model` part holds the package identity and `VERSION`. Its `ci` part holds the domain, the Sales Group, the external application, the profiles that grant the package capabilities, their grants and the Max Privileges. Each domain exports a factory from its `ci` part, for example `leadQualificationComponents({ application, audience, version })`. The factory takes the Identity Domain handles and the package version, and returns its components in deploy order. A `features` domain never imports a product, and a `ci` part never imports another domain's `ci` part. It names the resources of other domains by the constants in their `model` parts.
68
73
 
69
74
  This is the whole package entry:
70
75
 
71
76
  ```ts
72
- import { convertLeadComponents } from "@acme/lead-conversion/ci"
73
- import {
74
- leadQualificationComponents,
75
- leadScoreCardContributionFqn
76
- } from "@acme/lead-qualification/ci"
77
- import { leadComponents } from "@acme/lead/ci"
78
- import { opportunityComponents } from "@acme/opportunity/ci"
77
+ import { declarePackage } from "@collective-intelligence/extensions-sdk"
78
+ import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
79
+ import { leadComponents } from "@packages/features-lead-ci"
80
+ import { convertLeadComponents } from "@packages/features-lead-conversion-ci"
81
+ import { leadQualificationComponents } from "@packages/features-lead-qualification-ci"
82
+ import { leadScoreCardContributionFqn } from "@packages/features-lead-qualification-model"
83
+ import { opportunityComponents } from "@packages/features-opportunity-ci"
79
84
  import {
80
85
  acmeApplication,
81
86
  crmDomain,
82
- organizationComponents,
83
- packageManifest,
87
+ identityComponents,
84
88
  salesDeskApp,
85
- salesMembers,
89
+ salesMembers
90
+ } from "@packages/products-acme-identity-ci"
91
+ import {
92
+ packageManifest,
86
93
  VERSION
87
- } from "@acme/organization"
88
- import { declarePackage } from "@collective-intelligence/extensions-sdk"
89
- import { declareFrontendCatalogContribution } from "@collective-intelligence/extensions-sdk-frontend"
94
+ } from "@packages/products-acme-identity-model"
90
95
 
91
96
  export default declarePackage({
92
97
  components: [
93
98
  crmDomain,
94
99
  ...leadComponents({ domain: crmDomain, version: VERSION }),
95
100
  ...opportunityComponents({ domain: crmDomain, version: VERSION }),
96
- ...organizationComponents,
101
+ ...identityComponents,
97
102
  ...convertLeadComponents({
98
103
  application: acmeApplication,
99
104
  version: VERSION
@@ -117,19 +122,19 @@ export default declarePackage({
117
122
  })
118
123
  ```
119
124
 
120
- `apps/extensions/src/studio.ts` contains one line, `export { loadFrontendCatalog } from "@acme/organization"`. `ci package build` resolves a relative `load` import against the declaration file, so the contribution is the one declaration in `apps/extensions`. The build ships every export of that module to the browser, so it exports only the catalog loader.
125
+ `apps/extensions/src/studio.ts` exports only `loadFrontendCatalog`. That function gathers the Studio renderers of the `ci` parts under the package identity. Only an app may import several `ci` parts, so the catalog lives in `apps/extensions`. `ci package build` resolves a relative `load` import against the declaration file, so the contribution is the one declaration in `apps/extensions`. The build ships every export of that module to the browser, so it exports only the catalog loader.
121
126
 
122
- One entity package such as `@acme/lead` holds the CI schema in `./ci`, the BFF code in `./server` and the React views in `./views`. The lint rule `ci-solution/subpath-imports` keeps React out of the CI release: `domain/` imports no other subpath, `ci/` imports no `headless/` or `views/`, and `headless/` and `views/` import no `server/`.
127
+ One domain such as `features/lead` keeps each runtime in its own part: the CI schema in `ci`, the BFF code in `server` and the React views in `client`. Each part has one runtime, so `turbo boundaries` keeps React out of the CI release. The `runtime:ci` tag lets a `ci` part import only `ci`, neutral and build packages, and the `part:*` tags stop a part from importing a `server`, `client` or `ci` part.
123
128
 
124
- The template names components `acme.app.<kind>.<name>`, for example `acme.app.tools.lead-score` or `acme.app.workflows.convert-lead`, and the package itself is `acme.app.knowledge`. Each `./ci` subpath exports its FQN constants, and other code imports the constant instead of typing the string again.
129
+ The template names components `acme.app.<kind>.<name>`, for example `acme.app.tools.lead-score` or `acme.app.workflows.convert-lead`, and the package itself is `acme.app.knowledge`. Each domain's `model` part exports its FQN constants, and other code imports the constant instead of typing the string again.
125
130
 
126
131
  A widget needs two declarations. On the backend side, `declareStudioComponent` with `category: "widget"`, a `propsSchema` and a `sourceRef` goes into `components`. On the frontend side, `declareFrontendComponent` with a `load` callback and a `studio_component` target is returned from `loadFrontendCatalog`. The `sourceRef` names the Studio hosted contribution of the package.
127
132
 
128
133
  To add a component to the template:
129
134
 
130
- 1. Declare it in the `./ci` subpath of the package that owns it.
135
+ 1. Declare it in the `ci` part of the domain that owns it. Put its FQN constant in the domain's `model` part when other code names it.
131
136
  2. Add it to `components` in `apps/extensions/src/index.ts` after every component it references.
132
- 3. Bump `VERSION` in `packages/organization/acme/src/package.ts`. The package and every component share this one version.
137
+ 3. Bump `VERSION` in `packages/products/acme/identity/model/src/package.ts`. The package and every component share this one version.
133
138
 
134
139
  ## Lifecycle
135
140
 
@@ -10,7 +10,7 @@ The template keeps the families apart. Package code imports only `extensions-sdk
10
10
 
11
11
  ```mermaid
12
12
  flowchart LR
13
- subgraph pkg["Package: apps/extensions and ./ci subpaths"]
13
+ subgraph pkg["Package: apps/extensions and the ci parts"]
14
14
  decl["Declarations<br/>extensions-sdk"]
15
15
  impl["Tool and connector classes<br/>extensions-sdk-backend"]
16
16
  widget["Studio widgets<br/>extensions-sdk-frontend(-react)"]
@@ -32,7 +32,7 @@ flowchart LR
32
32
  server -->|"confidential credentials"| backend
33
33
  ```
34
34
 
35
- In the template, the left side is `apps/extensions` plus the `./ci` subpath of each entity and feature package. The CLI builds that code into a release and installs it into your Organization. After install, CI runs the backend classes and Studio renders the widgets, so this code never runs in your app.
35
+ In the template, the left side is `apps/extensions` plus the `ci` part of each domain. The CLI builds that code into a release and installs it into your Organization. After install, CI runs the backend classes and Studio renders the widgets, so this code never runs in your app.
36
36
 
37
37
  The right side is `apps/web`. Its browser code talks to its own server through a same-origin proxy, and the server calls CI with the application's confidential credentials. A browser can also call CI directly through the client SDK; in that case your app does not need the server SDK.
38
38
 
@@ -122,7 +122,7 @@ import { useQuery } from "@tanstack/react-query"
122
122
 
123
123
  `external-apps-client-sdk-react` adds `CollectiveIntelligenceProvider`, `CollectiveIntelligenceLoginProvider` and the entity hooks on `/resources`: `useEntityList`, `useEntityRecord`, `useEntityCreate`, `useEntityUpdate` and `useEntityDelete`. A write hook reports `conflict`, `rejected` and `uncertain` as well as `idle`, `pending` and `success`, and `resubmit()` repeats the exact same action when the user asks for it. Install its peers in your app: `react`, `react-dom`, `@tanstack/react-query`, `xstate`, `effect` and `@collective-intelligence/ui-react`.
124
124
 
125
- The template's own pages use the template's shadcn/ui package, `@acme/ui`. `ui-react` appears in the Studio widget and in SDK toasts.
125
+ The template's own pages use the template's shadcn/ui package, `@packages/ui-design-system`. `ui-react` appears in the Studio widget and in SDK toasts.
126
126
 
127
127
  ### Server SDK subpaths an external app uses
128
128
 
@@ -129,7 +129,7 @@ The app's server acts only with the grants that an Organization admin gave to it
129
129
 
130
130
  ## Data policies narrow records
131
131
 
132
- A capability opens a feature. A Knowledge Data Policy decides which records of one schema that capability reaches. Each template entity package declares its capabilities and two policies for its schema in its `./ci`: reading needs `read` on the entity's capabilities, and writing needs `manage`. This is the Lead write policy in `@acme/lead/ci`:
132
+ A capability opens a feature. A Knowledge Data Policy decides which records of one schema that capability reaches. Each template entity domain declares its capabilities and two policies for its schema in its `ci` part: reading needs `read` on the entity's capabilities, and writing needs `manage`. This is the Lead write policy in `@packages/features-lead-ci`:
133
133
 
134
134
  ```ts
135
135
  declareAccessKnowledgeDataPolicy({
@@ -170,7 +170,7 @@ export const managerProfile = declareAccessProfile({
170
170
  })
171
171
  ```
172
172
 
173
- The organization package grants the entity capabilities by the FQN constants that `@acme/lead/ci` and `@acme/opportunity/ci` export. The Sales rep profile holds the same gate with `platform.knowledge`, `platform.agents` and `read` on Leads and Opportunities. It leaves out `platform.workflows` and `manage`.
173
+ The Identity Domain grants the entity capabilities by the FQN constants that `@packages/features-lead-model` and `@packages/features-opportunity-model` export. The Sales rep profile holds the same gate with `platform.knowledge`, `platform.agents` and `read` on Leads and Opportunities. It leaves out `platform.workflows` and `manage`.
174
174
 
175
175
  The gate lets a user in. Max Privileges then limit what the app's user tokens may use, for every caller including tenant users:
176
176
 
@@ -227,7 +227,7 @@ flowchart LR
227
227
  Route --> CI["CI<br/>grants, Max Privileges, policies<br/>for the run and each record"]
228
228
  ```
229
229
 
230
- An Access Requirement is a serializable guard built from `requires`, `enters`, `allOf` and `anyOf`. A feature package exports the requirement of each operation, so the page and the route check the same value. On the server, `CiRuntime.access(cookie)` returns the app's slice of the user's capabilities, and `holds(slice, requirement)` checks one requirement against it. The browser SDK session holds no access data.
230
+ An Access Requirement is a serializable guard built from `requires`, `enters`, `allOf` and `anyOf`. A domain exports the requirement of each operation from its `ci` part, so the page and the route check the same value. On the server, `CiRuntime.access(cookie)` returns the app's slice of the user's capabilities, and `holds(slice, requirement)` checks one requirement against it. The browser SDK session holds no access data.
231
231
 
232
232
  ```tsx
233
233
  const CrmLeaf = async () => {
@@ -245,7 +245,7 @@ Dashboard feature flags such as `organization_onboarding`, `knowledge_setup` and
245
245
  The template's CRM page has a Convert action that starts the convert-lead workflow. Here is how to give it to every Sales member.
246
246
 
247
247
  1. Check what the template does today. `convertLeadRequirement` is `{ mode: "on", requires: "platform.workflows" }`. Only the Sales manager profile allows `core.platform.workflows`, so today only members of Sales managers see Convert and can run it. A member who is only in Sales gets no button, and the BFF route answers 403.
248
- 2. Add `allow(core.platform.workflows)` to `repProfile` in the organization package. The app's Max Privileges already allow `platform.workflows`, so they need no change. Bump `VERSION`, then build, publish, promote and install the package.
248
+ 2. Add `allow(core.platform.workflows)` to `repProfile` in the Identity Domain (`packages/products/acme/identity/ci`). The app's Max Privileges already allow `platform.workflows`, so they need no change. Bump `VERSION`, then build, publish, promote and install the package.
249
249
  3. Know who the run acts as. The BFF route starts the workflow with the signed-in user's delegated token, so the run acts as that user, with the user's current grants, and not as `convertLeadRunner`. The workflow's only node sets a run variable (`converted: true`) and writes no Lead record, so no Knowledge write policy takes part. Confirm it with one trial run as a rep before the demo.
250
250
  4. Sign in as a user who is only in Sales. The CRM page now shows Convert, and `POST /api/leads/:id/convert` answers `{ runId }`. In the Dashboard Check access tab, choose that user and `platform.workflows` to see which grant gives it. Allow up to 60 seconds after a grant change, or wait for the realtime access event to refresh the page.
251
251
 
@@ -111,7 +111,7 @@ The `next-effect-app` template has two composition roots, one for each side of t
111
111
  | `apps/extensions` | Inside CI, installed in the Organization | `extensions-sdk`, `extensions-sdk-backend`, `extensions-sdk-frontend-react`, `ui-react` | `ci package build`, publish, promote and install |
112
112
  | `apps/web` | Your host, as a Next.js app | `external-apps-server-sdk` on the server, `external-apps-client-sdk-react` in the browser | The BFF calls the Application API |
113
113
 
114
- The package root in `apps/extensions` is short. It lists the organization components and each package's `./ci` components in deploy order, with the Lead score card widget for Studio:
114
+ The package root in `apps/extensions` is short. It lists the Identity Domain components and the components of each domain's `ci` part in deploy order, with the Lead score card widget for Studio:
115
115
 
116
116
  ```ts
117
117
  export default declarePackage({
@@ -119,7 +119,7 @@ export default declarePackage({
119
119
  crmDomain,
120
120
  ...leadComponents({ domain: crmDomain, version: VERSION }),
121
121
  ...opportunityComponents({ domain: crmDomain, version: VERSION }),
122
- ...organizationComponents,
122
+ ...identityComponents,
123
123
  ...convertLeadComponents({
124
124
  application: acmeApplication,
125
125
  version: VERSION
@@ -250,7 +250,7 @@ A connection keeps every field that its template marks secret as a secret. A pac
250
250
 
251
251
  ## Code entrypoints
252
252
 
253
- Code in the template imports CI packages and its own workspaces by package name and exported subpath, for example `@acme/lead/views`, and never by relative path. Each subpath has one folder under `src/` with one `index.ts` and one `exports` entry in `package.json`.
253
+ Code in the template imports CI packages and its own workspaces by package name and exported entry, for example `@packages/features-lead-client`, and never by relative path. A CI SDK splits its code by subpath. A template domain splits its code by part: one package for each runtime.
254
254
 
255
255
  ### SDK subpaths
256
256
 
@@ -268,32 +268,30 @@ The SDKs split by where the code runs. [SDKs](../develop/sdks.md) has the full m
268
268
 
269
269
  Every SDK puts its Promise API at the root and its Effect services, Layers, errors and Schemas at `/effect`. `effect` is a required peer of every SDK, so install it next to the SDK and keep one `effect` version in the app. Optional peers such as Next.js, Express, Drizzle, Better Auth and the AI SDK sit behind their own subpaths, so importing the server SDK root never loads them. In the template, `/next` is imported only inside `apps/web/src/server`, because `/next` loads Next.js and `/effect` does not.
270
270
 
271
- ### Template package subpaths
271
+ ### Template domain parts
272
272
 
273
- Each template package exposes up to six subpaths, and each subpath holds one kind of code:
273
+ Each template domain has up to four parts. A part is one package with one runtime:
274
274
 
275
- | Subpath | Holds | Imported by |
276
- | ---------- | ------------------------------------------------------------------------------------------------ | ----------------------------------------- |
277
- | `domain` | Effect Schema models, resource contracts, schema FQNs, pure rules | Every other subpath and other packages |
278
- | `ci` | CI declarations, written as factories over Organization handles | `@acme/organization` |
279
- | `api` | The package `HttpApi` under `/api/app`, its groups and tagged errors | `server`, `headless`, app API composition |
280
- | `server` | The route Layer of the package `HttpApi` and its services | `apps/web/src/server` only |
281
- | `headless` | Typed client, query options, XState machines, entity bindings, Realtime hooks, simulated sources | `views`, the app |
282
- | `views` | Wired React views on `@acme/ui`, with slots for feature parts | The app |
275
+ | Part | Holds | Imported by |
276
+ | -------- | ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------- |
277
+ | `model` | Effect Schema models, resource contracts, pure rules, the domain `HttpApi` under `/api/app`, and the CI names other parts need | the domain's other parts, other domains, the apps |
278
+ | `server` | The route Layer of the domain `HttpApi` and its services | `apps/web/src/server` only |
279
+ | `client` | Typed client, query options, XState machines, entity bindings, Realtime hooks, simulated sources, wired React views | the app |
280
+ | `ci` | CI declarations, written as factories over Identity Domain handles | `apps/extensions` |
283
281
 
284
- Imports point one way. `domain` imports no other subpath, `ci` imports neither `headless` nor `views`, and `headless` and `views` never import `server`. The `ci-solution/subpath-imports` lint rule enforces these rules.
282
+ In one domain, `server`, `client` and `ci` import their own `model` and never each other. Across domains, a part imports only the other domain's `model` part. `turbo boundaries` enforces these rules with the `tier:*`, `runtime:*` and `part:*` tags of each package.
285
283
 
286
- A package exposes only the subpaths it needs. `@acme/lead` has all six, while `@acme/lead-qualification` has only `./ci`, which holds the lead qualifier agent, its Skill, its tool and its Studio widget. The `ci` subpath is where solution code becomes code that CI installs.
284
+ A domain has only the parts it needs. `features/lead` has all four, while `features/lead-qualification` has only `model` and `ci`. Its `ci` part holds the lead qualifier agent, its Skill, its tool and its Studio widget, and its `model` part holds their FQNs. The `ci` part is where solution code becomes code that CI installs.
287
285
 
288
286
  ### Template routes and widgets
289
287
 
290
- The web app has three route files, and each only re-exports handlers from `server/` and the packages:
288
+ The web app has three route files, and each only re-exports handlers from `server/` and the domain parts:
291
289
 
292
- | Route file | Serves |
293
- | ------------------------------------- | ------------------------------------------------------- |
294
- | `app/api/app/[[...path]]/route.ts` | The app's own API, composed from the package `HttpApi`s |
295
- | `app/api/[...path]/route.ts` | The CI BFF: sign-in, Resources, Realtime ticket |
296
- | `app/api/leads/[id]/convert/route.ts` | The fixed convert-lead workflow |
290
+ | Route file | Serves |
291
+ | ------------------------------------- | ------------------------------------------------------ |
292
+ | `app/api/app/[[...path]]/route.ts` | The app's own API, composed from the domain `HttpApi`s |
293
+ | `app/api/[...path]/route.ts` | The CI BFF: sign-in, Resources, Realtime ticket |
294
+ | `app/api/leads/[id]/convert/route.ts` | The fixed convert-lead workflow |
297
295
 
298
296
  Inside CI, a Studio or Dashboard widget enters through a hosted contribution. You write `declareFrontendCatalogContribution({ fqn, host: "studio", load: () => import("./studio") })` and pass it to `declarePackage({ hostedContributions })`. The `load` function stays out of the serialized package manifest, and the loaded module exports `loadFrontendCatalog` for the host.
299
297
 
@@ -8,100 +8,113 @@ What you get from next-effect-app, where each piece of code goes, and how to tak
8
8
 
9
9
  ```bash
10
10
  apps/
11
- web/ # @acme/web Next app: routes, composition, Data Sources, app API and BFF instances
12
- extensions/ # @acme/extensions Extension Package declaration (composition root)
11
+ web/ # @acme/web Next app: routes, composition, Data Sources, app API and BFF instances
12
+ extensions/ # @acme/extensions Extension Package declaration (composes the ci parts)
13
13
  packages/
14
- organization/acme/ # @acme/organization package identity, access, groups, external application
15
- features/intake/ # @acme/intake lead intake: API, store, XState flow, views
16
- features/lead-conversion/ # @acme/lead-conversion convert-lead workflow and browser flow
17
- features/lead-qualification/ # @acme/lead-qualification lead qualifier agent, Skill, tool, Studio widget
18
- entities/lead/ # @acme/lead Lead contract, CI schema, Lead API, Read Port, Realtime, views
19
- entities/opportunity/ # @acme/opportunity Opportunity contract, CI schema, views
20
- modules/identity/ # @acme/identity CI federated auth, CI runtime, principal, login providers
21
- modules/app-api/ # @acme/app-api typed package API client, QueryClient, ApiPrefetch
22
- modules/ui/ # @acme/ui shadcn/ui primitives, AI Elements, theme, workspace-kit
23
- tooling/config/ # @acme/config shared TypeScript base config
14
+ products/acme/identity/{model,ci} # Identity Domain: package identity and VERSION, access, groups, external application, Sales desk
15
+ features/lead/{model,server,client,ci} # Lead contract and CI names, Lead API and Read Port, Realtime and views, CI schema
16
+ features/opportunity/{model,client,ci} # Opportunity contract and CI names, views, CI schema
17
+ features/intake/{model,server,client} # lead intake: schemas and API, store, XState flow and views
18
+ features/lead-conversion/{client,ci} # convert-lead browser flow and Workflow
19
+ features/lead-qualification/{model,ci} # lead qualifier agent, Skill, tool, Studio widget, and their FQNs
20
+ modules/identity-{api,server,client} # principal and Authentication contract, CI runtime, login providers
21
+ modules/app-api, app-api-server # typed domain API client, QueryClient, simulated network; ApiPrefetch
22
+ ui/design-system/ # shadcn/ui primitives, AI Elements, theme, workspace-kit
23
+ tooling/config/ # shared TypeScript base config and the Layout Guard
24
24
  ```
25
25
 
26
- Intake is a form with an XState flow and an app API that keeps its data in an in-memory store. Lead conversion is a Fixed workflow started by a single-action task. Lead qualification is an agent with a Skill, a tool and a Studio widget. The repository has no docs wiki, no infra folder and no generated client code, because the browser derives each typed client from its package `HttpApi` at runtime. It also ships an agent harness: an `AGENTS.md` per scope, and `.agents/` with skills, rules and lint scripts.
26
+ Intake is a form with an XState flow and an app API that keeps its data in an in-memory store. Lead conversion is a Fixed workflow started by a single-action task. Lead qualification is an agent with a Skill, a tool and a Studio widget. The repository has no docs wiki, no infra folder and no generated client code, because the browser derives each typed client from its domain `HttpApi` at runtime. It also ships an agent harness: an `AGENTS.md` per scope, and `.agents/` with skills, rules and lint scripts.
27
27
 
28
- ## Tiers and the import rule
28
+ ## Domains, parts and the import rules
29
29
 
30
- Every package lives at `packages/<tier>/<name>`, keeps a flat name (`@acme/<name>`) and has exactly one `tier:*` tag in its own `turbo.json`. The six tiers, from top to bottom, are `app` (the composition roots), `organization` (package identity, access, groups, external application and deploy order), `features` (one user-visible capability each), `entities` (one business entity each), `modules` (business-agnostic machinery) and `tooling` (the shared tsconfig base).
30
+ The template groups its code by domain. One domain is one folder, and each runtime of the domain is its own package, a part. The folder directly below `packages/` is the kind:
31
+
32
+ | Kind | Holds |
33
+ | ------------------------------------ | ---------------------------------------------------------- |
34
+ | `features/<domain>/<part>` | a domain that names no product, such as `lead` or `intake` |
35
+ | `products/<product>/<domain>/<part>` | a domain of one product; it may name its product |
36
+ | `ui/<name>` | the design system and page blocks, with no product terms |
37
+ | `modules/<name>` | business-agnostic machinery with one runtime |
38
+ | `tooling/<name>` | TypeScript, lint, build and test configuration |
39
+
40
+ A domain has only the parts it needs, and each part has exactly one runtime:
41
+
42
+ | Part | Runtime | Holds |
43
+ | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
44
+ | `model` | neutral | Effect Schema models, resource contracts, pure rules, the domain `HttpApi` under `/api/app`, and the CI names other parts need |
45
+ | `server` | server | the route Layer of the domain `HttpApi` and its services; only `apps/web/src/server` imports it |
46
+ | `client` | client | typed client, query options, XState machines, entity bindings, Realtime topics and hooks, simulated sources, wired React views |
47
+ | `ci` | ci | CI declarations (extensions SDK) as factories over Identity Domain handles |
48
+
49
+ A package name is `@packages/` plus its path below `packages/`, with `-` in place of `/`. For example, `packages/features/lead/client` is `@packages/features-lead-client`. The apps keep their own names. Every internal dependency uses `workspace:*`. A part exports `.`, and a `client` part adds `./headless` only when a consumer needs state without components.
31
50
 
32
51
  ```mermaid
33
52
  flowchart TD
34
53
  web["apps/web"]
35
54
  ext["apps/extensions"]
36
- org["organization<br/>@acme/organization"]
37
- subgraph features["features"]
38
- f1["intake"]
39
- f2["lead-conversion"]
40
- f3["lead-qualification"]
55
+ subgraph identity["products/acme/identity"]
56
+ im["model"]
57
+ ic["ci"]
41
58
  end
42
- subgraph entities["entities"]
43
- e1["lead"]
44
- e2["opportunity"]
59
+ subgraph lead["features/lead"]
60
+ lm["model"]
61
+ ls["server"]
62
+ lc["client"]
63
+ lci["ci"]
45
64
  end
46
- subgraph modules["modules"]
47
- m1["identity"]
48
- m2["app-api"]
49
- m3["ui"]
65
+ subgraph conv["features/lead-conversion"]
66
+ cc["client"]
67
+ cci["ci"]
50
68
  end
51
- tooling["tooling<br/>config"]
52
- web --> org
53
- ext -->|"lists CI declarations in deploy order"| org
54
- ext -->|"lists each ./ci"| features
55
- org -->|"grants package capabilities"| features
56
- features --> entities
57
- entities --> modules
58
- modules --> tooling
59
- f1 -.-|"never imports"| f2
60
- e1 -.-|"never imports"| e2
69
+ modules["modules, ui, tooling"]
70
+ web -->|"composes server and client parts"| ls
71
+ web --> lc
72
+ web --> cc
73
+ ext -->|"lists each ci part in deploy order"| lci
74
+ ext --> cci
75
+ ext --> ic
76
+ ic -->|"grants by the names in model parts"| lm
77
+ ls --> lm
78
+ lc --> lm
79
+ lci --> lm
80
+ cc -->|"another domain's model only"| lm
81
+ lc --> modules
82
+ lc -.-|"never imports"| cc
61
83
  ```
62
84
 
63
- Imports point down the tiers and may skip a tier. Inside one tier, only modules and tooling packages import each other. A feature never imports another feature and an entity never imports another entity. When two of them must work together, a page in `apps/web` connects them.
85
+ - In one domain, `server`, `client` and `ci` import their own `model`. They never import each other.
86
+ - Across domains, a part imports only the other domain's `model` part. The `server`, `client` and `ci` parts of different domains meet only in an app: `apps/web` composes the views, and `apps/extensions` composes the `ci` parts.
87
+ - `features`, `ui` and `modules` never import `products`. A product never imports another product.
88
+ - `ui` imports only `ui` and `tooling`. `modules` imports only `modules` and `tooling`.
64
89
 
65
- The arrows are real configuration. The root `turbo.json` lists, for each tag, the tags it may depend on, and `bunx turbo boundaries` fails the build on a wrong import:
90
+ The rules are real configuration. Each workspace `turbo.json` has the Boundary Tags of its place: one `tier:*` tag, one `runtime:*` tag (apps have none), and one `part:*` tag for a part. The root `turbo.json` holds one rule for each tag, and `bunx turbo boundaries` fails the build on a wrong import:
66
91
 
67
92
  ```json
68
- "tier:features": { "dependencies": { "allow": ["tier:entities", "tier:modules", "tier:tooling"] } },
69
- "tier:entities": { "dependencies": { "allow": ["tier:modules", "tier:tooling"] } },
70
- "tier:modules": { "dependencies": { "allow": ["tier:modules", "tier:tooling"] } }
93
+ "tier:features": { "dependencies": { "allow": ["tier:features", "tier:ui", "tier:modules", "tier:tooling"] } },
94
+ "runtime:client": { "dependencies": { "deny": ["runtime:server", "runtime:ci"] } },
95
+ "part:client": { "dependencies": { "deny": ["part:server", "part:client", "part:ci"] } }
71
96
  ```
72
97
 
73
- Workspaces import each other by package name and exported subpath, such as `@acme/lead/views`, and never by relative path.
98
+ The full table is `BOUNDARY_TAGS` from `@collective-intelligence/lint/layout`. The `part:*` rules deny every `server`, `client` and `ci` part, so a part reaches only `model` parts. An app has no `part:*` tag, so the parts of different domains meet there.
74
99
 
75
- ## Package subpaths
100
+ Workspaces import each other by package name and exported entry, such as `@packages/features-lead-client`, and never by relative path.
76
101
 
77
- A feature or entity package exposes only the subpaths it needs. Each subpath is a folder under `src/` with one `index.ts` and one `exports` entry in `package.json`.
102
+ The template has these domains:
78
103
 
79
- | Subpath | Holds | Imported by |
80
- | ---------- | ----------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
81
- | `domain` | Effect Schema models, resource contracts, schema FQNs, pure rules | every other subpath and other packages |
82
- | `ci` | CI declarations (extensions SDK) as factories over organization handles | `apps/extensions`, `@acme/organization` |
83
- | `api` | the package `HttpApi` under `/api/app`, its groups and tagged errors | `server`, `headless`, the app API composition |
84
- | `server` | the route Layer of the package `HttpApi` and its services | `apps/web/src/server` only |
85
- | `headless` | typed client, query options, XState machines, entity bindings, Realtime topics and hooks, simulated sources | `views` and the app |
86
- | `views` | wired React views on `@acme/ui`; feature parts enter through slots | the app |
104
+ | Domain | Parts |
105
+ | ----------------------------- | --------------------------------- |
106
+ | `features/lead` | `model`, `server`, `client`, `ci` |
107
+ | `features/opportunity` | `model`, `client`, `ci` |
108
+ | `features/intake` | `model`, `server`, `client` |
109
+ | `features/lead-conversion` | `client`, `ci` |
110
+ | `features/lead-qualification` | `model`, `ci` |
111
+ | `products/acme/identity` | `model`, `ci` |
87
112
 
88
- Inside a package the subpaths also have a direction. `domain` imports no other subpath, `ci` imports neither `headless` nor `views`, and `headless` and `views` never import `server`. That keeps server code out of the browser bundle and keeps CI declarations free of React.
113
+ `features/lead-qualification` adds an agent, a Skill, a tool and a Studio widget, and all of that is CI-side behavior. Its `model` holds only the FQNs, and its `ci` part holds the declarations. That shows that you can ship an AI capability without writing any web code.
89
114
 
90
- Each template package exposes a different set:
115
+ ## Domains take their audience as a parameter
91
116
 
92
- | Package | Subpaths |
93
- | -------------------------- | ------------------------------------- |
94
- | `@acme/lead` | `domain ci api server headless views` |
95
- | `@acme/opportunity` | `domain ci headless views` |
96
- | `@acme/intake` | `domain api server headless views` |
97
- | `@acme/lead-conversion` | `ci headless views` |
98
- | `@acme/lead-qualification` | `ci` |
99
-
100
- `@acme/lead-qualification` adds an agent, a Skill, a tool and a Studio widget, and all of that is CI-side behavior. Its single `./ci` subpath shows that you can ship an AI capability without writing any web code.
101
-
102
- ## Features take their audience as a parameter
103
-
104
- A feature package must not import `@acme/organization`, because organization sits above it in the tiers. A feature that offers something to a group of users therefore takes that `audience`, and the application handle, as parameters. The organization package owns the groups, the application and the profiles; each entity package declares its own capabilities and Knowledge Data Policies, and the profiles grant them by the FQN constants of `@acme/lead/ci` and `@acme/opportunity/ci`. `apps/extensions/src/index.ts` passes the organization handles in and lists every component in deploy order, where each component follows the components it references:
117
+ `products/acme/identity` is the Identity Domain of the product `acme`. Its `model` part holds the package identity and `VERSION`. Its `ci` part holds the groups, the application, the Access Profiles, their grants and the Max Privileges. A `features` domain never imports a product, so a `ci` part that offers something to a group of users takes that `audience`, and the application handle, as parameters. Each domain declares its own capabilities and Knowledge Data Policies in its `ci` part. The profiles grant them by the FQN constants of `@packages/features-lead-model` and `@packages/features-opportunity-model`. `apps/extensions/src/index.ts` passes the Identity Domain handles in and lists every component in deploy order, where each component follows the components it references:
105
118
 
106
119
  ```ts
107
120
  export default declarePackage({
@@ -109,7 +122,7 @@ export default declarePackage({
109
122
  crmDomain,
110
123
  ...leadComponents({ domain: crmDomain, version: VERSION }),
111
124
  ...opportunityComponents({ domain: crmDomain, version: VERSION }),
112
- ...organizationComponents,
125
+ ...identityComponents,
113
126
  ...convertLeadComponents({
114
127
  application: acmeApplication,
115
128
  version: VERSION
@@ -126,21 +139,21 @@ export default declarePackage({
126
139
  })
127
140
  ```
128
141
 
129
- `organizationComponents` holds the Sales Group, the application, the profiles, their grants and the Max Privileges. The Studio contribution is the one declaration in `apps/extensions`: `ci package build` resolves its relative `load` import against that file.
142
+ `identityComponents` holds the Sales Group, the application, the profiles, their grants and the Max Privileges. The Studio contribution is the one declaration in `apps/extensions`: `ci package build` resolves its relative `load` import against that file.
130
143
 
131
144
  [Extensions](../develop/extensions.md) describes each kind of declaration, and [Access](../platform/access.md) explains the Access Profiles and Access Grants in that list.
132
145
 
133
146
  ## The web app layers
134
147
 
135
- Entity and feature code lives in packages. The web app keeps only routes, Composition, the sign-in gate, Data Sources and server instances, arranged in a fixed set of layers where each layer imports only the layers below it:
148
+ Domain code lives in the domain parts. The web app keeps only routes, Composition, the sign-in gate, Data Sources and server instances, arranged in a fixed set of layers where each layer imports only the layers below it:
136
149
 
137
- | Layer in `apps/web/src` | Holds |
138
- | ----------------------- | --------------------------------------------------------------------------------------------------------------------- |
139
- | `app/` | route files only; each re-exports a Composition export, and `app/api/**` forwards to `server/<domain>/server` |
140
- | `composition/` | `providers/` (global providers, Realtime providers) and `routing/` (access, shells, pages) |
141
- | `features/` | app-local capabilities: their Data Sources (`remote/server.ts`) and `page-link/` |
142
- | `entities/` | app-local entity machinery that several features need (the CI session), Data Sources of entity packages, `page-link/` |
143
- | `server/` | beside the layers: one folder per domain, where `server.ts` (`server-only`) holds the process instance |
150
+ | Layer in `apps/web/src` | Holds |
151
+ | ----------------------- | ------------------------------------------------------------------------------------------------------------------ |
152
+ | `app/` | route files only; each re-exports a Composition export, and `app/api/**` forwards to `server/<domain>/server` |
153
+ | `composition/` | `providers/` (global providers, Realtime providers) and `routing/` (access, shells, pages) |
154
+ | `features/` | app-local capabilities: their Data Sources (`remote/server.ts`) and `page-link/` |
155
+ | `entities/` | app-local entity machinery that several features need (the CI session), Data Sources of domain parts, `page-link/` |
156
+ | `server/` | beside the layers: one folder per domain, where `server.ts` (`server-only`) holds the process instance |
144
157
 
145
158
  Only Composition imports a Data Source, and only Data Sources and `app/api/**` import a `server/<domain>/server.ts`. Peers still meet without importing each other: the CRM page template passes `ConvertLead` into the `selectionActions` slot of `LeadWorkspace` and `LeadAttachment` into its `editorActions` slot. Each page's owner gives its `{ label, path }` in `page-link/`, and shells and links read it, so no route path is written twice.
146
159
 
@@ -148,7 +161,7 @@ One Next app serves two server surfaces:
148
161
 
149
162
  | Path | Handler | What it is |
150
163
  | ------------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------ |
151
- | `/api/app/*` | `server/app-api/server` | the app API: the packages' Effect `HttpApi`s merged, OpenAPI at `/api/app/openapi.json`, Scalar docs at `/api/app/docs` |
164
+ | `/api/app/*` | `server/app-api/server` | the app API: the domains' Effect `HttpApi`s merged , OpenAPI at `/api/app/openapi.json`, Scalar docs at `/api/app/docs` |
152
165
  | `/api/*` | `server/ci/server` | the CI SDK BFF: sign-in with a sealed cookie, Lead and Opportunity resource proxy, Realtime ticket and revalidate routes |
153
166
  | `/api/leads/[id]/convert` | `server/ci/server` | the Fixed convert-lead workflow route |
154
167
 
@@ -157,7 +170,7 @@ The BFF holds the CI session in a sealed cookie and proxies resource calls, so t
157
170
  ## Start a new demo
158
171
 
159
172
  1. Generate a repository with **Use this template** on the template repository. In the new repository, delete the README "Contributing" section and `.github/workflows/close-pull-requests.yml`, which only matter in the template repository itself.
160
- 2. Rename the template for the customer. Replace the `@acme/` package scopes and the `acme.app.` FQNs, replace `https://acme.localhost` in `packages/organization/acme/src/application.ts` and `.env.example`, and replace the theme tokens and the sidebar brand in `apps/web/src/composition/routing/shells/workspace/app-sidebar.tsx`. Theme tokens live once, in `packages/modules/ui/src/styles/globals.css`.
173
+ 2. Rename the template for the customer. Replace the `@acme/` app names, the product folder `packages/products/acme` with its package names `@packages/products-acme-*`, and the `acme.app.` FQNs. Replace `https://acme.localhost` in `packages/products/acme/identity/ci/src/application.ts` and `.env.example`, and replace the theme tokens and the sidebar brand in `apps/web/src/composition/routing/shells/workspace/app-sidebar.tsx`. Theme tokens live once, in `packages/ui/design-system/src/styles/globals.css`.
161
174
  3. Run it locally. The Overview and Lead intake pages work with no configuration, because the intake API keeps requests in memory:
162
175
 
163
176
  ```bash
@@ -226,22 +239,22 @@ The BFF holds the CI session in a sealed cookie and proxies resource calls, so t
226
239
 
227
240
  ## What to change and what to keep
228
241
 
229
- A new demo changes the organization package, the entities, the features, the theme and the origins. It keeps `modules/identity`, `modules/app-api`, the BFF and server wiring, the tier tags, the lint configuration and the harness files, because they hold no business logic. A new environment variable goes into `apps/web/.env.example`, `packages/modules/identity/src/server/env.ts`, `turbo.json` `globalEnv` and the README tenant section together.
242
+ A new demo changes the Identity Domain, the `features` domains, the theme and the origins. It keeps the `modules/identity-*` and `modules/app-api*` packages, the BFF and server wiring, the Boundary Tags, the Layout Guard, the lint configuration and the harness files, because they hold no business logic. A new environment variable goes into `apps/web/.env.example`, `packages/modules/identity-server/src/env.ts`, `turbo.json` `globalEnv` and the README tenant section together.
230
243
 
231
244
  ## Checks that keep the structure honest
232
245
 
246
+ Three checks keep the layout. `turbo boundaries` checks every import against the Boundary Tags. The Layout Guard, the Bun test `packages/tooling/config/src/workspace-layout.test.ts`, checks what the tags cannot express: the root `workspaces` globs, package names, each `turbo.json`, `workspace:*` ranges and product isolation. The `ci-solution/workspace-layout` lint rule reports a package that sits outside the accepted places. All three read one layout definition, `@collective-intelligence/lint/layout`.
247
+
233
248
  `@collective-intelligence/lint` is one Oxlint plugin named `ci-solution`. Extending `recommended` turns every rule on as an error:
234
249
 
235
- | Rule | Checks |
236
- | -------------------------------- | ---------------------------------------------------------------------------------- |
237
- | `ci-solution/package-entrypoint` | an import of another package targets an entrypoint in its `package.json` `exports` |
238
- | `ci-solution/subpath-imports` | imports between subpath folders follow the allowed direction |
239
- | `ci-solution/subpath-entrypoint` | an import of another subpath folder targets its index file |
240
- | `ci-solution/subpath-index` | every subpath folder has `index.ts` or `index.tsx` |
241
- | `ci-solution/effect-subpath` | SDK Effect APIs come from the SDK `/effect` subpath |
242
- | `ci-solution/no-run-in-view` | a view module calls no `fetch` and runs no Effect |
243
- | `ci-solution/effect-actors` | XState side-effect actors are `fromEffect` actors |
244
- | `ci-solution/effect-writes` | no module uses TanStack Query `useMutation`; writes run in `fromEffect` actors |
250
+ | Rule | Checks |
251
+ | -------------------------------- | ---------------------------------------------------------------------------------------------- |
252
+ | `ci-solution/package-entrypoint` | an import of another package targets an entrypoint in its `package.json` `exports` |
253
+ | `ci-solution/workspace-layout` | each workspace sits at `apps/<name>`, a domain part, or `packages/{ui,modules,tooling}/<name>` |
254
+ | `ci-solution/effect-subpath` | SDK Effect APIs come from the SDK `/effect` subpath |
255
+ | `ci-solution/no-run-in-view` | a view module calls no `fetch` and runs no Effect |
256
+ | `ci-solution/effect-actors` | XState side-effect actors are `fromEffect` actors |
257
+ | `ci-solution/effect-writes` | no module uses TanStack Query `useMutation`; writes run in `fromEffect` actors |
245
258
 
246
259
  Each package has an `oxlint.local.ts` that extends the preset:
247
260
 
@@ -264,14 +277,14 @@ The web app also runs a `frontend-layers` lint for layer order, domain entrypoin
264
277
 
265
278
  ```bash
266
279
  bun run check-types
267
- bun run test
280
+ bun run test # includes the Layout Guard
268
281
  bunx turbo boundaries
269
282
  bun run lint
270
283
  bun run format:check
271
284
  bun run build
272
285
  ```
273
286
 
274
- When you change the Lead cache, a Lead write or Lead Realtime, also run `bun run check:models` in `packages/entities/lead`. [State machines](state-machines.md) explains what that command checks.
287
+ When you change the Lead cache, a Lead write or Lead Realtime, also run `bun run check:models` in `packages/features/lead/client`. [State machines](state-machines.md) explains what that command checks.
275
288
 
276
289
  ## Related pages
277
290
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  How next-effect-app models UI flows as XState machines with Effect actors, keeps server data in the QueryCache, resends uncertain writes safely, and checks hard flows with Models.
4
4
 
5
- In `next-effect-app`, a UI flow that carries business logic is an XState machine in the `headless/` folder of its package, at `headless/<flow>-machine.ts`. Flows that belong only to the web app live at `apps/web/src/{features,entities}/<domain>/<flow>-machine.ts`. The machine decides where the flow is: editing, reviewing, submitting, failed. Every side effect is an Effect program that the machine runs as an actor, and TanStack Query owns the remote data that those programs read and write.
5
+ In `next-effect-app`, a UI flow that carries business logic is an XState machine in the `src/headless/` folder of its domain's `client` part, at `src/headless/<flow>-machine.ts`. Flows that belong only to the web app live at `apps/web/src/{features,entities}/<domain>/<flow>-machine.ts`. The machine decides where the flow is: editing, reviewing, submitting, failed. Every side effect is an Effect program that the machine runs as an actor, and TanStack Query owns the remote data that those programs read and write.
6
6
 
7
7
  The machine context holds flow state only and never an API response. Two views that show the same record therefore read one cache entry, and no machine keeps a copy that can go stale. Server Components never run machines or Effects; they await a Promise boundary, and machines exist only in client code.
8
8
 
@@ -72,7 +72,7 @@ submitting: {
72
72
 
73
73
  Leaving the invoking state interrupts the Effect fiber. The machine has no UI of its own: `submitted` is a typed action, and the view provides the toast with `machine.provide({ actions })`. The view runs `useMachine(intakeMachine.provide(...), { input: { runtime } })` and renders by `snapshot.matches("editing")`, `matches("submitting")` and `matches("done")`.
74
74
 
75
- The same `provide` call swaps the data source for a demo without a backend. A simulated source lives in `headless/simulated-*.ts`, built with `simulate("<pace>", effect)` from `@acme/app-api`, and only Composition or a test selects it. Tests use the same mechanism. A test drives the machine on a `ManagedRuntime` of the SDK `makeTestQueryCache` layer, never a hand-made `QueryCache` double, and asserts on cache entries or recorded calls:
75
+ The same `provide` call swaps the data source for a demo without a backend. A simulated source lives in `headless/simulated-*.ts`, built with `simulate("<pace>", effect)` from `@packages/modules-app-api`, and only Composition or a test selects it. Tests use the same mechanism. A test drives the machine on a `ManagedRuntime` of the SDK `makeTestQueryCache` layer, never a hand-made `QueryCache` double, and asserts on cache entries or recorded calls:
76
76
 
77
77
  ```ts
78
78
  const cache = makeTestQueryCache({ seed: [[intakeRequestsQuery.queryKey, []]] })
@@ -160,7 +160,7 @@ stateDiagram-v2
160
160
  done --> running: RUN with a new file
161
161
  ```
162
162
 
163
- The steps inside `running` are steps of the Effect program, and the machine itself sees one `running` state. A resubmit skips the upload and sends only the final write. The size and type checks use `leadAttachmentAccepts` and `leadAttachmentMaxBytes` (5 MiB) from `@acme/lead/domain`. The CI schema declares the same values on the File field, so CI refuses a larger upload too, while a file that fails the local check sends nothing.
163
+ The steps inside `running` are steps of the Effect program, and the machine itself sees one `running` state. A resubmit skips the upload and sends only the final write. The size and type checks use `leadAttachmentAccepts` and `leadAttachmentMaxBytes` (5 MiB) from `@packages/features-lead-model`. The CI schema declares the same values on the File field, so CI refuses a larger upload too, while a file that fails the local check sends nothing.
164
164
 
165
165
  The write that might need a resend is a value the failure carries:
166
166
 
@@ -224,7 +224,7 @@ A Model is a `*.proof.ts` TypeScript module that states the state, actions and i
224
224
  | `/** @constraint */` | a bound, so the search ends |
225
225
  | `ghost` prefix on a `let` | records what a consumer saw, only to state a guarantee |
226
226
 
227
- The Lead Realtime Model in `packages/entities/lead` is trimmed here. The full file also has `writeConfirm`, `otherWrite`, `realtimeChange` and `neverBehindConfirmed`:
227
+ The Lead Realtime Model in `packages/features/lead/client/src/headless/lead-realtime.proof.ts` is trimmed here. The full file also has `writeConfirm`, `otherWrite`, `realtimeChange` and `neverBehindConfirmed`:
228
228
 
229
229
  ```ts
230
230
  let server: Revision = 0
@@ -260,7 +260,7 @@ export const isRefetchDue = () => refetchDue && !isFresh()
260
260
  The checker visits 22 states and proves two things. A Realtime refetch never hides the tab's pending optimistic write (`pendingWriteShown`, `neverBehindConfirmed`), and after a Realtime change the views eventually reach the stored revision (`@leadsTo isFresh`). The package runs it with one script:
261
261
 
262
262
  ```bash
263
- cd packages/entities/lead
263
+ cd packages/features/lead/client
264
264
  bun run check:models
265
265
  ```
266
266
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@collective-intelligence/extensions-sdk-frontend-react",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Public hosted React contribution contracts for Collective Intelligence extensions.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -80,11 +80,11 @@
80
80
  "type-check": "bun check --no-script -p tsconfig.json && bun check --no-script -p tsconfig.type-tests.json"
81
81
  },
82
82
  "dependencies": {
83
- "@collective-intelligence/extensions-sdk": "0.6.0",
84
- "@collective-intelligence/extensions-sdk-frontend": "0.6.0"
83
+ "@collective-intelligence/extensions-sdk": "0.7.0",
84
+ "@collective-intelligence/extensions-sdk-frontend": "0.7.0"
85
85
  },
86
86
  "peerDependencies": {
87
- "@collective-intelligence/ui-react": "0.6.0",
87
+ "@collective-intelligence/ui-react": "0.7.0",
88
88
  "@tanstack/react-query": ">=5 <6",
89
89
  "@xyflow/react": ">=12 <13",
90
90
  "effect": "^4.1.0",
@@ -101,7 +101,7 @@
101
101
  "access": "public"
102
102
  },
103
103
  "devDependencies": {
104
- "@collective-intelligence/ui-react": "0.6.0",
104
+ "@collective-intelligence/ui-react": "0.7.0",
105
105
  "@effect/eslint-plugin": "0.3.2",
106
106
  "@effect/vitest": "4.1.4",
107
107
  "@hey-api/openapi-ts": "^0.96.0",
@@ -129,5 +129,5 @@
129
129
  "vitest": "5.0.2",
130
130
  "xstate": "5.33.3"
131
131
  },
132
- "gitHead": "94535cc59ece904d4a9374a368edb09222688bb6"
132
+ "gitHead": "e387355aacb167f048998872edebc78d4c669d8d"
133
133
  }