@membranehq/cli 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -2
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var pr=Object.defineProperty;var l=(n,e)=>pr(n,"name",{value:e,configurable:!0});import{jsxs as L,jsx as g}from"react/jsx-runtime";import*as H from"node:path";import{resolve as mr,dirname as yr,join as gr}from"node:path";import{useInput as ht,Box as O,Text as v,Newline as wr,render as br}from"ink";import Sr from"minimist";import{SWRConfig as kr}from"swr";import{exec as Cr}from"node:child_process";import{useState as B,useEffect as tn,createContext as nn,useContext as sn,useCallback as rs}from"react";import*as M from"node:fs";import{readFileSync as vr}from"node:fs";import*as Ar from"node:crypto";import{createHash as Tr}from"node:crypto";import*as Or from"node:os";import{TextInput as Er,Select as $r}from"@inkjs/ui";import rn from"ink-spinner";import os from"swr/immutable";import se from"js-yaml";import{z as F}from"zod";import Ir from"ink-text-input";import Nr from"os";import j from"path";import Lr from"conf";import{WorkspaceElementSpecs as ie,WorkspaceElementType as I,IntegrationAppClient as pt,setValueAtLocator as on,extractIntegrationAppErrorData as re,getDataCollectionCreateFields as an,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as mt,getRequiredFieldsFromSchema as _r,getValueAtLocator as Pr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as cn}from"@integration-app/sdk";import Ye from"jsonwebtoken";import{EventEmitter as xr}from"node:events";import jr from"chokidar";import k from"chalk";import{fileURLToPath as Kr}from"node:url";import{Command as Dr}from"commander";import ln from"axios";import{FastMCP as Mr}from"fastmcp";import P from"fs";import Rr from"archiver";import Br from"form-data";import Fr from"unzipper";import un from"lodash/merge.js";import qr from"@anthropic-ai/sdk";import{faker as Ze}from"@faker-js/faker";import Ur from"lodash/template.js";import Jr from"lodash/templateSettings.js";const fn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(M.existsSync(n))try{t=JSON.parse(M.readFileSync(n,"utf8"))}catch{t={}}const s={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return M.writeFileSync(n,JSON.stringify(s,null,2)),`MCP server configuration added to ${n}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".cursor"),e=H.join(n,"mcp.json");M.existsSync(n)||M.mkdirSync(n);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let s={};if(M.existsSync(e))try{s=JSON.parse(M.readFileSync(e,"utf8"))}catch{s={}}const i={...s,mcpServers:{...s.mcpServers,...t.mcpServers}};return M.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}],Vr=l(({onExit:n,onComplete:e})=>{const[t,s]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[d,f]=B("");ht((w,p)=>{if(c||d){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)n();else if(p.upArrow||w==="k")s(Math.max(0,t-1));else if(p.downArrow||w==="j")s(Math.min(fn.length-1,t+1));else if(p.return||w===" "){const y=fn[t];a(y),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"green",children:"Success"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"green",children:c}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(O,{marginTop:1,paddingLeft:2,children:g(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"red",children:"Error"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:g(v,{color:"red",children:d})}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Confirmation"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[L(v,{children:["Connect ",g(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,children:g(v,{color:"yellow",bold:!0,children:o.actionDescription})}),g(O,{marginTop:2,marginBottom:1,children:L(v,{children:[g(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Select Agent"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,flexDirection:"column",children:fn.map((w,p)=>L(O,{children:[L(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),L(v,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})},"AddMcpServerScreen"),fe=H.join(Or.tmpdir(),"membrane-mcp-status"),us=3e4;function dn(n){return Tr("md5").update(n).digest("hex").slice(0,8)}l(dn,"getCwdHash");function hn(n,e){const t=dn(e);return H.join(fe,`mcp-${t}-${n}.json`)}l(hn,"getStatusFilePath");function Te(n,e){try{const t=e||process.cwd();if(!n){const i=yt(t);return i.length===0?null:i[0]}const s=hn(n,t);if(M.existsSync(s)){const i=M.statSync(s),r=new Date;if(r.getTime()-i.mtime.getTime()>us)return Qe(n,t),null;const a=M.readFileSync(s,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>us)return Qe(n,t),null}return c}}catch{n&&e&&Qe(n,e)}return null}l(Te,"getMcpStatus");function yt(n){try{const e=n||process.cwd(),t=dn(e);if(!M.existsSync(fe))return[];const s=M.readdirSync(fe),i=[];for(const r of s){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=Te(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yt,"getAllMcpStatusFiles");function pn(n){try{const t={...Te(n.processId,n.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:n.processId,cwd:n.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...n};M.existsSync(fe)||M.mkdirSync(fe,{recursive:!0});const s=hn(n.processId,n.cwd);M.writeFileSync(s,JSON.stringify(t,null,2))}catch{}}l(pn,"updateMcpStatus");function Qe(n,e){try{const t=e||process.cwd();if(n){const s=hn(n,t);M.existsSync(s)&&M.unlinkSync(s)}else{const s=dn(t);if(M.existsSync(fe)){const i=M.readdirSync(fe);for(const r of i)r.match(new RegExp(`^mcp-${s}-\\d+\\.json$`))&&M.unlinkSync(H.join(fe,r))}}}catch{}}l(Qe,"clearMcpStatus");function Wr(n,e){const t=Te(n,e);t&&pn({processId:n,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(Wr,"trackToolExecution");function zr(){const[n,e]=B(Te()),[t,s]=B(yt()),[i,r]=B(null);return tn(()=>{try{const a=process.cwd();e(Te(void 0,a)),s(yt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),s([])}const o=setInterval(()=>{try{const a=process.cwd(),c=Te(void 0,a),u=yt(a);e(c),s(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),s([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:n,allMcpServers:t,error:i,isRunning:n?.isRunning||!1,toolsCount:n?.toolsCount||0,totalRequests:n?.totalRequests||0,lastActivity:n?.lastActivity,processId:n?.processId,serverCount:t.length}}l(zr,"useMcpStatus");const Hr=l(()=>{const n=Math.min(100,process.stdout.columns||100),{error:e,serverCount:t,allMcpServers:s}=zr();return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(O,{marginTop:-1,marginBottom:0,flexDirection:"column",children:L(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",e?g(v,{color:"red",children:"error reading status"}):t===0?g(v,{color:"yellow",children:"none"}):g(v,{color:"green",children:t})]})}),!e&&t===0&&g(O,{marginTop:1,children:L(v,{color:"grey",children:["Connect your AI agents to Membrane.",g(wr,{}),"It will give them tools and context to build integrations."]})}),s.length>0&&g(O,{flexDirection:"column",paddingLeft:2,marginTop:1,children:s.map((i,r)=>g(O,{children:L(v,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[a: connect an agent]"})})]})},"AgentStatus"),fs=nn(process.cwd());function Gr({cwd:n,children:e}){return g(fs.Provider,{value:n,children:e})}l(Gr,"CwdProvider");function mn(){return sn(fs)}l(mn,"useCwd");const Yr="membrane.config.yml";function de(n){const e=H.join(n??process.cwd(),Yr);try{const t=M.readFileSync(e,"utf8"),s=se.load(t),i=ds.safeParse(s);return i.success?i.data:null}catch{return null}}l(de,"readProjectConfig");const Zr="membrane.config.yml",ds=F.object({workspaceKey:F.string().optional(),workspaceSecret:F.string().optional(),apiUri:F.string().optional(),testCustomerId:F.string().optional(),anthropicApiKey:F.string().optional()});F.enum(["pull"]);const hs=nn(void 0);function Qr({children:n}){const e=mn(),[t,s]=B(null),[i,r]=B(!0);tn(()=>{const u=de(e);s(u),r(!1)},[e]);const o=rs(u=>{const d=H.join(e,Zr),h={...de(e)??{},...u},m=ds.safeParse(h);return m.success?(M.writeFileSync(d,se.dump(m.data)),s(m.data),!0):!1},[e]),a=rs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return g(hs.Provider,{value:c,children:n})}l(Qr,"ProjectConfigProvider");function yn(){const n=sn(hs);if(n===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return n}l(yn,"useProjectConfig");const ps=l(({onExit:n,showEscOption:e=!0})=>{const[t,s]=B(""),{data:i,error:r,isLoading:o}=os("/account"),{updateConfig:a,isLoading:c}=yn(),u=i?.workspaces,d=o||c;if(ht((y,S)=>{S.escape&&n?.()}),d)return L(O,{children:[g(rn,{}),g(v,{children:" Fetching workspaces..."})]});if(r)return L(O,{flexDirection:"column",children:[L(v,{color:"red",children:["Error: ",r.message]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(y=>({label:y.name,value:y.id})),m=h.length,w=u?.length??0,p=l(async y=>{const S=f.find(A=>A.id===y);if(!S)return;const{key:b,secret:C}=S;!b||!C||(await a({workspaceKey:b,workspaceSecret:C}),n?.())},"handleSelect");return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,children:g(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),L(O,{marginTop:1,children:[g(v,{children:"Search: "}),g(Er,{placeholder:"Enter a search query...",onChange:s})]}),w>5&&L(v,{children:["Showing ",m," of ",w," workspaces."]}),g(O,{marginTop:1,children:g($r,{options:h,onChange:l(y=>{y&&p(y)},"onChange")})}),e&&g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),Xr=l(({currentPat:n,onSubmit:e})=>{const[t,s]=B(""),[i,r]=B(!1),[o,a]=B(null);return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,marginBottom:1,children:g(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(v,{children:"Please provide your Personal Access Token. You can find it here:"}),g(O,{marginTop:1,marginBottom:1,children:g(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),n&&g(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Ir,{mask:"*",placeholder:`${n?"******":"Enter your token here..."}`,value:t,onChange:s,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),s("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&g(O,{marginTop:1,children:L(v,{children:[g(rn,{type:"dots"})," Validating token..."]})}),o&&g(v,{color:"red",children:o})]})},"PersonalAccessTokenInput"),eo="membrane",to="membrane.config.yml",gn="https://api.integration.app";function Xe(){const n=process.cwd(),e=H.join(n,eo),t=H.join(n,to),s=e,i=H.join(s,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:s,workspaceDataFilePath:i}}l(Xe,"getPaths");const no={pat:{type:"string"},workspace:{type:"object"}},wn=new Lr({schema:no,configName:"config",cwd:j.join(Nr.homedir(),".membrane")}),so=l(n=>{wn.set("pat",n)},"setPat"),ms=l(()=>wn.get("pat"),"getPat"),io=l(()=>!!wn.get("pat"),"hasPat");class ys{static{l(this,"AccountApiClient")}constructor(e=gn){this.apiBaseUrl=e}async request(e,t={}){const s=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!s.has("Authorization")){const o=ms();if(!o)throw new Error("Personal Access Token not found.");s.set("Authorization",`Bearer ${o}`)}t.body&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:s});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const ro=l(n=>{const e=new ys(gn);return t=>e.get(t)},"createAccountApiFetcher");var et=(n=>(n[n.Authenticate=0]="Authenticate",n[n.ConnectWorkspace=1]="ConnectWorkspace",n))(et||{});const oo={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=l(()=>{const{config:n}=yn(),e=io(),t=!!(n?.workspaceKey&&n?.workspaceSecret);return{isAuthenticated:e,workspaceIsConfigured:t,isSetupComplete:e&&t}},"useSetup"),ao=l(({status:n,label:e})=>L(O,{children:[L(O,{width:2,children:[n==="current"&&g(rn,{type:"dots"}),n==="done"&&g(v,{children:"\u2705"})]}),g(v,{dimColor:n!=="current",children:e})]}),"StepDisplay"),bn=[et.Authenticate,et.ConnectWorkspace],co=l(({onComplete:n})=>{const[e,t]=B(!1),[s,i]=B(0),[r,o]=B(!1),[a,c]=B(null),[u,d]=B(""),{isSetupComplete:f}=gs(),h=bn[s],m=s+1,w=bn.length,p=bn.map((C,A)=>{let $="pending";return A<s?$="done":A===s&&($="current"),{id:C,label:oo[C],status:$}}),y=ms();y&&"*".repeat(y.length);const S=l(async C=>{c(null),o(!0);const A=y&&C===""?y:C,$=new ys;try{await $.request("/account",{headers:{Authorization:`Bearer ${A}`}}),so(A),i(N=>N+1),d("")}catch(N){console.log(N),c("Invalid token. Please try again.")}finally{o(!1)}},"handlePatSubmit"),b=l(()=>{t(!0),n&&n()},"handleWorkspaceSelected");return ht((C,A)=>{f&&A.escape&&n&&n()}),e?g(O,{children:g(v,{children:"\u2705 Setup complete. You are ready to go!"})}):L(O,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",L(v,{color:"cyan",children:["Step ",m," of ",w]}),f&&g(v,{color:"grey",children:" [esc: go back]"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:p.map(C=>g(ao,{status:C.status,label:C.label},C.id))})]}),h===et.Authenticate&&g(Xr,{currentPat:y,onSubmit:S}),h===et.ConnectWorkspace&&g(ps,{onExit:b,showEscOption:!1})]})},"Setup");function ws(n){if(!fo(n)&&uo(n))return lo(n)}l(ws,"getTypeAndKeyFromPath");function lo(n){const e=Object.values(ie).map(o=>o.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),s=n.match(t);if(s&&s.groups){const{elementTypePlural:o,elementKey:a}=s.groups,c=bs(o);if(c)return{key:a,type:c}}const i=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),r=n.match(i);if(r&&r.groups){const{elementTypePlural:o,elementKey:a}=r.groups,c=bs(o);if(c)return{key:a,type:c}}}l(lo,"extractWorkspaceElementKeyReference");function uo(n){return n.endsWith(".yml")||n.endsWith(".yaml")}l(uo,"isWorkspaceElementFile");function fo(n){const[e]=n.split(H.sep);return e===ie[I.Connector].apiPath}l(fo,"isConnectorFile");function bs(n){return Object.values(I).find(e=>ho(e)===n)}l(bs,"getWorkspaceElementTypeFromFolderName");function ho(n){return ie[n].apiPath}l(ho,"getWorkspaceElementTypeFolderName");const Ss=nn(null);function po({children:n,fileWatcher:e}){const[t,s]=B([]);tn(()=>{const r=l(u=>d=>{const f=ws(d.relativePath);if(!f)return;const h={...d,elementType:f.type,elementKey:f.key,type:u,timestamp:Date.now()};s(m=>[h,...m.slice(0,2)])},"handleFileChange"),o=r("added"),a=r("changed"),c=r("deleted");return e.on("added",o),e.on("changed",a),e.on("deleted",c),()=>{e.off("added",o),e.off("changed",a),e.off("deleted",c)}},[e]);const i={fileWatcher:e,recentChanges:t};return g(Ss.Provider,{value:i,children:n})}l(po,"FileWatcherProvider");function mo(){const n=sn(Ss);if(!n)throw new Error("useFileWatcher must be used within a FileWatcherProvider");return n}l(mo,"useFileWatcher");const yo=l(n=>{switch(n){case"added":return{symbol:"+",color:"green"};case"changed":return{symbol:"*",color:"yellow"};case"deleted":return{symbol:"-",color:"red"};default:return{symbol:"?",color:"gray"}}},"getSymbolAndColor"),go=l(n=>{switch(n){case"added":return"ADD";case"changed":return"UPD";case"deleted":return"DEL";default:return"UNKNOWN"}},"getActionText");function wo(){const{recentChanges:n}=mo(),e=[...n].sort((t,s)=>t.timestamp-s.timestamp);return e.length===0?g(O,{paddingTop:1,children:g(v,{color:"gray",children:"No recent changes"})}):L(O,{flexDirection:"column",paddingTop:1,children:[g(v,{color:"gray",children:"Recent Changes:"}),e.map((t,s)=>{const{symbol:i,color:r}=yo(t.type),o=go(t.type);return L(O,{marginLeft:1,children:[L(v,{color:r,children:[i," ",o,":"," "]}),L(v,{children:["[",t.elementType,"] ",g(v,{bold:!0,children:t.elementKey})," (",t.relativePath,")"]})]},`${t.filePath}-${t.timestamp}`)})]})}l(wo,"RecentChanges");const ks=l(()=>{const{isSetupComplete:n}=gs(),{config:e}=yn(),t=mn();return{isSetupComplete:n,workspaceKey:e?.workspaceKey,config:e,cwd:t}},"useStatus");function bo(n,e=30){return n.length<=e?n:n.slice(0,e-3)+"..."}l(bo,"truncateWorkspaceName");const So=l(()=>{const{workspaceKey:n,cwd:e}=ks(),t=Math.min(100,process.stdout.columns||100),{data:s}=os("/account"),o=s?.workspaces?.find(c=>c.key===n)?.name,a=o?bo(o):n;return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",g(v,{color:"green",children:"in sync"})]})}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Local:"})}),g(v,{color:"grey",children:e})]}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Remote:"})}),n?L(v,{color:"grey",children:[a," [o: open in console] [w: change]"]}):L(v,{children:[g(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),g(wo,{})]})},"WorkspaceSync");class ko{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return Ye.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=de(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new pt({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const s=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||s||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const Cs=new ko;async function vs(n){const e=await Cs.getClient(n);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(vs,"getWorkspaceId");const Co=l(()=>{const{isSetupComplete:n,workspaceKey:e,config:t}=ks(),[s,i]=B(!1),[r,o]=B(!1),[a,c]=B(!1),u=mn();return ht(d=>{!s&&!r&&!a&&(d==="w"&&i(!0),d==="a"&&c(!0),d==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await vs(u)}`,m=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Cr(`${m} "${h}"`)}catch(f){console.error("Failed to open workspace:",f)}})(),d==="s"&&o(!0))}),s?g(ps,{onExit:l(()=>i(!1),"onExit")}):a?g(Vr,{onExit:l(()=>c(!1),"onExit"),onComplete:l(()=>c(!1),"onComplete")}):r||!n?g(co,{onComplete:l(()=>o(!1),"onComplete")},Date.now()):L(O,{flexDirection:"column",children:[g(O,{flexGrow:1,children:g(Hr,{})}),g(So,{}),g(O,{paddingLeft:2,children:g(v,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),Sn=Symbol.for("yaml.alias"),kn=Symbol.for("yaml.document"),he=Symbol.for("yaml.map"),As=Symbol.for("yaml.pair"),oe=Symbol.for("yaml.scalar"),Oe=Symbol.for("yaml.seq"),Q=Symbol.for("yaml.node.type"),pe=l(n=>!!n&&typeof n=="object"&&n[Q]===Sn,"isAlias"),we=l(n=>!!n&&typeof n=="object"&&n[Q]===kn,"isDocument"),Ee=l(n=>!!n&&typeof n=="object"&&n[Q]===he,"isMap"),R=l(n=>!!n&&typeof n=="object"&&n[Q]===As,"isPair"),K=l(n=>!!n&&typeof n=="object"&&n[Q]===oe,"isScalar$1"),$e=l(n=>!!n&&typeof n=="object"&&n[Q]===Oe,"isSeq");function q(n){if(n&&typeof n=="object")switch(n[Q]){case he:case Oe:return!0}return!1}l(q,"isCollection$1");function U(n){if(n&&typeof n=="object")switch(n[Q]){case Sn:case he:case oe:case Oe:return!0}return!1}l(U,"isNode");const Ts=l(n=>(K(n)||q(n))&&!!n.anchor,"hasAnchor"),Y=Symbol("break visit"),Os=Symbol("skip children"),ae=Symbol("remove node");function be(n,e){const t=Es(e);we(n)?Ie(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):Ie(null,n,t,Object.freeze([]))}l(be,"visit$1"),be.BREAK=Y,be.SKIP=Os,be.REMOVE=ae;function Ie(n,e,t,s){const i=$s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ie(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=Ie(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=Ie("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=Ie("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ie,"visit_");async function gt(n,e){const t=Es(e);we(n)?await Ne(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):await Ne(null,n,t,Object.freeze([]))}l(gt,"visitAsync"),gt.BREAK=Y,gt.SKIP=Os,gt.REMOVE=ae;async function Ne(n,e,t,s){const i=await $s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ne(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=await Ne(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=await Ne("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=await Ne("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ne,"visitAsync_");function Es(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}l(Es,"initVisitor");function $s(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(Ee(e))return t.Map?.(n,e,s);if($e(e))return t.Seq?.(n,e,s);if(R(e))return t.Pair?.(n,e,s);if(K(e))return t.Scalar?.(n,e,s);if(pe(e))return t.Alias?.(n,e,s)}l($s,"callVisitor");function Is(n,e,t){const s=e[e.length-1];if(q(s))s.items[n]=t;else if(R(s))n==="key"?s.key=t:s.value=t;else if(we(s))s.contents=t;else{const i=pe(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(Is,"replaceNode");const vo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ao=l(n=>n.replace(/[!,[\]{}]/g,e=>vo[e]),"escapeTagName");class G{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},G.defaultYaml,e),this.tags=Object.assign({},G.defaultTags,t)}clone(){const e=new G(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new G(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:G.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},G.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:G.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},G.defaultTags),this.atNextDocument=!1);const s=e.trim().split(/[ \t]+/),i=s.shift();switch(i){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[r,o]=s;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=s;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,s,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Ao(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&U(e.contents)){const r={};be(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of s)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
|
|
2
|
+
#!/usr/bin/env node
|
|
3
|
+
var pr=Object.defineProperty;var l=(n,e)=>pr(n,"name",{value:e,configurable:!0});import{jsxs as L,jsx as g}from"react/jsx-runtime";import*as H from"node:path";import{resolve as mr,dirname as yr,join as gr}from"node:path";import{useInput as ht,Box as O,Text as v,Newline as wr,render as br}from"ink";import Sr from"minimist";import{SWRConfig as kr}from"swr";import{exec as Cr}from"node:child_process";import{useState as B,useEffect as tn,createContext as nn,useContext as sn,useCallback as rs}from"react";import*as M from"node:fs";import{readFileSync as vr}from"node:fs";import*as Ar from"node:crypto";import{createHash as Tr}from"node:crypto";import*as Or from"node:os";import{TextInput as Er,Select as $r}from"@inkjs/ui";import rn from"ink-spinner";import os from"swr/immutable";import se from"js-yaml";import{z as F}from"zod";import Ir from"ink-text-input";import Nr from"os";import j from"path";import Lr from"conf";import{WorkspaceElementSpecs as ie,WorkspaceElementType as I,IntegrationAppClient as pt,setValueAtLocator as on,extractIntegrationAppErrorData as re,getDataCollectionCreateFields as an,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as mt,getRequiredFieldsFromSchema as _r,getValueAtLocator as Pr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as cn}from"@membranehq/sdk";import Ye from"jsonwebtoken";import{EventEmitter as xr}from"node:events";import jr from"chokidar";import k from"chalk";import{fileURLToPath as Kr}from"node:url";import{Command as Dr}from"commander";import ln from"axios";import{FastMCP as Mr}from"fastmcp";import P from"fs";import Rr from"archiver";import Br from"form-data";import Fr from"unzipper";import un from"lodash/merge.js";import qr from"@anthropic-ai/sdk";import{faker as Ze}from"@faker-js/faker";import Ur from"lodash/template.js";import Jr from"lodash/templateSettings.js";const fn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(M.existsSync(n))try{t=JSON.parse(M.readFileSync(n,"utf8"))}catch{t={}}const s={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return M.writeFileSync(n,JSON.stringify(s,null,2)),`MCP server configuration added to ${n}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".cursor"),e=H.join(n,"mcp.json");M.existsSync(n)||M.mkdirSync(n);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let s={};if(M.existsSync(e))try{s=JSON.parse(M.readFileSync(e,"utf8"))}catch{s={}}const i={...s,mcpServers:{...s.mcpServers,...t.mcpServers}};return M.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}],Vr=l(({onExit:n,onComplete:e})=>{const[t,s]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[d,f]=B("");ht((w,p)=>{if(c||d){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)n();else if(p.upArrow||w==="k")s(Math.max(0,t-1));else if(p.downArrow||w==="j")s(Math.min(fn.length-1,t+1));else if(p.return||w===" "){const y=fn[t];a(y),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"green",children:"Success"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"green",children:c}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(O,{marginTop:1,paddingLeft:2,children:g(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"red",children:"Error"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:g(v,{color:"red",children:d})}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Confirmation"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[L(v,{children:["Connect ",g(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,children:g(v,{color:"yellow",bold:!0,children:o.actionDescription})}),g(O,{marginTop:2,marginBottom:1,children:L(v,{children:[g(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Select Agent"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,flexDirection:"column",children:fn.map((w,p)=>L(O,{children:[L(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),L(v,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})},"AddMcpServerScreen"),fe=H.join(Or.tmpdir(),"membrane-mcp-status"),us=3e4;function dn(n){return Tr("md5").update(n).digest("hex").slice(0,8)}l(dn,"getCwdHash");function hn(n,e){const t=dn(e);return H.join(fe,`mcp-${t}-${n}.json`)}l(hn,"getStatusFilePath");function Te(n,e){try{const t=e||process.cwd();if(!n){const i=yt(t);return i.length===0?null:i[0]}const s=hn(n,t);if(M.existsSync(s)){const i=M.statSync(s),r=new Date;if(r.getTime()-i.mtime.getTime()>us)return Qe(n,t),null;const a=M.readFileSync(s,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>us)return Qe(n,t),null}return c}}catch{n&&e&&Qe(n,e)}return null}l(Te,"getMcpStatus");function yt(n){try{const e=n||process.cwd(),t=dn(e);if(!M.existsSync(fe))return[];const s=M.readdirSync(fe),i=[];for(const r of s){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=Te(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yt,"getAllMcpStatusFiles");function pn(n){try{const t={...Te(n.processId,n.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:n.processId,cwd:n.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...n};M.existsSync(fe)||M.mkdirSync(fe,{recursive:!0});const s=hn(n.processId,n.cwd);M.writeFileSync(s,JSON.stringify(t,null,2))}catch{}}l(pn,"updateMcpStatus");function Qe(n,e){try{const t=e||process.cwd();if(n){const s=hn(n,t);M.existsSync(s)&&M.unlinkSync(s)}else{const s=dn(t);if(M.existsSync(fe)){const i=M.readdirSync(fe);for(const r of i)r.match(new RegExp(`^mcp-${s}-\\d+\\.json$`))&&M.unlinkSync(H.join(fe,r))}}}catch{}}l(Qe,"clearMcpStatus");function Wr(n,e){const t=Te(n,e);t&&pn({processId:n,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(Wr,"trackToolExecution");function zr(){const[n,e]=B(Te()),[t,s]=B(yt()),[i,r]=B(null);return tn(()=>{try{const a=process.cwd();e(Te(void 0,a)),s(yt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),s([])}const o=setInterval(()=>{try{const a=process.cwd(),c=Te(void 0,a),u=yt(a);e(c),s(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),s([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:n,allMcpServers:t,error:i,isRunning:n?.isRunning||!1,toolsCount:n?.toolsCount||0,totalRequests:n?.totalRequests||0,lastActivity:n?.lastActivity,processId:n?.processId,serverCount:t.length}}l(zr,"useMcpStatus");const Hr=l(()=>{const n=Math.min(100,process.stdout.columns||100),{error:e,serverCount:t,allMcpServers:s}=zr();return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(O,{marginTop:-1,marginBottom:0,flexDirection:"column",children:L(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",e?g(v,{color:"red",children:"error reading status"}):t===0?g(v,{color:"yellow",children:"none"}):g(v,{color:"green",children:t})]})}),!e&&t===0&&g(O,{marginTop:1,children:L(v,{color:"grey",children:["Connect your AI agents to Membrane.",g(wr,{}),"It will give them tools and context to build integrations."]})}),s.length>0&&g(O,{flexDirection:"column",paddingLeft:2,marginTop:1,children:s.map((i,r)=>g(O,{children:L(v,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[a: connect an agent]"})})]})},"AgentStatus"),fs=nn(process.cwd());function Gr({cwd:n,children:e}){return g(fs.Provider,{value:n,children:e})}l(Gr,"CwdProvider");function mn(){return sn(fs)}l(mn,"useCwd");const Yr="membrane.config.yml";function de(n){const e=H.join(n??process.cwd(),Yr);try{const t=M.readFileSync(e,"utf8"),s=se.load(t),i=ds.safeParse(s);return i.success?i.data:null}catch{return null}}l(de,"readProjectConfig");const Zr="membrane.config.yml",ds=F.object({workspaceKey:F.string().optional(),workspaceSecret:F.string().optional(),apiUri:F.string().optional(),testCustomerId:F.string().optional(),anthropicApiKey:F.string().optional()});F.enum(["pull"]);const hs=nn(void 0);function Qr({children:n}){const e=mn(),[t,s]=B(null),[i,r]=B(!0);tn(()=>{const u=de(e);s(u),r(!1)},[e]);const o=rs(u=>{const d=H.join(e,Zr),h={...de(e)??{},...u},m=ds.safeParse(h);return m.success?(M.writeFileSync(d,se.dump(m.data)),s(m.data),!0):!1},[e]),a=rs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return g(hs.Provider,{value:c,children:n})}l(Qr,"ProjectConfigProvider");function yn(){const n=sn(hs);if(n===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return n}l(yn,"useProjectConfig");const ps=l(({onExit:n,showEscOption:e=!0})=>{const[t,s]=B(""),{data:i,error:r,isLoading:o}=os("/account"),{updateConfig:a,isLoading:c}=yn(),u=i?.workspaces,d=o||c;if(ht((y,S)=>{S.escape&&n?.()}),d)return L(O,{children:[g(rn,{}),g(v,{children:" Fetching workspaces..."})]});if(r)return L(O,{flexDirection:"column",children:[L(v,{color:"red",children:["Error: ",r.message]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(y=>({label:y.name,value:y.id})),m=h.length,w=u?.length??0,p=l(async y=>{const S=f.find(A=>A.id===y);if(!S)return;const{key:b,secret:C}=S;!b||!C||(await a({workspaceKey:b,workspaceSecret:C}),n?.())},"handleSelect");return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,children:g(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),L(O,{marginTop:1,children:[g(v,{children:"Search: "}),g(Er,{placeholder:"Enter a search query...",onChange:s})]}),w>5&&L(v,{children:["Showing ",m," of ",w," workspaces."]}),g(O,{marginTop:1,children:g($r,{options:h,onChange:l(y=>{y&&p(y)},"onChange")})}),e&&g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),Xr=l(({currentPat:n,onSubmit:e})=>{const[t,s]=B(""),[i,r]=B(!1),[o,a]=B(null);return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,marginBottom:1,children:g(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(v,{children:"Please provide your Personal Access Token. You can find it here:"}),g(O,{marginTop:1,marginBottom:1,children:g(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),n&&g(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Ir,{mask:"*",placeholder:`${n?"******":"Enter your token here..."}`,value:t,onChange:s,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),s("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&g(O,{marginTop:1,children:L(v,{children:[g(rn,{type:"dots"})," Validating token..."]})}),o&&g(v,{color:"red",children:o})]})},"PersonalAccessTokenInput"),eo="membrane",to="membrane.config.yml",gn="https://api.integration.app";function Xe(){const n=process.cwd(),e=H.join(n,eo),t=H.join(n,to),s=e,i=H.join(s,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:s,workspaceDataFilePath:i}}l(Xe,"getPaths");const no={pat:{type:"string"},workspace:{type:"object"}},wn=new Lr({schema:no,configName:"config",cwd:j.join(Nr.homedir(),".membrane")}),so=l(n=>{wn.set("pat",n)},"setPat"),ms=l(()=>wn.get("pat"),"getPat"),io=l(()=>!!wn.get("pat"),"hasPat");class ys{static{l(this,"AccountApiClient")}constructor(e=gn){this.apiBaseUrl=e}async request(e,t={}){const s=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!s.has("Authorization")){const o=ms();if(!o)throw new Error("Personal Access Token not found.");s.set("Authorization",`Bearer ${o}`)}t.body&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:s});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const ro=l(n=>{const e=new ys(gn);return t=>e.get(t)},"createAccountApiFetcher");var et=(n=>(n[n.Authenticate=0]="Authenticate",n[n.ConnectWorkspace=1]="ConnectWorkspace",n))(et||{});const oo={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=l(()=>{const{config:n}=yn(),e=io(),t=!!(n?.workspaceKey&&n?.workspaceSecret);return{isAuthenticated:e,workspaceIsConfigured:t,isSetupComplete:e&&t}},"useSetup"),ao=l(({status:n,label:e})=>L(O,{children:[L(O,{width:2,children:[n==="current"&&g(rn,{type:"dots"}),n==="done"&&g(v,{children:"\u2705"})]}),g(v,{dimColor:n!=="current",children:e})]}),"StepDisplay"),bn=[et.Authenticate,et.ConnectWorkspace],co=l(({onComplete:n})=>{const[e,t]=B(!1),[s,i]=B(0),[r,o]=B(!1),[a,c]=B(null),[u,d]=B(""),{isSetupComplete:f}=gs(),h=bn[s],m=s+1,w=bn.length,p=bn.map((C,A)=>{let $="pending";return A<s?$="done":A===s&&($="current"),{id:C,label:oo[C],status:$}}),y=ms();y&&"*".repeat(y.length);const S=l(async C=>{c(null),o(!0);const A=y&&C===""?y:C,$=new ys;try{await $.request("/account",{headers:{Authorization:`Bearer ${A}`}}),so(A),i(N=>N+1),d("")}catch(N){console.log(N),c("Invalid token. Please try again.")}finally{o(!1)}},"handlePatSubmit"),b=l(()=>{t(!0),n&&n()},"handleWorkspaceSelected");return ht((C,A)=>{f&&A.escape&&n&&n()}),e?g(O,{children:g(v,{children:"\u2705 Setup complete. You are ready to go!"})}):L(O,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",L(v,{color:"cyan",children:["Step ",m," of ",w]}),f&&g(v,{color:"grey",children:" [esc: go back]"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:p.map(C=>g(ao,{status:C.status,label:C.label},C.id))})]}),h===et.Authenticate&&g(Xr,{currentPat:y,onSubmit:S}),h===et.ConnectWorkspace&&g(ps,{onExit:b,showEscOption:!1})]})},"Setup");function ws(n){if(!fo(n)&&uo(n))return lo(n)}l(ws,"getTypeAndKeyFromPath");function lo(n){const e=Object.values(ie).map(o=>o.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),s=n.match(t);if(s&&s.groups){const{elementTypePlural:o,elementKey:a}=s.groups,c=bs(o);if(c)return{key:a,type:c}}const i=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),r=n.match(i);if(r&&r.groups){const{elementTypePlural:o,elementKey:a}=r.groups,c=bs(o);if(c)return{key:a,type:c}}}l(lo,"extractWorkspaceElementKeyReference");function uo(n){return n.endsWith(".yml")||n.endsWith(".yaml")}l(uo,"isWorkspaceElementFile");function fo(n){const[e]=n.split(H.sep);return e===ie[I.Connector].apiPath}l(fo,"isConnectorFile");function bs(n){return Object.values(I).find(e=>ho(e)===n)}l(bs,"getWorkspaceElementTypeFromFolderName");function ho(n){return ie[n].apiPath}l(ho,"getWorkspaceElementTypeFolderName");const Ss=nn(null);function po({children:n,fileWatcher:e}){const[t,s]=B([]);tn(()=>{const r=l(u=>d=>{const f=ws(d.relativePath);if(!f)return;const h={...d,elementType:f.type,elementKey:f.key,type:u,timestamp:Date.now()};s(m=>[h,...m.slice(0,2)])},"handleFileChange"),o=r("added"),a=r("changed"),c=r("deleted");return e.on("added",o),e.on("changed",a),e.on("deleted",c),()=>{e.off("added",o),e.off("changed",a),e.off("deleted",c)}},[e]);const i={fileWatcher:e,recentChanges:t};return g(Ss.Provider,{value:i,children:n})}l(po,"FileWatcherProvider");function mo(){const n=sn(Ss);if(!n)throw new Error("useFileWatcher must be used within a FileWatcherProvider");return n}l(mo,"useFileWatcher");const yo=l(n=>{switch(n){case"added":return{symbol:"+",color:"green"};case"changed":return{symbol:"*",color:"yellow"};case"deleted":return{symbol:"-",color:"red"};default:return{symbol:"?",color:"gray"}}},"getSymbolAndColor"),go=l(n=>{switch(n){case"added":return"ADD";case"changed":return"UPD";case"deleted":return"DEL";default:return"UNKNOWN"}},"getActionText");function wo(){const{recentChanges:n}=mo(),e=[...n].sort((t,s)=>t.timestamp-s.timestamp);return e.length===0?g(O,{paddingTop:1,children:g(v,{color:"gray",children:"No recent changes"})}):L(O,{flexDirection:"column",paddingTop:1,children:[g(v,{color:"gray",children:"Recent Changes:"}),e.map((t,s)=>{const{symbol:i,color:r}=yo(t.type),o=go(t.type);return L(O,{marginLeft:1,children:[L(v,{color:r,children:[i," ",o,":"," "]}),L(v,{children:["[",t.elementType,"] ",g(v,{bold:!0,children:t.elementKey})," (",t.relativePath,")"]})]},`${t.filePath}-${t.timestamp}`)})]})}l(wo,"RecentChanges");const ks=l(()=>{const{isSetupComplete:n}=gs(),{config:e}=yn(),t=mn();return{isSetupComplete:n,workspaceKey:e?.workspaceKey,config:e,cwd:t}},"useStatus");function bo(n,e=30){return n.length<=e?n:n.slice(0,e-3)+"..."}l(bo,"truncateWorkspaceName");const So=l(()=>{const{workspaceKey:n,cwd:e}=ks(),t=Math.min(100,process.stdout.columns||100),{data:s}=os("/account"),o=s?.workspaces?.find(c=>c.key===n)?.name,a=o?bo(o):n;return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",g(v,{color:"green",children:"in sync"})]})}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Local:"})}),g(v,{color:"grey",children:e})]}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Remote:"})}),n?L(v,{color:"grey",children:[a," [o: open in console] [w: change]"]}):L(v,{children:[g(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),g(wo,{})]})},"WorkspaceSync");class ko{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return Ye.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=de(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new pt({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const s=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||s||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const Cs=new ko;async function vs(n){const e=await Cs.getClient(n);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(vs,"getWorkspaceId");const Co=l(()=>{const{isSetupComplete:n,workspaceKey:e,config:t}=ks(),[s,i]=B(!1),[r,o]=B(!1),[a,c]=B(!1),u=mn();return ht(d=>{!s&&!r&&!a&&(d==="w"&&i(!0),d==="a"&&c(!0),d==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await vs(u)}`,m=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Cr(`${m} "${h}"`)}catch(f){console.error("Failed to open workspace:",f)}})(),d==="s"&&o(!0))}),s?g(ps,{onExit:l(()=>i(!1),"onExit")}):a?g(Vr,{onExit:l(()=>c(!1),"onExit"),onComplete:l(()=>c(!1),"onComplete")}):r||!n?g(co,{onComplete:l(()=>o(!1),"onComplete")},Date.now()):L(O,{flexDirection:"column",children:[g(O,{flexGrow:1,children:g(Hr,{})}),g(So,{}),g(O,{paddingLeft:2,children:g(v,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),Sn=Symbol.for("yaml.alias"),kn=Symbol.for("yaml.document"),he=Symbol.for("yaml.map"),As=Symbol.for("yaml.pair"),oe=Symbol.for("yaml.scalar"),Oe=Symbol.for("yaml.seq"),Q=Symbol.for("yaml.node.type"),pe=l(n=>!!n&&typeof n=="object"&&n[Q]===Sn,"isAlias"),we=l(n=>!!n&&typeof n=="object"&&n[Q]===kn,"isDocument"),Ee=l(n=>!!n&&typeof n=="object"&&n[Q]===he,"isMap"),R=l(n=>!!n&&typeof n=="object"&&n[Q]===As,"isPair"),K=l(n=>!!n&&typeof n=="object"&&n[Q]===oe,"isScalar$1"),$e=l(n=>!!n&&typeof n=="object"&&n[Q]===Oe,"isSeq");function q(n){if(n&&typeof n=="object")switch(n[Q]){case he:case Oe:return!0}return!1}l(q,"isCollection$1");function U(n){if(n&&typeof n=="object")switch(n[Q]){case Sn:case he:case oe:case Oe:return!0}return!1}l(U,"isNode");const Ts=l(n=>(K(n)||q(n))&&!!n.anchor,"hasAnchor"),Y=Symbol("break visit"),Os=Symbol("skip children"),ae=Symbol("remove node");function be(n,e){const t=Es(e);we(n)?Ie(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):Ie(null,n,t,Object.freeze([]))}l(be,"visit$1"),be.BREAK=Y,be.SKIP=Os,be.REMOVE=ae;function Ie(n,e,t,s){const i=$s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ie(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=Ie(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=Ie("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=Ie("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ie,"visit_");async function gt(n,e){const t=Es(e);we(n)?await Ne(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):await Ne(null,n,t,Object.freeze([]))}l(gt,"visitAsync"),gt.BREAK=Y,gt.SKIP=Os,gt.REMOVE=ae;async function Ne(n,e,t,s){const i=await $s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ne(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=await Ne(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=await Ne("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=await Ne("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ne,"visitAsync_");function Es(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}l(Es,"initVisitor");function $s(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(Ee(e))return t.Map?.(n,e,s);if($e(e))return t.Seq?.(n,e,s);if(R(e))return t.Pair?.(n,e,s);if(K(e))return t.Scalar?.(n,e,s);if(pe(e))return t.Alias?.(n,e,s)}l($s,"callVisitor");function Is(n,e,t){const s=e[e.length-1];if(q(s))s.items[n]=t;else if(R(s))n==="key"?s.key=t:s.value=t;else if(we(s))s.contents=t;else{const i=pe(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(Is,"replaceNode");const vo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ao=l(n=>n.replace(/[!,[\]{}]/g,e=>vo[e]),"escapeTagName");class G{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},G.defaultYaml,e),this.tags=Object.assign({},G.defaultTags,t)}clone(){const e=new G(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new G(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:G.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},G.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:G.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},G.defaultTags),this.atNextDocument=!1);const s=e.trim().split(/[ \t]+/),i=s.shift();switch(i){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[r,o]=s;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=s;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,s,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Ao(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&U(e.contents)){const r={};be(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of s)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
|
|
3
4
|
`)}}G.defaultYaml={explicit:!1,version:"1.2"},G.defaultTags={"!!":"tag:yaml.org,2002:"};function Ns(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}l(Ns,"anchorIsValid");function Ls(n){const e=new Set;return be(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}l(Ls,"anchorNames");function _s(n,e){for(let t=1;;++t){const s=`${n}${t}`;if(!e.has(s))return s}}l(_s,"findNewAnchor");function To(n,e){const t=[],s=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=Ls(n));const o=_s(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=s.get(r);if(typeof o=="object"&&o.anchor&&(K(o.node)||q(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:s}}l(To,"createNodeAnchors");function Le(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let i=0,r=s.length;i<r;++i){const o=s[i],a=Le(n,s,String(i),o);a===void 0?delete s[i]:a!==o&&(s[i]=a)}else if(s instanceof Map)for(const i of Array.from(s.keys())){const r=s.get(i),o=Le(n,s,i,r);o===void 0?s.delete(i):o!==r&&s.set(i,o)}else if(s instanceof Set)for(const i of Array.from(s)){const r=Le(n,s,i,i);r===void 0?s.delete(i):r!==i&&(s.delete(i),s.add(r))}else for(const[i,r]of Object.entries(s)){const o=Le(n,s,i,r);o===void 0?delete s[i]:o!==r&&(s[i]=o)}return n.call(e,t,s)}l(Le,"applyReviver");function X(n,e,t){if(Array.isArray(n))return n.map((s,i)=>X(s,String(i),t));if(n&&typeof n.toJSON=="function"){if(!t||!Ts(n))return n.toJSON(e,t);const s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=r=>{s.res=r,delete t.onCreate};const i=n.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof n=="bigint"&&!t?.keep?Number(n):n}l(X,"toJS");class Cn{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,Q,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:s,onAnchor:i,reviver:r}={}){if(!we(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=X(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?Le(r,{"":a},"",a):a}}class wt extends Cn{static{l(this,"Alias")}constructor(e){super(Sn),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],be(e,{Node:l((r,o)=>{(pe(o)||Ts(o))&&s.push(o)},"Node")}),t&&(t.aliasResolveCache=s));let i;for(const r of s){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:s,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(X(o,null,t),a=s.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=bt(i,o,s)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,s){const i=`*${this.source}`;if(e){if(Ns(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function bt(n,e,t){if(pe(e)){const s=e.resolve(n),i=t&&s&&t.get(s);return i?i.count*i.aliasCount:0}else if(q(e)){let s=0;for(const i of e.items){const r=bt(n,i,t);r>s&&(s=r)}return s}else if(R(e)){const s=bt(n,e.key,t),i=bt(n,e.value,t);return Math.max(s,i)}return 1}l(bt,"getAliasCount");const Ps=l(n=>!n||typeof n!="function"&&typeof n!="object","isScalarValue");class _ extends Cn{static{l(this,"Scalar")}constructor(e){super(oe),this.value=e}toJSON(e,t){return t?.keep?this.value:X(this.value,e,t)}toString(){return String(this.value)}}_.BLOCK_FOLDED="BLOCK_FOLDED",_.BLOCK_LITERAL="BLOCK_LITERAL",_.PLAIN="PLAIN",_.QUOTE_DOUBLE="QUOTE_DOUBLE",_.QUOTE_SINGLE="QUOTE_SINGLE";const Oo="tag:yaml.org,2002:";function Eo(n,e,t){if(e){const s=t.filter(r=>r.tag===e),i=s.find(r=>!r.format)??s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>s.identify?.(n)&&!s.format)}l(Eo,"findTagObject");function tt(n,e,t){if(we(n)&&(n=n.contents),U(n))return n;if(R(n)){const f=t.schema[he].createNode?.(t.schema,null,t);return f.items.push(n),f}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:s,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(s&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=i(n)),new wt(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=Oo+e.slice(2));let u=Eo(n,e,o.tags);if(!u){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){const f=new _(n);return c&&(c.node=f),f}u=n instanceof Map?o[he]:Symbol.iterator in Object(n)?o[Oe]:o[he]}r&&(r(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,n,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,n,t):new _(n);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}l(tt,"createNode");function St(n,e,t){let s=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=s,s=o}else s=new Map([[r,s]])}return tt(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:n,sourceObjects:new Map})}l(St,"collectionFromPath");const nt=l(n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,"isEmptyPath");class xs extends Cn{static{l(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(s=>U(s)||R(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(nt(e))this.add(t);else{const[s,...i]=e,r=this.get(s,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(s,St(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}deleteIn(e){const[t,...s]=e;if(s.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){const[s,...i]=e,r=this.get(s,!0);return i.length===0?!t&&K(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!R(t))return!1;const s=t.value;return s==null||e&&K(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){const[t,...s]=e;if(s.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(s):!1}setIn(e,t){const[s,...i]=e;if(i.length===0)this.set(s,t);else{const r=this.get(s,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(s,St(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}}const $o=l(n=>n.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function ce(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}l(ce,"indentComment");const Se=l((n,e,t)=>n.endsWith(`
|
|
4
5
|
`)?ce(t,e):t.includes(`
|
|
5
6
|
`)?`
|
|
@@ -137,7 +138,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
137
138
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
138
139
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ye(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(Ai(t.key)&&!ye(t.sep,"newline")){const o=Me(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ye(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Me(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ye(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ye(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ye(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s&&s.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{const s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){const i=qt(s),r=Me(i);Ti(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
139
140
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
140
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function Oi(n){const e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Ci||null,prettyErrors:e}}l(Oi,"parseOptions");function $a(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e),o=Array.from(r.compose(i.parse(n)));if(s&&t)for(const a of o)a.errors.forEach(jt(n,t)),a.warnings.forEach(jt(n,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l($a,"parseAllDocuments");function Ei(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e);let o=null;for(const a of r.compose(i.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ce(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(jt(n,t)),o.warnings.forEach(jt(n,t))),o}l(Ei,"parseDocument");function Ia(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Ei(n,t);if(!i)return null;if(i.warnings.forEach(r=>Ms(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:s},t))}l(Ia,"parse");function Na(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(n===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return we(n)&&!s?n.toString(t):new Ge(n,s,t).toString(t)}l(Na,"stringify");var La=Object.freeze({__proto__:null,Alias:wt,CST:Ta,Composer:Un,Document:Ge,Lexer:ki,LineCounter:Ci,Pair:z,Parser:zn,Scalar:_,Schema:en,YAMLError:Dn,YAMLMap:Z,YAMLParseError:Ce,YAMLSeq:me,YAMLWarning:ai,isAlias:pe,isCollection:q,isDocument:we,isMap:Ee,isNode:U,isPair:R,isScalar:K,isSeq:$e,parse:Ia,parseAllDocuments:$a,parseDocument:Ei,stringify:Na,visit:be,visitAsync:gt});const _a="membrane",Pa=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function xa(n){return H.join(n,_a)}l(xa,"getMembraneDir");const ja={ignored:Pa,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ka extends xr{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=xa(e.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(M.existsSync(this.membraneDir)||M.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=jr.watch(this.membraneDir,ja),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("deleted",e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.emit("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const s=H.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(s);const a={filePath:t,relativePath:s,data:void 0};this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(s,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(s,i),this.emit(e,o)}readFileContent(e){return M.readFileSync(e,"utf8")}processFileEvent(e,t){const s=H.relative(this.membraneDir,e);let i;try{i=t?La.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:s,data:i}}hasContentChanged(e,t,s){if(s==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return Ar.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}}var x={},Ut={},$i;function Ii(){if($i)return Ut;$i=1,Object.defineProperty(Ut,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toCamelCase"),Ut.default=n,Ut}l(Ii,"requireJsCamelcase");var Jt={},Ni;function Li(){if(Ni)return Jt;Ni=1,Object.defineProperty(Jt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(n,"toSnakeCase"),Jt.default=n,Jt}l(Li,"requireJsSnakecase");var Vt={},_i;function Pi(){if(_i)return Vt;_i=1,Object.defineProperty(Vt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toPascalCase"),Vt.default=n,Vt}l(Pi,"requireJsPascalcase");var Wt={},xi;function Da(){if(xi)return Wt;xi=1,Object.defineProperty(Wt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(n,"toDotCase"),Wt.default=n,Wt}l(Da,"requireJsDotcase");var zt={},ji;function Ma(){if(ji)return zt;ji=1,Object.defineProperty(zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(n,"toPathCase"),zt.default=n,zt}l(Ma,"requireJsPathcase");var Ht={},Ki;function Ra(){if(Ki)return Ht;Ki=1,Object.defineProperty(Ht,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(n,"toTextCase"),Ht.default=n,Ht}l(Ra,"requireJsTextcase");var Gt={},Di;function Ba(){if(Di)return Gt;Di=1,Object.defineProperty(Gt,"__esModule",{value:!0});function n(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(s,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(n,"toSentenceCase"),Gt.default=n,Gt}l(Ba,"requireJsSentencecase");var Yt={},Mi;function Fa(){if(Mi)return Yt;Mi=1,Object.defineProperty(Yt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,s,i,r){return s+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(n,"toHeaderCase"),Yt.default=n,Yt}l(Fa,"requireJsHeadercase");var Zt={},Ri;function Bi(){if(Ri)return Zt;Ri=1,Object.defineProperty(Zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(n,"toKebabCase"),Zt.default=n,Zt}l(Bi,"requireJsKebabcase");var Re={},Hn={},Fi;function Be(){return Fi||(Fi=1,function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.belongToTypes=n.isValidObject=n.isArrayObject=n.validateOptions=n.DefaultOption=void 0,n.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},n.validateOptions=function(e){return e===void 0&&(e=n.DefaultOption),e.recursive==null?e=n.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},n.isArrayObject=function(e){return e!=null&&Array.isArray(e)},n.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},n.belongToTypes=function(e,t){return(t||[]).some(function(s){return e instanceof s})}}(Hn)),Hn}l(Be,"requireUtils");var qi;function qa(){if(qi)return Re;qi=1;var n=Re&&Re.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Re,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"lowerKeys"),Re.default=t,Re}l(qa,"requireLowercaseKeysObject");var Fe={},Ui;function Ua(){if(Ui)return Fe;Ui=1;var n=Fe&&Fe.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Fe,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"upperKeys"),Fe.default=t,Fe}l(Ua,"requireUppercaseKeysObject");var qe={},Ji;function Ja(){if(Ji)return qe;Ji=1;var n=qe&&qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Be(),t=Ii();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"camelKeys"),qe.default=s,qe}l(Ja,"requireCamelcaseKeysObject");var Ue={},Vi;function Va(){if(Vi)return Ue;Vi=1;var n=Ue&&Ue.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ue,"__esModule",{value:!0});var e=Be(),t=Li();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"snakeKeys"),Ue.default=s,Ue}l(Va,"requireSnakecaseKeysObject");var Je={},Wi;function Wa(){if(Wi)return Je;Wi=1;var n=Je&&Je.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Je,"__esModule",{value:!0});var e=Be(),t=Pi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"pascalKeys"),Je.default=s,Je}l(Wa,"requirePascalcaseKeysObject");var Ve={},zi;function za(){if(zi)return Ve;zi=1;var n=Ve&&Ve.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ve,"__esModule",{value:!0});var e=Be(),t=Bi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"kebabKeys"),Ve.default=s,Ve}l(za,"requireKebabcaseKeysObject");var Hi;function Ha(){if(Hi)return x;Hi=1,Object.defineProperty(x,"__esModule",{value:!0}),x.kebabKeys=x.pascalKeys=x.snakeKeys=x.camelKeys=x.upperKeys=x.lowerKeys=x.toLowerCase=x.toUpperCase=x.toKebabCase=x.toHeaderCase=x.toSentenceCase=x.toTextCase=x.toPathCase=x.toDotCase=x.toPascalCase=x.toSnakeCase=x.toCamelCase=void 0;var n=Ii();x.toCamelCase=n.default;var e=Li();x.toSnakeCase=e.default;var t=Pi();x.toPascalCase=t.default;var s=Da();x.toDotCase=s.default;var i=Ma();x.toPathCase=i.default;var r=Ra();x.toTextCase=r.default;var o=Ba();x.toSentenceCase=o.default;var a=Fa();x.toHeaderCase=a.default;var c=Bi();x.toKebabCase=c.default;var u=qa();x.lowerKeys=u.default;var d=Ua();x.upperKeys=d.default;var f=Ja();x.camelKeys=f.default;var h=Va();x.snakeKeys=h.default;var m=Wa();x.pascalKeys=m.default;var w=za();x.kebabKeys=w.default;var p=l(function(b){return String(b||"").toLowerCase()},"toLowerCase");x.toLowerCase=p;var y=l(function(b){return String(b||"").toUpperCase()},"toUpperCase");x.toUpperCase=y;var S={toCamelCase:n.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:s.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return x.default=S,x}l(Ha,"requireLib");var Gn,Gi;function Ga(){return Gi||(Gi=1,Gn=Ha()),Gn}l(Ga,"requireJsConvertCase");var We=Ga();const ut={[I.Integration]:{element:"integration",elements:"integrations",exportable:!1},[I.Connector]:{element:"connector",elements:"connectors",exportable:!1},[I.Action]:{element:"action",elements:"actions",integrationSpecific:!0},[I.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[I.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[I.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[I.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[I.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0},[I.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0},[I.Customer]:{element:"customer",elements:"customers"},[I.FlowInstance]:{element:"flowInstance",elements:"flowInstances"},[I.FlowRun]:{element:"flowRun",elements:"flowRuns"},[I.Scenario]:{element:"scenario",elements:"scenarios"},[I.ActionInstance]:{element:"actionInstance",elements:"actionInstances"},[I.Connection]:{element:"connection",elements:"connections"},[I.FieldMappingInstance]:{element:"fieldMappingInstance",elements:"fieldMappingInstances"},[I.DataSourceInstance]:{element:"dataSourceInstance",elements:"dataSourceInstances"},[I.DataLinkTableInstance]:{element:"dataLinkTableInstance",elements:"dataLinkTableInstances"},[I.AppEventSubscription]:{element:"appEventSubscription",elements:"appEventSubscriptions"},[I.AppDataSchemaInstance]:{element:"appDataSchemaInstance",elements:"appDataSchemaInstances"},[I.ExternalEventSubscription]:{element:"externalEventSubscription",elements:"externalEventSubscriptions"},[I.ExternalEventLogRecord]:{element:"externalEventLogRecord",elements:"externalEventLogRecords"},[I.ExternalEventPull]:{element:"externalEventPull",elements:"externalEventPulls"},[I.DataCollection]:{element:"dataCollection",elements:"dataCollections"},[I.Screen]:{element:"screen",elements:"screens"},[I.ActionRunLogRecord]:{element:"actionRunLogRecord",elements:"actionRunLogRecords"}};class Ya{static{l(this,"WorkspaceElementService")}constructor(e){this.fileWatcher=e,this.setupEventHandlers()}client;workspaceDataCache={};cacheExpirationTime=5*60*1e3;lastCacheUpdate=0;async init(){this.client=await Cs.getClient(this.fileWatcher.getCwd())}setupEventHandlers(){this.fileWatcher.on("added",e=>this.processElementChange(e,"added")),this.fileWatcher.on("changed",e=>this.processElementChange(e,"changed")),this.fileWatcher.on("deleted",e=>this.processElementChange(e,"deleted"))}async processElementChange(e,t){try{const s=ws(e.relativePath);if(!s||!s.key||!s.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${s.key} of type ${s.type}`),t){case"added":case"changed":await this.pushElement(s.type,{...e.data,key:s.key});break;case"deleted":break}}catch(s){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,s)}}async pushElement(e,t){if(!ut[e])throw new Error(`Unknown element type: ${e}`);const i={...t},r=await this.getWorkspaceData();delete i.integrationId;const o=this.matchElement(i,e,r);o?await this.handleExistingElement(e,i,o):await this.handleNewElement(e,i,r)}async handleExistingElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await this.client[r](s.id).put(t),console.debug(`Updated ${t.integrationKey||"universal"} ${i.element} ${t.key}`);else if(this.hasParent(t))try{await this.client[r](s.id).reset(),console.debug(`Customization reset ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(o){throw console.debug("Error resetting element:",s,t),o}else console.warn(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}async handleNewElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name),o=We.toCamelCase(ie[e].namePlural);if(this.hasParent(t)){try{await this.client[r]({key:t.key}).apply([t.integrationKey])}catch{try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey,s);await this.client[o].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t),console.debug(`Applied & Customized ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug("Error customizing element:",t),a}else console.debug(`Applied universal ${i.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const a=this.findIntegrationId(t.integrationKey,s);t.integrationId=a}await this.client[o].create(t),console.debug(`Created ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug(`Error creating element ${e}`,this.hasParent(t),t.integrationKey,t),a}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}matchElement(e,t,s){const i=s[t]?.filter(r=>r.key===e.key&&r.integrationKey===e.integrationKey&&!r.archivedAt);if(!(!i||i.length===0)){if(i.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return i[0]}}findIntegrationId(e,t){const s=t.integration?.find(i=>i.key===e);if(!s)throw new Error(`Integration with key ${e} not found`);return s.id}async getWorkspaceData(){const e=Date.now();if(this.lastCacheUpdate&&e-this.lastCacheUpdate<this.cacheExpirationTime)return this.workspaceDataCache;console.debug("Refreshing workspace data cache");const t={};try{const s=await this.client.integrations.findAll();t.integration=s.map(i=>({id:i.id,key:i.key,name:i.name}));for(const i of Object.keys(ut)){const r=ut[i];if(r.exportable!==!1)try{const o=[],a=await this.client[r.elements].findAll();if(o.push(...a),r.integrationSpecific)for(const c of s)try{const u=await this.client[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>({...d,integrationKey:c.key})))}catch(u){console.error(`Failed to fetch ${i} for integration ${c.key}:`,u)}t[i]=o}catch(o){console.error(`Failed to fetch ${i} elements:`,o),t[i]=[]}}return this.workspaceDataCache=t,this.lastCacheUpdate=e,console.debug("Workspace data cache refreshed successfully"),t}catch(s){return console.error("Failed to refresh workspace data cache:",s),Object.keys(this.workspaceDataCache).length>0?(console.debug("Using existing workspace data cache due to refresh failure"),this.workspaceDataCache):{integration:[]}}}}const Za={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Qa={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class E{static{l(this,"Logger")}static formatMessage(e,t,s={}){const i=s.timestamp?`${k.gray(new Date().toISOString())} `:"",r=s.prefix?`${k.gray(s.prefix)} `:"",o=s.suffix?` ${k.gray(s.suffix)}`:"",a=Za[t],c=Qa[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let s=k.blue;if(t?.color&&(s=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${s(e)}`)}else console.debug(s(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
141
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function Oi(n){const e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Ci||null,prettyErrors:e}}l(Oi,"parseOptions");function $a(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e),o=Array.from(r.compose(i.parse(n)));if(s&&t)for(const a of o)a.errors.forEach(jt(n,t)),a.warnings.forEach(jt(n,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l($a,"parseAllDocuments");function Ei(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e);let o=null;for(const a of r.compose(i.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ce(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(jt(n,t)),o.warnings.forEach(jt(n,t))),o}l(Ei,"parseDocument");function Ia(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Ei(n,t);if(!i)return null;if(i.warnings.forEach(r=>Ms(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:s},t))}l(Ia,"parse");function Na(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(n===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return we(n)&&!s?n.toString(t):new Ge(n,s,t).toString(t)}l(Na,"stringify");var La=Object.freeze({__proto__:null,Alias:wt,CST:Ta,Composer:Un,Document:Ge,Lexer:ki,LineCounter:Ci,Pair:z,Parser:zn,Scalar:_,Schema:en,YAMLError:Dn,YAMLMap:Z,YAMLParseError:Ce,YAMLSeq:me,YAMLWarning:ai,isAlias:pe,isCollection:q,isDocument:we,isMap:Ee,isNode:U,isPair:R,isScalar:K,isSeq:$e,parse:Ia,parseAllDocuments:$a,parseDocument:Ei,stringify:Na,visit:be,visitAsync:gt});const _a="membrane",Pa=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function xa(n){return H.join(n,_a)}l(xa,"getMembraneDir");const ja={ignored:Pa,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ka extends xr{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=xa(e.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(M.existsSync(this.membraneDir)||M.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=jr.watch(this.membraneDir,ja),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("deleted",e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.emit("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const s=H.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(s);const a={filePath:t,relativePath:s,data:void 0};this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(s,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(s,i),this.emit(e,o)}readFileContent(e){return M.readFileSync(e,"utf8")}processFileEvent(e,t){const s=H.relative(this.membraneDir,e);let i;try{i=t?La.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:s,data:i}}hasContentChanged(e,t,s){if(s==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return Ar.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}}var x={},Ut={},$i;function Ii(){if($i)return Ut;$i=1,Object.defineProperty(Ut,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toCamelCase"),Ut.default=n,Ut}l(Ii,"requireJsCamelcase");var Jt={},Ni;function Li(){if(Ni)return Jt;Ni=1,Object.defineProperty(Jt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(n,"toSnakeCase"),Jt.default=n,Jt}l(Li,"requireJsSnakecase");var Vt={},_i;function Pi(){if(_i)return Vt;_i=1,Object.defineProperty(Vt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toPascalCase"),Vt.default=n,Vt}l(Pi,"requireJsPascalcase");var Wt={},xi;function Da(){if(xi)return Wt;xi=1,Object.defineProperty(Wt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(n,"toDotCase"),Wt.default=n,Wt}l(Da,"requireJsDotcase");var zt={},ji;function Ma(){if(ji)return zt;ji=1,Object.defineProperty(zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(n,"toPathCase"),zt.default=n,zt}l(Ma,"requireJsPathcase");var Ht={},Ki;function Ra(){if(Ki)return Ht;Ki=1,Object.defineProperty(Ht,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(n,"toTextCase"),Ht.default=n,Ht}l(Ra,"requireJsTextcase");var Gt={},Di;function Ba(){if(Di)return Gt;Di=1,Object.defineProperty(Gt,"__esModule",{value:!0});function n(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(s,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(n,"toSentenceCase"),Gt.default=n,Gt}l(Ba,"requireJsSentencecase");var Yt={},Mi;function Fa(){if(Mi)return Yt;Mi=1,Object.defineProperty(Yt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,s,i,r){return s+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(n,"toHeaderCase"),Yt.default=n,Yt}l(Fa,"requireJsHeadercase");var Zt={},Ri;function Bi(){if(Ri)return Zt;Ri=1,Object.defineProperty(Zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(n,"toKebabCase"),Zt.default=n,Zt}l(Bi,"requireJsKebabcase");var Re={},Hn={},Fi;function Be(){return Fi||(Fi=1,function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.belongToTypes=n.isValidObject=n.isArrayObject=n.validateOptions=n.DefaultOption=void 0,n.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},n.validateOptions=function(e){return e===void 0&&(e=n.DefaultOption),e.recursive==null?e=n.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},n.isArrayObject=function(e){return e!=null&&Array.isArray(e)},n.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},n.belongToTypes=function(e,t){return(t||[]).some(function(s){return e instanceof s})}}(Hn)),Hn}l(Be,"requireUtils");var qi;function qa(){if(qi)return Re;qi=1;var n=Re&&Re.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Re,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"lowerKeys"),Re.default=t,Re}l(qa,"requireLowercaseKeysObject");var Fe={},Ui;function Ua(){if(Ui)return Fe;Ui=1;var n=Fe&&Fe.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Fe,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"upperKeys"),Fe.default=t,Fe}l(Ua,"requireUppercaseKeysObject");var qe={},Ji;function Ja(){if(Ji)return qe;Ji=1;var n=qe&&qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Be(),t=Ii();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"camelKeys"),qe.default=s,qe}l(Ja,"requireCamelcaseKeysObject");var Ue={},Vi;function Va(){if(Vi)return Ue;Vi=1;var n=Ue&&Ue.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ue,"__esModule",{value:!0});var e=Be(),t=Li();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"snakeKeys"),Ue.default=s,Ue}l(Va,"requireSnakecaseKeysObject");var Je={},Wi;function Wa(){if(Wi)return Je;Wi=1;var n=Je&&Je.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Je,"__esModule",{value:!0});var e=Be(),t=Pi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"pascalKeys"),Je.default=s,Je}l(Wa,"requirePascalcaseKeysObject");var Ve={},zi;function za(){if(zi)return Ve;zi=1;var n=Ve&&Ve.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ve,"__esModule",{value:!0});var e=Be(),t=Bi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"kebabKeys"),Ve.default=s,Ve}l(za,"requireKebabcaseKeysObject");var Hi;function Ha(){if(Hi)return x;Hi=1,Object.defineProperty(x,"__esModule",{value:!0}),x.kebabKeys=x.pascalKeys=x.snakeKeys=x.camelKeys=x.upperKeys=x.lowerKeys=x.toLowerCase=x.toUpperCase=x.toKebabCase=x.toHeaderCase=x.toSentenceCase=x.toTextCase=x.toPathCase=x.toDotCase=x.toPascalCase=x.toSnakeCase=x.toCamelCase=void 0;var n=Ii();x.toCamelCase=n.default;var e=Li();x.toSnakeCase=e.default;var t=Pi();x.toPascalCase=t.default;var s=Da();x.toDotCase=s.default;var i=Ma();x.toPathCase=i.default;var r=Ra();x.toTextCase=r.default;var o=Ba();x.toSentenceCase=o.default;var a=Fa();x.toHeaderCase=a.default;var c=Bi();x.toKebabCase=c.default;var u=qa();x.lowerKeys=u.default;var d=Ua();x.upperKeys=d.default;var f=Ja();x.camelKeys=f.default;var h=Va();x.snakeKeys=h.default;var m=Wa();x.pascalKeys=m.default;var w=za();x.kebabKeys=w.default;var p=l(function(b){return String(b||"").toLowerCase()},"toLowerCase");x.toLowerCase=p;var y=l(function(b){return String(b||"").toUpperCase()},"toUpperCase");x.toUpperCase=y;var S={toCamelCase:n.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:s.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return x.default=S,x}l(Ha,"requireLib");var Gn,Gi;function Ga(){return Gi||(Gi=1,Gn=Ha()),Gn}l(Ga,"requireJsConvertCase");var We=Ga();const ut={[I.Integration]:{element:"integration",elements:"integrations",exportable:!1},[I.Connector]:{element:"connector",elements:"connectors",exportable:!1},[I.Action]:{element:"action",elements:"actions",integrationSpecific:!0},[I.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[I.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[I.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[I.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[I.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0},[I.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0},[I.Customer]:{element:"customer",elements:"customers"},[I.FlowInstance]:{element:"flowInstance",elements:"flowInstances"},[I.FlowRun]:{element:"flowRun",elements:"flowRuns"},[I.Scenario]:{element:"scenario",elements:"scenarios"},[I.ActionInstance]:{element:"actionInstance",elements:"actionInstances"},[I.Connection]:{element:"connection",elements:"connections"},[I.FieldMappingInstance]:{element:"fieldMappingInstance",elements:"fieldMappingInstances"},[I.DataSourceInstance]:{element:"dataSourceInstance",elements:"dataSourceInstances"},[I.DataLinkTableInstance]:{element:"dataLinkTableInstance",elements:"dataLinkTableInstances"},[I.AppEventSubscription]:{element:"appEventSubscription",elements:"appEventSubscriptions"},[I.AppDataSchemaInstance]:{element:"appDataSchemaInstance",elements:"appDataSchemaInstances"},[I.ExternalEventSubscription]:{element:"externalEventSubscription",elements:"externalEventSubscriptions"},[I.ExternalEventLogRecord]:{element:"externalEventLogRecord",elements:"externalEventLogRecords"},[I.ExternalEventPull]:{element:"externalEventPull",elements:"externalEventPulls"},[I.DataCollection]:{element:"dataCollection",elements:"dataCollections"},[I.Screen]:{element:"screen",elements:"screens"},[I.ActionRunLogRecord]:{element:"actionRunLogRecord",elements:"actionRunLogRecords"}};class Ya{static{l(this,"WorkspaceElementService")}constructor(e){this.fileWatcher=e,this.setupEventHandlers()}client;workspaceDataCache={};cacheExpirationTime=300*1e3;lastCacheUpdate=0;async init(){this.client=await Cs.getClient(this.fileWatcher.getCwd())}setupEventHandlers(){this.fileWatcher.on("added",e=>this.processElementChange(e,"added")),this.fileWatcher.on("changed",e=>this.processElementChange(e,"changed")),this.fileWatcher.on("deleted",e=>this.processElementChange(e,"deleted"))}async processElementChange(e,t){try{const s=ws(e.relativePath);if(!s||!s.key||!s.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${s.key} of type ${s.type}`),t){case"added":case"changed":await this.pushElement(s.type,{...e.data,key:s.key});break;case"deleted":break}}catch(s){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,s)}}async pushElement(e,t){if(!ut[e])throw new Error(`Unknown element type: ${e}`);const i={...t},r=await this.getWorkspaceData();delete i.integrationId;const o=this.matchElement(i,e,r);o?await this.handleExistingElement(e,i,o):await this.handleNewElement(e,i,r)}async handleExistingElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await this.client[r](s.id).put(t),console.debug(`Updated ${t.integrationKey||"universal"} ${i.element} ${t.key}`);else if(this.hasParent(t))try{await this.client[r](s.id).reset(),console.debug(`Customization reset ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(o){throw console.debug("Error resetting element:",s,t),o}else console.warn(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}async handleNewElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name),o=We.toCamelCase(ie[e].namePlural);if(this.hasParent(t)){try{await this.client[r]({key:t.key}).apply([t.integrationKey])}catch{try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey,s);await this.client[o].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t),console.debug(`Applied & Customized ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug("Error customizing element:",t),a}else console.debug(`Applied universal ${i.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const a=this.findIntegrationId(t.integrationKey,s);t.integrationId=a}await this.client[o].create(t),console.debug(`Created ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug(`Error creating element ${e}`,this.hasParent(t),t.integrationKey,t),a}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}matchElement(e,t,s){const i=s[t]?.filter(r=>r.key===e.key&&r.integrationKey===e.integrationKey&&!r.archivedAt);if(!(!i||i.length===0)){if(i.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return i[0]}}findIntegrationId(e,t){const s=t.integration?.find(i=>i.key===e);if(!s)throw new Error(`Integration with key ${e} not found`);return s.id}async getWorkspaceData(){const e=Date.now();if(this.lastCacheUpdate&&e-this.lastCacheUpdate<this.cacheExpirationTime)return this.workspaceDataCache;console.debug("Refreshing workspace data cache");const t={};try{const s=await this.client.integrations.findAll();t.integration=s.map(i=>({id:i.id,key:i.key,name:i.name}));for(const i of Object.keys(ut)){const r=ut[i];if(r.exportable!==!1)try{const o=[],a=await this.client[r.elements].findAll();if(o.push(...a),r.integrationSpecific)for(const c of s)try{const u=await this.client[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>({...d,integrationKey:c.key})))}catch(u){console.error(`Failed to fetch ${i} for integration ${c.key}:`,u)}t[i]=o}catch(o){console.error(`Failed to fetch ${i} elements:`,o),t[i]=[]}}return this.workspaceDataCache=t,this.lastCacheUpdate=e,console.debug("Workspace data cache refreshed successfully"),t}catch(s){return console.error("Failed to refresh workspace data cache:",s),Object.keys(this.workspaceDataCache).length>0?(console.debug("Using existing workspace data cache due to refresh failure"),this.workspaceDataCache):{integration:[]}}}}const Za={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Qa={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class E{static{l(this,"Logger")}static formatMessage(e,t,s={}){const i=s.timestamp?`${k.gray(new Date().toISOString())} `:"",r=s.prefix?`${k.gray(s.prefix)} `:"",o=s.suffix?` ${k.gray(s.suffix)}`:"",a=Za[t],c=Qa[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let s=k.blue;if(t?.color&&(s=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${s(e)}`)}else console.debug(s(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
141
142
|
${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
|
|
142
143
|
${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const s=t||Object.keys(e[0]),i=e.map(r=>{const o={};return s.forEach(a=>{o[a]=r[a]}),o});console.table(i,s)}static divider(){}}const Yi=Sr(process.argv.slice(2)),Zi=Yi.cwd?mr(Yi.cwd):process.cwd();async function Xa(){try{await ec.init()}catch(n){E.error(n.toString()),process.exit(1)}}l(Xa,"startBackgroundServices");const Qi=new Ka({cwd:Zi}),ec=new Ya(Qi),tc=l(()=>g(Gr,{cwd:Zi,children:g(po,{fileWatcher:Qi,children:g(Qr,{children:g(kr,{value:{fetcher:ro()},children:g(Co,{})})})})}),"App");function nc(){Xa(),br(g(tc,{}))}l(nc,"runAgent");async function sc(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Ye.sign(t,e)}l(sc,"generateAdminAccessToken");async function ic(n,e){return(await ln.get(`${n}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(ic,"fetchOpenApiSchema");function Xi(n,e=!0){if(!n)return e?F.string():F.string().optional();let t;switch(n.type){case"integer":t=F.coerce.number().int();break;case"number":t=F.coerce.number();break;case"boolean":t=F.coerce.boolean();break;case"string":default:t=F.string();break}return n.format==="uuid"?t=F.string().uuid():n.format==="email"?t=F.string().email():n.format==="date"?t=F.string().regex(/^\d{4}-\d{2}-\d{2}$/):n.format==="date-time"&&(t=F.string().datetime()),n.enum&&(t=F.enum(n.enum)),(n.type==="integer"||n.type==="number")&&(n.minimum!==void 0&&(t=t.min(n.minimum)),n.maximum!==void 0&&(t=t.max(n.maximum))),n.type==="string"&&(n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength))),e?t:t.optional()}l(Xi,"convertOpenApiSchemaToZod");function er(n){const e=n.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(er,"extractPathParameters");function rc(n,e,t,s,i){const r=n.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,o=n.description||n.summary||`${t.toUpperCase()} ${e}`,a={},c={},u={};if(n.parameters){for(const f of n.parameters)if(f.in==="path")c[f.name]=Xi(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const h=f.required===!0;u[f.name]=Xi(f.schema,h).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(c).length>0&&(a.params=F.object(c).describe("Path parameters")),Object.keys(u).length>0&&(a.query=F.object(u).describe("Query parameters")),n.requestBody&&n.requestBody.content&&n.requestBody.content["application/json"]&&(a.body=F.any().describe("Request body"));const d=Object.keys(a).length>0?F.object(a):F.object({});return{name:r,description:o,parameters:d,async execute(f){try{const h=er(e);if(h.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const b=h.filter(C=>!(C in f.params));if(b.length>0)throw new Error(`Missing required path parameters: ${b.join(", ")}`)}let m=`${s}${e}`;if(f.params)for(const[b,C]of Object.entries(f.params)){const A=`{${b}}`;m.includes(A)&&(m=m.replace(A,String(C)))}const w=er(m);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const p=new URLSearchParams;if(f.query)for(const[b,C]of Object.entries(f.query))C!=null&&p.append(b,String(C));p.toString()&&(m+=`?${p.toString()}`);const y={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(y.data=f.body);const S=await ln.request({url:m,...y});return{content:[{type:"text",text:JSON.stringify(S.data,null,2)}]}}catch(h){return ln.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(rc,"createApiTool");function oc(n,e,t){const s=[];if(!n.paths)return s;for(const[i,r]of Object.entries(n.paths))if(typeof r=="object"&&r!==null){for(const[o,a]of Object.entries(r))if(["get","post","put","delete","patch"].includes(o)&&a&&typeof a=="object"){const c=rc(a,i,o,e,t);s.push(c)}}return s}l(oc,"convertOpenApiToTools");function ac(n){n.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
|
|
143
144
|
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=de();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||gn,s=await sc(e.workspaceKey,e.workspaceSecret),i=await ic(t,s),r=oc(i,t,s),o=new Mr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@membranehq/cli",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"cli",
|
|
6
6
|
"integration",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"@buildwithlayer/openapi-to-tools": "^1.3.3",
|
|
34
34
|
"@faker-js/faker": "^9.8.0",
|
|
35
35
|
"@inkjs/ui": "^2.0.0",
|
|
36
|
-
"@
|
|
36
|
+
"@membranehq/sdk": "^0.1.0",
|
|
37
37
|
"@types/jsonwebtoken": "^9.0.10",
|
|
38
38
|
"archiver": "^7.0.1",
|
|
39
39
|
"axios": "^1.10.0",
|
|
@@ -52,8 +52,8 @@
|
|
|
52
52
|
"lodash": "^4.17.21",
|
|
53
53
|
"minimist": "^1.2.8",
|
|
54
54
|
"open": "^8.4.2",
|
|
55
|
-
"react": "^
|
|
56
|
-
"react-dom": "^
|
|
55
|
+
"react": "^18.3.1",
|
|
56
|
+
"react-dom": "^18.3.1",
|
|
57
57
|
"swr": "^2.3.4",
|
|
58
58
|
"unzipper": "^0.12.3",
|
|
59
59
|
"zod": "^3.25.76"
|