@membranehq/cli 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var Fi=Object.defineProperty;var c=(s,e)=>Fi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as I,Fragment as Yt}from"react/jsx-runtime";import*as D from"node:path";import{resolve as Bi,dirname as Ui,join as qi}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Ji,render as dt}from"ink";import Wi from"minimist";import{SWRConfig as Gi}from"swr";import Vi from"os";import F from"path";import Hi from"conf";import De,{createContext as zt,useContext as Qt,useState as K,useEffect as ye,useCallback as ts,useMemo as Yi,useRef as zi}from"react";import*as x from"node:fs";import{readFileSync as Qi}from"node:fs";import de from"js-yaml";import{z as B}from"zod";import{exec as Xi}from"node:child_process";import*as Zi from"node:crypto";import{createHash as er}from"node:crypto";import*as tr from"node:os";import{TextInput as nr,Select as sr}from"@inkjs/ui";import ht from"ink-spinner";import ns from"swr/immutable";import ir from"ink-text-input";import{EventEmitter as rr}from"events";import{WorkspaceElementType as U,IntegrationAppClient as ss,WorkspaceElementSpecs as he,setValueAtLocator as Xt,extractIntegrationAppErrorData as ce,getDataCollectionCreateFields as Zt,excludeWriteOnlyFieldsFromSchema as is,valueToSchema as pt,getRequiredFieldsFromSchema as or,getValueAtLocator as ar,walkSchema as rs,makeDataLocationPath as os,getDataCollectionUpdateFields as en}from"@membranehq/sdk";import j from"fs";import cr from"archiver";import lr from"form-data";import ur from"unzipper";import tn from"jsonwebtoken";import fr from"lodash/isEqual.js";import dr from"chokidar";import{fileURLToPath as hr}from"node:url";import k from"chalk";import{Command as pr}from"commander";import nn from"axios";import{FastMCP as mr}from"fastmcp";import sn from"lodash/merge.js";import gr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import yr from"lodash/template.js";import wr from"lodash/templateSettings.js";const br="membrane",Sr="membrane.config.yml",rn="https://api.integration.app";function on(){const s=process.cwd(),e=D.join(s,br),t=D.join(s,Sr),n=e,i=D.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(on,"getPaths");function Cr(){return on().membraneDirPath}c(Cr,"getBasePath");const kr={pat:{type:"string"},workspace:{type:"object"}},as=new Hi({schema:kr,configName:"config",cwd:F.join(Vi.homedir(),".membrane")}),vr=c(s=>{as.set("pat",s)},"setPat"),cs=c(()=>as.get("pat"),"getPat");class ls{static{c(this,"AccountApiClient")}constructor(e=rn){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=cs();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});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 Er=c(s=>{const e=new ls(rn);return t=>e.get(t)},"createAccountApiFetcher"),us=zt(process.cwd());function Tr({cwd:s,children:e}){return m(us.Provider,{value:s,children:e})}c(Tr,"CwdProvider");function fs(){return Qt(us)}c(fs,"useCwd");const Ir="membrane.config.yml";function Pe(s){const e=D.join(s??process.cwd(),Ir);try{const t=x.readFileSync(e,"utf8"),n=de.load(t),i=ds.safeParse(n);return i.success?i.data:null}catch{return null}}c(Pe,"readProjectConfig");const Nr="membrane.config.yml",ds=B.object({workspaceKey:B.string().optional(),workspaceSecret:B.string().optional(),apiUri:B.string().optional(),testCustomerId:B.string().optional(),anthropicApiKey:B.string().optional()});B.enum(["pull"]);const hs=zt(void 0);function Ar({children:s}){const e=fs(),[t,n]=K(null),[i,r]=K(!0);ye(()=>{const u=Pe(e);n(u),r(!1)},[e]);const o=ts(u=>{const p=D.join(e,Nr),f={...Pe(e)??{},...u},g=ds.safeParse(f);return g.success?(x.writeFileSync(p,de.dump(g.data)),n(g.data),!0):!1},[e]),a=ts(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),l={config:t,isLoading:i,updateConfig:o,validateConfig:a};return m(hs.Provider,{value:l,children:s})}c(Ar,"ProjectConfigProvider");function Ze(){const s=Qt(hs);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}c(Ze,"useProjectConfig");function mt({cwd:s,children:e}){const t=s||process.cwd();return m(Tr,{cwd:t,children:m(Ar,{children:m(Gi,{value:{fetcher:Er()},children:e})})})}c(mt,"Layout");const an=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".cursor"),e=D.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Or({onExit:s,onComplete:e}){const[t,n]=K(0),[i,r]=K(!1),[o,a]=K(null),[l,u]=K(""),[p,d]=K("");xe((w,h)=>{if(l||p){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?f(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(an.length-1,t+1));else if(h.return||w===" "){const y=an[t];a(y),r(!0)}});const f=c(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[I(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:I(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:an.map((w,h)=>I(b,{children:[I(S,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),I(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Or,"AddMcpServerScreen");const we=D.join(tr.tmpdir(),"membrane-mcp-status"),ps=3e4;function cn(s){return er("md5").update(s).digest("hex").slice(0,8)}c(cn,"getCwdHash");function ln(s,e){const t=cn(e);return D.join(we,`mcp-${t}-${s}.json`)}c(ln,"getStatusFilePath");function Me(s,e){try{const t=e||process.cwd();if(!s){const i=gt(t);return i.length===0?null:i[0]}const n=ln(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ps)return et(s,t),null;const a=x.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>ps)return et(s,t),null}return l}}catch{s&&e&&et(s,e)}return null}c(Me,"getMcpStatus");function gt(s){try{const e=s||process.cwd(),t=cn(e);if(!x.existsSync(we))return[];const n=x.readdirSync(we),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=Me(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(gt,"getAllMcpStatusFiles");function un(s){try{const t={...Me(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(we)||x.mkdirSync(we,{recursive:!0});const n=ln(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(un,"updateMcpStatus");function et(s,e){try{const t=e||process.cwd();if(s){const n=ln(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=cn(t);if(x.existsSync(we)){const i=x.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(D.join(we,r))}}}catch{}}c(et,"clearMcpStatus");function $r(s,e){const t=Me(s,e);t&&un({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c($r,"trackToolExecution");function Lr(){const[s,e]=K(Me()),[t,n]=K(gt()),[i,r]=K(null);return ye(()=>{try{const a=process.cwd();e(Me(void 0,a)),n(gt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),n([])}const o=setInterval(()=>{try{const a=process.cwd(),l=Me(void 0,a),u=gt(a);e(l),n(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),n([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Lr,"useMcpStatus");function xr(){const{error:s,serverCount:e,allMcpServers:t}=Lr(),n=Math.min(100,process.stdout.columns||100);return I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:I(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Ji,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:I(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(xr,"Agent");function ms({onExit:s,showEscOption:e=!0}){const[t,n]=K(""),{data:i,error:r,isLoading:o}=ns("/account"),{updateConfig:a,isLoading:l}=Ze(),u=i?.workspaces,p=o||l;if(xe((y,C)=>{C.escape&&s?.()}),p)return I(b,{children:[m(ht,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return I(b,{flexDirection:"column",children:[I(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const d=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(y=>({label:y.name,value:y.id})),g=f.length,w=u?.length??0;async function h(y){const C=d.find(T=>T.id===y);if(!C)return;const{key:v,secret:A}=C;!v||!A||(await a({workspaceKey:v,workspaceSecret:A}),s?.())}return c(h,"handleSelect"),I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),I(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(nr,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&I(S,{children:["Showing ",g," of ",w," workspaces."]}),m(b,{marginTop:1,children:m(sr,{options:f,onChange:c(y=>{y&&h(y)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ms,"SelectWorkspace");function Dr({currentPat:s,onSubmit:e}){const[t,n]=K(""),[i,r]=K(!1),[o,a]=K(null);return I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(ir,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:I(S,{children:[m(ht,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Dr,"PersonalAccessTokenInput");var tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(tt||{});const Pr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=c(()=>{const{config:s}=Ze(),e=!!(s?.workspaceKey&&s?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),fn=[tt.Authenticate,tt.ConnectWorkspace];function ys({onComplete:s}){const[e,t]=K(!1),[n,i]=K(0),{isSetupComplete:r}=gs(),o=cs(),a=fn[n],l=n+1,u=fn.length,p=fn.map((g,w)=>{let h="pending";return w<n?h="done":w===n&&(h="current"),{id:g,label:Pr[g],status:h}});async function d(g){const w=o&&g===""?o:g,h=new ls;try{await h.request("/account",{headers:{Authorization:`Bearer ${w}`}}),vr(w),i(y=>y+1)}catch(y){console.error(y)}}c(d,"handlePatSubmit");function f(){t(!0),s&&s()}return c(f,"handleWorkspaceSelected"),xe((g,w)=>{r&&w.escape&&s&&s()}),e?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):I(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(S,{color:"cyan",children:["Step ",l," of ",u]}),r&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:p.map(g=>m(Mr,{status:g.status,label:g.label},g.id))})]}),a===tt.Authenticate&&m(Dr,{currentPat:o,onSubmit:d}),a===tt.ConnectWorkspace&&m(ms,{onExit:f,showEscOption:!1})]})}c(ys,"Setup");function Mr({status:s,label:e}){return I(b,{children:[I(b,{width:2,children:[s==="current"&&m(ht,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Mr,"StepDisplay");const te={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged"};class ws extends rr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class jr extends ws{static{c(this,"WorkspaceNotifications")}constructor(){super()}setState(e){this.emit(te.StateChanged,{state:e})}setConflicts(e){this.emit(te.ConflictsChanged,{conflicts:e})}setStats(e){this.emit(te.StatsChanged,{stats:e})}addLog(e){this.emit(te.LogAdded,{log:e})}}const re=new jr,ne={[U.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[U.Connector]:{element:"connector",elements:"connectors",exportable:!1},[U.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[U.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[U.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[U.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[U.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[U.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[U.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Rr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Rr,"baseExportCleanup");class bs{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}class Kr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=re}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const $=new Kr;class Ss{static{c(this,"ElementsManager")}cache;handler;constructor(e){this.cache=new bs,this.handler=e}async refresh(){try{const e=new bs,t=await this.handler.getIntegrations();e.addAll(t);const n=[U.Integration,U.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){$.error(`Failed to refresh elements: ${e instanceof Error?e.message:"Unknown error"}`)}}async putElement(e){let t;try{e.data.id?t=await this.handler.updateElement(e):t=await this.handler.createElement(e),this.cache.put(t)}catch(n){$.error(`Failed to ${e.data.id?"update":"create"} element: ${n instanceof Error?n.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e),this.cache.remove(e)}catch(t){$.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}}async function _r(s,e="full"){const t={};$.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>dn("integration",i));for(const i of Object.keys(ne)){const r=ne[i];if(r.exportable===!1)continue;const o=[];$.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>dn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,dn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return $.success("[connectors] Remote workspace data retrieved successfully"),t}c(_r,"getWorkspaceData");function dn(s,e){return e=Rr(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}c(dn,"cleanUpForExport");class Fr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return tn.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=Pe(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 ss({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 n=!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||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const yt=new Fr;async function Cs(s){const e=await yt.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(Cs,"getWorkspaceId");const ks="connectors",vs="development",hn={};async function Br({integrations:s,allConnectors:e=!1}){const t=Cr(),n=await yt.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Es({client:n,connectorId:a});(!!u.workspaceId||e)&&(i.has(a)||(await Vr({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await Hr({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Br,"pullConnectors");async function Ur(){const s=await yt.getClient(process.cwd()),e=await _r(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};$.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);$.info("[connectors] Loading public connectors"),e.connector=o;const a=pn(),u=(j.existsSync(a)?j.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=F.join(a,p);try{return j.statSync(d).isDirectory()}catch{return!1}});for(const p of u){$.info(`[connectors] Loading connector from: ${p}`);const d=j.readdirSync(F.join(a,p)),f=await qr(p);if("baseUri"in f&&delete f.baseUri,f.uuid&&e.connector?.find(w=>w.uuid==f.uuid))i[f.id]=e.connector.find(w=>w.uuid==f.uuid).id,$.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!i[f.id])if(!!(await Es({client:s,connectorId:f.id})).workspaceId){$.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const y=await r.post("connectors",{...f,workspaceId:n});i[f.id]=y.id}else{$.info(`[connectors] Skipping public connector ${f.name} (${f.key})`);continue}const g=d.filter(w=>j.statSync(F.join(a,p,w)).isDirectory());for(const w of g)await Gr({client:s,connector:f,version:w,connectorId:i[f.id]})}}c(Ur,"pushConnectors");function pn(){const s=on();return F.join(s.membraneDirPath,ks)}c(pn,"getConnectorsPath");async function qr(s){return de.load(j.readFileSync(F.join(pn(),s,`${s}.yml`),"utf8"))}c(qr,"readConnector");async function Jr(s,e){return $.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=j.createWriteStream(e),r=cr("zip",{zlib:{level:9}});i.on("close",()=>{$.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{$.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=j.readdirSync(s);for(const a of o){const l=F.join(s,a),u=j.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(Jr,"createZipArchive");async function Wr(s,e){return $.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=ur.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=F.join(e,o);j.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=F.join(e,o),u=F.dirname(l);j.mkdirSync(u,{recursive:!0});const p=j.createWriteStream(l);r.pipe(p),p.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{$.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(Wr,"extractZipArchive");async function Gr({client:s,connector:e,version:t,connectorId:n}){const i=F.join(pn(),wt(e),Ts(t)),r=F.join(i,"src"),o=F.join(i,"src.zip"),a=j.existsSync(o);if(j.existsSync(r)&&($.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await Jr(r,o)),!j.existsSync(o)){$.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new lr;if(l.append("file",j.createReadStream(o),"file.zip"),$.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==vs)$.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){$.info(`[connectors] Version ${t} already published`);return}$.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}$.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch{$.error(`Error pushing connector version ${t} for ${e.name}`)}finally{!a&&j.existsSync(o)&&($.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),j.unlinkSync(o))}}c(Gr,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(hn[e])return hn[e];const t=await s.get(`connectors/${e}`);return hn[e]=t,t}c(Es,"getConnector");async function Vr({basePath:s,connector:e}){const t=wt(e),n=F.join(s,ks,t);j.mkdirSync(n,{recursive:!0});const i=F.join(n,`${wt(e)}.yml`);j.writeFileSync(i,de.dump(e)),$.info(`[connectors] Pulled connector ${e.name}`)}c(Vr,"pullConnector");async function Hr({client:s,connector:e,connectorVersion:t,basePath:n}){const i=wt(e),r=Ts(t),o=F.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});j.mkdirSync(o,{recursive:!0});const l=F.join(o,"src.zip");j.writeFileSync(l,a);const u=F.join(o,"src");j.existsSync(u)&&await Wr(a,u),$.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(Hr,"pullConnectorVersion");function wt(s){return s.key}c(wt,"getConnectorDirName");function Ts(s){return s??vs}c(Ts,"getConnectorVersionDirName");const P={NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},Yr="membrane",zr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function bt(s){return D.join(s,Yr)}c(bt,"getMembraneDir");const Qr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],Is=[U.Action,U.FieldMapping,U.Flow,U.DataSource];class V{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=he[this.type].apiPath;if(this.integrationKey){const t=he[U.Integration].apiPath;return D.join(t,this.integrationKey,e,this.key)}return D.join(e,this.key)}get path(){return D.join(this.dirPath,"spec.yaml")}get relativePath(){return D.relative(bt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return fr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Qr.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ne?.[this.type]?.parentKey&&(e=ne?.[this.type]?.parentKey),e}static new(e,t,n,i){return new V(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;if(n)return V.new(n.type,i,n.integrationKey,t)}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===U.Integration?`${e}:${t}`:V.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(this.isConnectorFile(t)||!this.isElementFile(t))return;const n=Object.values(he).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static isConnectorFile(e){const[t]=e.split(D.sep);return t===he[U.Connector].apiPath}static getElementTypeFromPath(e){return Object.values(U).find(t=>he[t].apiPath===e)}static getRelativePath(e){return D.relative(bt(process.cwd()),e)}static isIntegrationSpecific(e){return Is.includes(e)}static canBeIntegrationSpecific(e){return Is.includes(e)}}class Xr{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=bt(process.cwd())}async getElementsByType(e,t){const n=[],i=D.join(this.basePath,he[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=D.join(this.basePath,he[U.Integration].apiPath,o.key,he[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&$.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e)}async updateElement(e){if(!e.data)throw new Error("Element must have data to write");const t=D.join(this.basePath,e.dirPath),n=D.join(this.basePath,e.path);return x.existsSync(t)||x.mkdirSync(t,{recursive:!0}),x.writeFileSync(n,de.dump(e.data)),$.info(`[local] Written ${e.relativePath}`),e}async deleteElement(e){const t=D.join(this.basePath,e.path),n=D.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),$.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=D.join(this.basePath,he[U.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=de.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=D.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(D.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Zr{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&$.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const n=await(await this.getClient())[ne[e.type].element](e.data.id).get();return V.fromData(e.type,n)}async createElement(e){const t=e.clean(),i=await(await this.getClient())[ne[e.type].elements].create(t),r=V.fromData(e.type,i);return $.info(`[remote] Created ${r.id}`),r}async updateElement(e){if(!e.data.id)throw new Error("Element must have an id to update");const t=e.clean(),i=await(await this.getClient())[ne[e.type].element](e.data.id).put(t),r=V.fromData(e.type,i);return $.info(`[remote] Updated ${e.id}`),r}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[ne[e.type].element](e.data.id).archive(),$.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>V.fromData(U.Integration,i));return n.length>0&&$.success(`[remote] Fetched ${n.length} integrations`),n}async findAll(e,t={}){return(await(await this.getClient())[ne[e].elements].findAll(t)).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await yt.getClient(process.cwd())),this.client}}const mn=Symbol.for("yaml.alias"),gn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),le=Symbol.for("yaml.scalar"),je=Symbol.for("yaml.seq"),se=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[se]===mn,"isAlias"),Ee=c(s=>!!s&&typeof s=="object"&&s[se]===gn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[se]===be,"isMap"),_=c(s=>!!s&&typeof s=="object"&&s[se]===Ns,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[se]===le,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[se]===je,"isSeq");function q(s){if(s&&typeof s=="object")switch(s[se]){case be:case je:return!0}return!1}c(q,"isCollection$1");function J(s){if(s&&typeof s=="object")switch(s[se]){case mn:case be:case le:case je:return!0}return!1}c(J,"isNode");const As=c(s=>(R(s)||q(s))&&!!s.anchor,"hasAnchor"),X=Symbol("break visit"),Os=Symbol("skip children"),ue=Symbol("remove node");function Te(s,e){const t=$s(e);Ee(s)?_e(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Te,"visit$1"),Te.BREAK=X,Te.SKIP=Os,Te.REMOVE=ue;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(J(i)||_(i))return xs(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=_e(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=_e("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(_e,"visit_");async function St(s,e){const t=$s(e);Ee(s)?await Fe(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(St,"visitAsync"),St.BREAK=X,St.SKIP=Os,St.REMOVE=ue;async function Fe(s,e,t,n){const i=await Ls(s,e,t,n);if(J(i)||_(i))return xs(s,n,i),Fe(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Fe(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(Fe,"visitAsync_");function $s(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c($s,"initVisitor");function Ls(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(_(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(q(n))n.items[s]=t;else if(_(n))s==="key"?n.key=t:n.value=t;else if(Ee(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const eo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},to=c(s=>s.replace(/[!,[\]{}]/g,e=>eo[e]),"escapeTagName");class Q{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Q.defaultYaml,e),this.tags=Object.assign({},Q.defaultTags,t)}clone(){const e=new Q(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Q(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Q.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Q.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Q.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Q.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;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[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+to(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&J(e.contents)){const r={};Te(e.contents,(o,a)=>{J(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
2
+ var Fi=Object.defineProperty;var c=(s,e)=>Fi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as I,Fragment as Yt}from"react/jsx-runtime";import*as D from"node:path";import{resolve as Bi,dirname as Ui,join as qi}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Ji,render as dt}from"ink";import Wi from"minimist";import{SWRConfig as Gi}from"swr";import Vi from"os";import F from"path";import Hi from"conf";import De,{createContext as zt,useContext as Qt,useState as K,useEffect as ye,useCallback as ts,useMemo as Yi,useRef as zi}from"react";import*as x from"node:fs";import{readFileSync as Qi}from"node:fs";import de from"js-yaml";import{z as B}from"zod";import{exec as Xi}from"node:child_process";import*as Zi from"node:crypto";import{createHash as er}from"node:crypto";import*as tr from"node:os";import{TextInput as nr,Select as sr}from"@inkjs/ui";import ht from"ink-spinner";import ns from"swr/immutable";import ir from"ink-text-input";import{EventEmitter as rr}from"events";import{WorkspaceElementType as U,IntegrationAppClient as ss,WorkspaceElementSpecs as he,setValueAtLocator as Xt,extractIntegrationAppErrorData as ce,getDataCollectionCreateFields as Zt,excludeWriteOnlyFieldsFromSchema as is,valueToSchema as pt,getRequiredFieldsFromSchema as or,getValueAtLocator as ar,walkSchema as rs,makeDataLocationPath as os,getDataCollectionUpdateFields as en}from"@membranehq/sdk";import j from"fs";import cr from"archiver";import lr from"form-data";import ur from"unzipper";import tn from"jsonwebtoken";import fr from"lodash/isEqual.js";import dr from"chokidar";import{fileURLToPath as hr}from"node:url";import k from"chalk";import{Command as pr}from"commander";import nn from"axios";import{FastMCP as mr}from"fastmcp";import sn from"lodash/merge.js";import gr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import yr from"lodash/template.js";import wr from"lodash/templateSettings.js";const br="membrane",Sr="membrane.config.yml",rn="https://api.integration.app";function on(){const s=process.cwd(),e=D.join(s,br),t=D.join(s,Sr),n=e,i=D.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(on,"getPaths");function Cr(){return on().membraneDirPath}c(Cr,"getBasePath");const kr={pat:{type:"string"},workspace:{type:"object"}},as=new Hi({schema:kr,configName:"config",cwd:F.join(Vi.homedir(),".membrane")}),vr=c(s=>{as.set("pat",s)},"setPat"),cs=c(()=>as.get("pat"),"getPat");class ls{static{c(this,"AccountApiClient")}constructor(e=rn){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=cs();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});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 Er=c(s=>{const e=new ls(rn);return t=>e.get(t)},"createAccountApiFetcher"),us=zt(process.cwd());function Tr({cwd:s,children:e}){return m(us.Provider,{value:s,children:e})}c(Tr,"CwdProvider");function fs(){return Qt(us)}c(fs,"useCwd");const Ir="membrane.config.yml";function Pe(s){const e=D.join(s??process.cwd(),Ir);try{const t=x.readFileSync(e,"utf8"),n=de.load(t),i=ds.safeParse(n);return i.success?i.data:null}catch{return null}}c(Pe,"readProjectConfig");const Nr="membrane.config.yml",ds=B.object({workspaceKey:B.string().optional(),workspaceSecret:B.string().optional(),apiUri:B.string().optional(),testCustomerId:B.string().optional(),anthropicApiKey:B.string().optional()});B.enum(["pull"]);const hs=zt(void 0);function Ar({children:s}){const e=fs(),[t,n]=K(null),[i,r]=K(!0);ye(()=>{const u=Pe(e);n(u),r(!1)},[e]);const o=ts(u=>{const p=D.join(e,Nr),f={...Pe(e)??{},...u},g=ds.safeParse(f);return g.success?(x.writeFileSync(p,de.dump(g.data)),n(g.data),!0):!1},[e]),a=ts(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),l={config:t,isLoading:i,updateConfig:o,validateConfig:a};return m(hs.Provider,{value:l,children:s})}c(Ar,"ProjectConfigProvider");function Ze(){const s=Qt(hs);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}c(Ze,"useProjectConfig");function mt({cwd:s,children:e}){const t=s||process.cwd();return m(Tr,{cwd:t,children:m(Ar,{children:m(Gi,{value:{fetcher:Er()},children:e})})})}c(mt,"Layout");const an=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".cursor"),e=D.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Or({onExit:s,onComplete:e}){const[t,n]=K(0),[i,r]=K(!1),[o,a]=K(null),[l,u]=K(""),[p,d]=K("");xe((w,h)=>{if(l||p){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?f(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(an.length-1,t+1));else if(h.return||w===" "){const y=an[t];a(y),r(!0)}});const f=c(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[I(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:I(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:an.map((w,h)=>I(b,{children:[I(S,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),I(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Or,"AddMcpServerScreen");const we=D.join(tr.tmpdir(),"membrane-mcp-status"),ps=3e4;function cn(s){return er("md5").update(s).digest("hex").slice(0,8)}c(cn,"getCwdHash");function ln(s,e){const t=cn(e);return D.join(we,`mcp-${t}-${s}.json`)}c(ln,"getStatusFilePath");function Me(s,e){try{const t=e||process.cwd();if(!s){const i=gt(t);return i.length===0?null:i[0]}const n=ln(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ps)return et(s,t),null;const a=x.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>ps)return et(s,t),null}return l}}catch{s&&e&&et(s,e)}return null}c(Me,"getMcpStatus");function gt(s){try{const e=s||process.cwd(),t=cn(e);if(!x.existsSync(we))return[];const n=x.readdirSync(we),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=Me(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(gt,"getAllMcpStatusFiles");function un(s){try{const t={...Me(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(we)||x.mkdirSync(we,{recursive:!0});const n=ln(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(un,"updateMcpStatus");function et(s,e){try{const t=e||process.cwd();if(s){const n=ln(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=cn(t);if(x.existsSync(we)){const i=x.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(D.join(we,r))}}}catch{}}c(et,"clearMcpStatus");function $r(s,e){const t=Me(s,e);t&&un({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c($r,"trackToolExecution");function Lr(){const[s,e]=K(Me()),[t,n]=K(gt()),[i,r]=K(null);return ye(()=>{try{const a=process.cwd();e(Me(void 0,a)),n(gt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),n([])}const o=setInterval(()=>{try{const a=process.cwd(),l=Me(void 0,a),u=gt(a);e(l),n(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),n([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Lr,"useMcpStatus");function xr(){const{error:s,serverCount:e,allMcpServers:t}=Lr(),n=Math.min(100,process.stdout.columns||100);return I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:I(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Ji,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:I(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(xr,"Agent");function ms({onExit:s,showEscOption:e=!0}){const[t,n]=K(""),{data:i,error:r,isLoading:o}=ns("/account"),{updateConfig:a,isLoading:l}=Ze(),u=i?.workspaces,p=o||l;if(xe((y,C)=>{C.escape&&s?.()}),p)return I(b,{children:[m(ht,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return I(b,{flexDirection:"column",children:[I(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const d=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(y=>({label:y.name,value:y.id})),g=f.length,w=u?.length??0;async function h(y){const C=d.find(T=>T.id===y);if(!C)return;const{key:v,secret:A}=C;!v||!A||(await a({workspaceKey:v,workspaceSecret:A}),s?.())}return c(h,"handleSelect"),I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),I(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(nr,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&I(S,{children:["Showing ",g," of ",w," workspaces."]}),m(b,{marginTop:1,children:m(sr,{options:f,onChange:c(y=>{y&&h(y)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ms,"SelectWorkspace");function Dr({currentPat:s,onSubmit:e}){const[t,n]=K(""),[i,r]=K(!1),[o,a]=K(null);return I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(ir,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:I(S,{children:[m(ht,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Dr,"PersonalAccessTokenInput");var tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(tt||{});const Pr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=c(()=>{const{config:s}=Ze(),e=!!(s?.workspaceKey&&s?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),fn=[tt.Authenticate,tt.ConnectWorkspace];function ys({onComplete:s}){const[e,t]=K(!1),[n,i]=K(0),{isSetupComplete:r}=gs(),o=cs(),a=fn[n],l=n+1,u=fn.length,p=fn.map((g,w)=>{let h="pending";return w<n?h="done":w===n&&(h="current"),{id:g,label:Pr[g],status:h}});async function d(g){const w=o&&g===""?o:g,h=new ls;try{await h.request("/account",{headers:{Authorization:`Bearer ${w}`}}),vr(w),i(y=>y+1)}catch(y){console.error(y)}}c(d,"handlePatSubmit");function f(){t(!0),s&&s()}return c(f,"handleWorkspaceSelected"),xe((g,w)=>{r&&w.escape&&s&&s()}),e?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):I(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(S,{color:"cyan",children:["Step ",l," of ",u]}),r&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:p.map(g=>m(Mr,{status:g.status,label:g.label},g.id))})]}),a===tt.Authenticate&&m(Dr,{currentPat:o,onSubmit:d}),a===tt.ConnectWorkspace&&m(ms,{onExit:f,showEscOption:!1})]})}c(ys,"Setup");function Mr({status:s,label:e}){return I(b,{children:[I(b,{width:2,children:[s==="current"&&m(ht,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Mr,"StepDisplay");const te={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged"};class ws extends rr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class jr extends ws{static{c(this,"WorkspaceNotifications")}constructor(){super()}setState(e){this.emit(te.StateChanged,{state:e})}setConflicts(e){this.emit(te.ConflictsChanged,{conflicts:e})}setStats(e){this.emit(te.StatsChanged,{stats:e})}addLog(e){this.emit(te.LogAdded,{log:e})}}const re=new jr,ne={[U.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[U.Connector]:{element:"connector",elements:"connectors",exportable:!1},[U.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[U.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[U.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[U.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[U.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[U.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[U.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Rr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Rr,"baseExportCleanup");class bs{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}class Kr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=re}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const $=new Kr;class Ss{static{c(this,"ElementsManager")}cache;handler;constructor(e){this.cache=new bs,this.handler=e}async refresh(){try{const e=new bs,t=await this.handler.getIntegrations();e.addAll(t);const n=[U.Integration,U.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){$.error(`Failed to refresh elements: ${e instanceof Error?e.message:"Unknown error"}`)}}async putElement(e){let t;try{e.data.id&&this.cache.get(e.id)?t=await this.handler.updateElement(e):t=await this.handler.createElement(e),this.cache.put(t)}catch(n){$.error(`Failed to ${e.data.id?"update":"create"} element: ${n instanceof Error?n.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e),this.cache.remove(e)}catch(t){$.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}}async function _r(s,e="full"){const t={};$.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>dn("integration",i));for(const i of Object.keys(ne)){const r=ne[i];if(r.exportable===!1)continue;const o=[];$.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>dn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,dn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return $.success("[connectors] Remote workspace data retrieved successfully"),t}c(_r,"getWorkspaceData");function dn(s,e){return e=Rr(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}c(dn,"cleanUpForExport");class Fr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return tn.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=Pe(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 ss({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 n=!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||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const yt=new Fr;async function Cs(s){const e=await yt.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(Cs,"getWorkspaceId");const ks="connectors",vs="development",hn={};async function Br({integrations:s,allConnectors:e=!1}){const t=Cr(),n=await yt.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Es({client:n,connectorId:a}),d=!!u.workspaceId||e;if(!u?.key){$.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await Vr({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await Hr({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Br,"pullConnectors");async function Ur(){const s=await yt.getClient(process.cwd()),e=await _r(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};$.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);$.info("[connectors] Loading public connectors"),e.connector=o;const a=pn(),u=(j.existsSync(a)?j.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=F.join(a,p);try{return j.statSync(d).isDirectory()}catch{return!1}});for(const p of u){$.info(`[connectors] Loading connector from: ${p}`);const d=j.readdirSync(F.join(a,p)),f=await qr(p);if("baseUri"in f&&delete f.baseUri,f.uuid&&e.connector?.find(w=>w.uuid==f.uuid))i[f.id]=e.connector.find(w=>w.uuid==f.uuid).id,$.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!i[f.id])if(!!(await Es({client:s,connectorId:f.id})).workspaceId){$.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const y=await r.post("connectors",{...f,workspaceId:n});i[f.id]=y.id}else{$.info(`[connectors] Skipping public connector ${f.name} (${f.key})`);continue}const g=d.filter(w=>j.statSync(F.join(a,p,w)).isDirectory());for(const w of g)await Gr({client:s,connector:f,version:w,connectorId:i[f.id]})}}c(Ur,"pushConnectors");function pn(){const s=on();return F.join(s.membraneDirPath,ks)}c(pn,"getConnectorsPath");async function qr(s){return de.load(j.readFileSync(F.join(pn(),s,`${s}.yml`),"utf8"))}c(qr,"readConnector");async function Jr(s,e){return $.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=j.createWriteStream(e),r=cr("zip",{zlib:{level:9}});i.on("close",()=>{$.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{$.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=j.readdirSync(s);for(const a of o){const l=F.join(s,a),u=j.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(Jr,"createZipArchive");async function Wr(s,e){return $.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=ur.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=F.join(e,o);j.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=F.join(e,o),u=F.dirname(l);j.mkdirSync(u,{recursive:!0});const p=j.createWriteStream(l);r.pipe(p),p.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{$.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(Wr,"extractZipArchive");async function Gr({client:s,connector:e,version:t,connectorId:n}){const i=F.join(pn(),wt(e),Ts(t)),r=F.join(i,"src"),o=F.join(i,"src.zip"),a=j.existsSync(o);if(j.existsSync(r)&&($.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await Jr(r,o)),!j.existsSync(o)){$.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new lr;if(l.append("file",j.createReadStream(o),"file.zip"),$.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==vs)$.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){$.info(`[connectors] Version ${t} already published`);return}$.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}$.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch{$.error(`Error pushing connector version ${t} for ${e.name}`)}finally{!a&&j.existsSync(o)&&($.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),j.unlinkSync(o))}}c(Gr,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(hn[e])return hn[e];const t=await s.get(`connectors/${e}`);return hn[e]=t,t}c(Es,"getConnector");async function Vr({basePath:s,connector:e}){const t=wt(e),n=F.join(s,ks,t);j.mkdirSync(n,{recursive:!0});const i=F.join(n,`${wt(e)}.yml`);j.writeFileSync(i,de.dump(e)),$.info(`[connectors] Pulled connector ${e.name}`)}c(Vr,"pullConnector");async function Hr({client:s,connector:e,connectorVersion:t,basePath:n}){const i=wt(e),r=Ts(t),o=F.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});j.mkdirSync(o,{recursive:!0});const l=F.join(o,"src.zip");j.writeFileSync(l,a);const u=F.join(o,"src");j.existsSync(u)&&await Wr(a,u),$.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(Hr,"pullConnectorVersion");function wt(s){return s.key}c(wt,"getConnectorDirName");function Ts(s){return s??vs}c(Ts,"getConnectorVersionDirName");const P={NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},Yr="membrane",zr=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function bt(s){return D.join(s,Yr)}c(bt,"getMembraneDir");const Qr=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],Is=[U.Action,U.FieldMapping,U.Flow,U.DataSource];class V{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=he[this.type].apiPath;if(this.integrationKey){const t=he[U.Integration].apiPath;return D.join(t,this.integrationKey,e,this.key)}return D.join(e,this.key)}get path(){return D.join(this.dirPath,"spec.yaml")}get relativePath(){return D.relative(bt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return fr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Qr.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ne?.[this.type]?.parentKey&&(e=ne?.[this.type]?.parentKey),e}static new(e,t,n,i){return new V(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;if(n)return V.new(n.type,i,n.integrationKey,t)}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===U.Integration?`${e}:${t}`:V.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(this.isConnectorFile(t)||!this.isElementFile(t))return;const n=Object.values(he).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static isConnectorFile(e){const[t]=e.split(D.sep);return t===he[U.Connector].apiPath}static getElementTypeFromPath(e){return Object.values(U).find(t=>he[t].apiPath===e)}static getRelativePath(e){return D.relative(bt(process.cwd()),e)}static isIntegrationSpecific(e){return Is.includes(e)}static canBeIntegrationSpecific(e){return Is.includes(e)}}class Xr{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=bt(process.cwd())}async getElementsByType(e,t){const n=[],i=D.join(this.basePath,he[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=D.join(this.basePath,he[U.Integration].apiPath,o.key,he[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&$.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e)}async updateElement(e){if(!e.data)throw new Error("Element must have data to write");const t=D.join(this.basePath,e.dirPath),n=D.join(this.basePath,e.path);return x.existsSync(t)||x.mkdirSync(t,{recursive:!0}),x.writeFileSync(n,de.dump(e.data)),$.info(`[local] Written ${e.relativePath}`),e}async deleteElement(e){const t=D.join(this.basePath,e.path),n=D.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),$.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=D.join(this.basePath,he[U.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=de.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=D.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(D.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Zr{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&$.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const n=await(await this.getClient())[ne[e.type].element](e.data.id).get();return V.fromData(e.type,n)}async createElement(e){const t=e.clean(),i=await(await this.getClient())[ne[e.type].elements].create(t),r=V.fromData(e.type,i);return $.info(`[remote] Created ${r.id}`),r}async updateElement(e){if(!e.data.id)throw new Error("Element must have an id to update");const t=e.clean(),i=await(await this.getClient())[ne[e.type].element](e.data.id).put(t),r=V.fromData(e.type,i);return $.info(`[remote] Updated ${e.id}`),r}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[ne[e.type].element](e.data.id).archive(),$.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>V.fromData(U.Integration,i));return n.length>0&&$.success(`[remote] Fetched ${n.length} integrations`),n}async findAll(e,t={}){return(await(await this.getClient())[ne[e].elements].findAll(t)).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await yt.getClient(process.cwd())),this.client}}const mn=Symbol.for("yaml.alias"),gn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),le=Symbol.for("yaml.scalar"),je=Symbol.for("yaml.seq"),se=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[se]===mn,"isAlias"),Ee=c(s=>!!s&&typeof s=="object"&&s[se]===gn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[se]===be,"isMap"),_=c(s=>!!s&&typeof s=="object"&&s[se]===Ns,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[se]===le,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[se]===je,"isSeq");function q(s){if(s&&typeof s=="object")switch(s[se]){case be:case je:return!0}return!1}c(q,"isCollection$1");function J(s){if(s&&typeof s=="object")switch(s[se]){case mn:case be:case le:case je:return!0}return!1}c(J,"isNode");const As=c(s=>(R(s)||q(s))&&!!s.anchor,"hasAnchor"),X=Symbol("break visit"),Os=Symbol("skip children"),ue=Symbol("remove node");function Te(s,e){const t=$s(e);Ee(s)?_e(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Te,"visit$1"),Te.BREAK=X,Te.SKIP=Os,Te.REMOVE=ue;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(J(i)||_(i))return xs(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=_e(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=_e("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(_e,"visit_");async function St(s,e){const t=$s(e);Ee(s)?await Fe(null,s.contents,t,Object.freeze([s]))===ue&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(St,"visitAsync"),St.BREAK=X,St.SKIP=Os,St.REMOVE=ue;async function Fe(s,e,t,n){const i=await Ls(s,e,t,n);if(J(i)||_(i))return xs(s,n,i),Fe(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Fe(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===ue&&(e.items.splice(r,1),r-=1)}}}else if(_(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===X)return X;r===ue&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===X)return X;o===ue&&(e.value=null)}}return i}c(Fe,"visitAsync_");function $s(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c($s,"initVisitor");function Ls(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(_(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(q(n))n.items[s]=t;else if(_(n))s==="key"?n.key=t:n.value=t;else if(Ee(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const eo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},to=c(s=>s.replace(/[!,[\]{}]/g,e=>eo[e]),"escapeTagName");class Q{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Q.defaultYaml,e),this.tags=Object.assign({},Q.defaultTags,t)}clone(){const e=new Q(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Q(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Q.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Q.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Q.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Q.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;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[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+to(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&J(e.contents)){const r={};Te(e.contents,(o,a)=>{J(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
3
  `)}}Q.defaultYaml={explicit:!1,version:"1.2"},Q.defaultTags={"!!":"tag:yaml.org,2002:"};function Ds(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(Ds,"anchorIsValid");function Ps(s){const e=new Set;return Te(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Ps,"anchorNames");function Ms(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ms,"findNewAnchor");function no(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Ps(s));const o=Ms(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(R(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:n}}c(no,"createNodeAnchors");function Be(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=Be(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=Be(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=Be(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=Be(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Be,"applyReviver");function ie(s,e,t){if(Array.isArray(s))return s.map((n,i)=>ie(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!As(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(ie,"toJS");class yn{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,se,{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:n,onAnchor:i,reviver:r}={}){if(!Ee(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 n=="number"?n:100},a=ie(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Be(r,{"":a},"",a):a}}class Ct extends yn{static{c(this,"Alias")}constructor(e){super(mn),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Te(e,{Node:c((r,o)=>{(Se(o)||As(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(ie(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=kt(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(Ds(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 kt(s,e,t){if(Se(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(q(e)){let n=0;for(const i of e.items){const r=kt(s,i,t);r>n&&(n=r)}return n}else if(_(e)){const n=kt(s,e.key,t),i=kt(s,e.value,t);return Math.max(n,i)}return 1}c(kt,"getAliasCount");const js=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends yn{static{c(this,"Scalar")}constructor(e){super(le),this.value=e}toJSON(e,t){return t?.keep?this.value:ie(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const so="tag:yaml.org,2002:";function io(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}c(io,"findTagObject");function nt(s,e,t){if(Ee(s)&&(s=s.contents),J(s))return s;if(_(s)){const d=t.schema[be].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new Ct(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=so+e.slice(2));let u=io(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new L(s);return l&&(l.node=d),d}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[je]:o[be]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new L(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(nt,"createNode");function vt(s,e,t){let n=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]=n,n=o}else n=new Map([[r,n]])}return nt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(vt,"collectionFromPath");const st=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Rs extends yn{static{c(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(n=>J(n)||_(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(st(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,vt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&R(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!_(t))return!1;const n=t.value;return n==null||e&&R(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,vt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const ro=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function pe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(pe,"indentComment");const Ie=c((s,e,t)=>s.endsWith(`
4
4
  `)?pe(t,e):t.includes(`
5
5
  `)?`
@@ -137,7 +137,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
137
137
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
138
  `,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 n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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 n=!this.onKeyLine&&this.indent===e.indent,i=n&&(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 l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.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(ke(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(Ni(t.key)&&!ke(t.sep,"newline")){const o=He(t.start),a=t.key,l=t.sep;l.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:l}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=He(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]}):ke(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&&!ke(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 n&&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 n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.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||ke(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.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 n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const i=Wt(n),r=He(i);Ai(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
139
  `)+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=Wt(e),n=He(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Wt(e),n=He(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.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(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Ti||null,prettyErrors:e}}c(Oi,"parseOptions");function oa(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Kt(s,t)),a.warnings.forEach(Kt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(oa,"parseAllDocuments");function $i(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ae(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Kt(s,t)),o.warnings.forEach(Kt(s,t))),o}c($i,"parseDocument");function aa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=$i(s,t);if(!i)return null;if(i.warnings.forEach(r=>Bs(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:n},t))}c(aa,"parse");function ca(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=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(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Ee(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(ca,"stringify");var la=Object.freeze({__proto__:null,Alias:Ct,CST:sa,Composer:Kn,Document:Qe,Lexer:Ei,LineCounter:Ti,Pair:Y,Parser:Un,Scalar:L,Schema:Ht,YAMLError:xn,YAMLMap:ee,YAMLParseError:Ae,YAMLSeq:Ce,YAMLWarning:ui,isAlias:Se,isCollection:q,isDocument:Ee,isMap:Re,isNode:J,isPair:_,isScalar:R,isSeq:Ke,parse:aa,parseAllDocuments:oa,parseDocument:$i,stringify:ca,visit:Te,visitAsync:St});const Z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},ua={ignored:zr,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 fa extends ws{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=bt(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=dr.watch(this.membraneDir,ua),this.watcher.on("add",e=>this.handleFileSystemEvent(Z.Added,e)).on("change",e=>this.handleFileSystemEvent(Z.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(Z.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(Z.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=D.relative(this.membraneDir,t);if(e===Z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};$.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&($.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=D.relative(this.membraneDir,e);let i;try{i=t?la.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return Zi.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]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=D.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=D.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}const z={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"};class ft{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=re}fileWatcher=void 0;notifier;changes=[];hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new fa({cwd:process.cwd()}),this.fileWatcher.on(Z.Added,e=>this.handleLocalEvent(e,Z.Added)),this.fileWatcher.on(Z.Changed,e=>this.handleLocalEvent(e,Z.Changed)),this.fileWatcher.on(Z.Deleted,e=>this.handleLocalEvent(e,Z.Deleted)),await this.fileWatcher.start(),$.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){let n=V.fromPathAndData(e.filePath,e.data);if(!n){const r=V.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch($.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case Z.Added:case Z.Changed:await i.putElement(n);break;case Z.Deleted:await i.deleteElement(n);break}}detectIncomingChanges(){this.clearChanges();const e=ft.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=ft.getChanges(fe.OUTGOING,this.localManager.cache,this.remoteManager.cache);return this.updateChanges(e),e}getChange(e){const t=this.localManager.cache.get(e.id),n=this.remoteManager.cache.get(e.id);return!t&&n?{type:z.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:z.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:z.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){this.hasChanges()&&($.info("[resolver] Resolving changes.."),await Promise.all(this.changes.map(e=>this.resolveChange(e))),$.success(`[resolver] Resolved ${this.changes.length} changes`))}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case z.DELETE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case z.CREATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case z.UPDATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),t.putElement(e.element)}}getManager(e){return e===fe.INCOMING?this.localManager:this.remoteManager}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),d=ft.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)$.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);$.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case fe.INCOMING:return"local\u2190remote";case fe.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case z.CREATE:return"ADD";case z.UPDATE:return"UPD";case z.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:z.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:z.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:z.UPDATE,element:e,direction:n,isConflict:!0}:null}}class da{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=re,this.local=new Ss(new Xr),this.remote=new Ss(new Zr),this.syncService=new ft(this.local,this.remote)}async push(e={}){if(this.notifier.setState(P.PUSHING),await this.refreshElements(),this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Ur(),await this.resolveChanges({watch:e.watch})}async pull(e={}){if(this.notifier.setState(P.PULLING),await this.refreshElements(),this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Br({integrations:this.remote.cache.getElementsByType(U.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.resolveChanges({watch:e.watch})}async resolveChanges(e={}){this.notifier.setState(P.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),this.notifier.setState(P.SYNCED),e.watch&&(this.notifier.setState(P.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}async refreshElements(){return Promise.all([this.remote.refresh(),this.local.refresh()])}updateStats(){const e={};for(const t of this.local.cache.getAll())e[t.type]=(e[t.type]||0)+1;this.notifier.setStats(e)}}const qn=new da,Li=zt(null);function Jn({children:s,onExit:e}){const{config:t,isLoading:n}=Ze(),{data:i}=ns("/account"),[r,o]=K(P.NOT_SYNCED),[a,l]=K([]),[u,p]=K({}),[d,f]=K([]),w=i?.workspaces?.find(T=>T.key===t?.workspaceKey)||null,h=t?.workspaceKey&&t?.workspaceSecret;function y(T){if(h)try{qn.resolveChanges(T||{})}catch(N){console.error("Failed to resolve conflicts:",N),A()}}c(y,"resolveConflicts");function C(T){if(h)try{qn.pull(T||{})}catch(N){console.error("Failed to pull:",N),A()}}c(C,"pull");function v(T){if(h)try{qn.push(T||{})}catch(N){console.error("Failed to push:",N),A()}}c(v,"push");function A(){h&&e()}return c(A,"exit"),ye(()=>{const T=c(({state:E})=>o(E),"handleStateChanged"),N=c(({stats:E})=>p(E),"handleStatsChanged"),O=c(({log:E})=>f(W=>[...W,E]),"handleLogAdded"),M=c(({conflicts:E})=>l(E),"handleConflictsUpdated");return re.on(te.StateChanged,T),re.on(te.StatsChanged,N),re.on(te.LogAdded,O),re.on(te.ConflictsChanged,M),()=>{re.off(te.StateChanged,T),re.off(te.StatsChanged,N),re.off(te.LogAdded,O),re.off(te.ConflictsChanged,M)}},[]),n?null:h?m(Li.Provider,{value:{state:r,stats:u,logs:d,currentWorkspace:w,conflicts:a,resolveConflicts:y,pull:C,push:v,exit:A},children:s}):m(b,{children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})})}c(Jn,"WorkspaceServiceProvider");function $e(){const s=Qt(Li);if(!s)throw new Error("useWorkspaceService must be used within WorkspaceServiceProvider");return s}c($e,"useWorkspaceService");function Wn(){const{stats:s}=$e(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:I(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>I(b,{children:[m(b,{width:20,children:I(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(Wn,"ElementStats");const Gn=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function xi(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(xi,"truncateText");const Vn=5,ha=6;function pa(){const{logs:s}=$e(),[e,t]=K(0),n=Math.min(100,process.stdout.columns||100),i=Vn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-ha,u=e<s.length-i,p=e>0;return xe((d,f)=>{if(s.length!==0)if(f.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else f.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),I(b,{flexDirection:"column",paddingTop:1,children:[I(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>Vn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,f)=>m(b,{marginLeft:1,children:m(S,{color:Gn(d.type),children:xi(d.message,l)})},d.timestamp+f)),s.length>Vn&&I(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(pa,"Logs");const Gt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function ma(){const{state:s,resolveConflicts:e,exit:t}=$e(),[n,i]=K(0),[r,o]=K(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Gt.length-1):l.downArrow?i(u=>u<Gt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Gt[n].value==="sync"?e({watch:!0}):t()))}),ye(()=>{s!==P.CONFLICTS&&r&&o(!1)},[s,r]),I(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(Hn,{})}),I(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?I(b,{flexDirection:"row",gap:1,children:[m(ht,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Gt.map((a,l)=>m(b,{flexDirection:"column",children:I(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(ma,"ResolveChangesUI");const ga={[z.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[z.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[z.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Hn(){const{conflicts:s}=$e(),e=Yi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=ga[i][r];return I(b,{flexDirection:"column",children:[I(b,{flexDirection:"row",gap:1,children:[I(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:I(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(Hn,"Conflicts");function ya(){const{config:s}=Ze(),{state:e,logs:t,currentWorkspace:n,pull:i}=$e(),r=n?.name,o=r?xi(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ye(()=>{i({allConnectors:!1,force:!1,watch:!0})},[]),I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:I(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),I(S,{color:ba(e),children:[" [",wa(e),"] "]})]})}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?I(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):I(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(ma,{}):I(Yt,{children:[m(b,{paddingTop:1,children:m(Wn,{})}),t.length>0&&m(pa,{})]})]})}c(ya,"Workspace");function wa(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced"}}c(wa,"getStatusDisplay");function ba(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey"}}c(ba,"getStatusColor");const Sa=c(()=>{const{isSetupComplete:s}=gs(),{config:e}=Ze();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e}},"useStatus");function Ca({onExit:s}){const e=fs(),{isSetupComplete:t,workspaceKey:n,config:i}=Sa(),[r,o]=K(!1),[a,l]=K(!1),[u,p]=K(!1),d=zi(!0);return xe(f=>{r||a||u||(f==="w"&&o(!0),f==="a"&&p(!0),f==="o"&&n&&i?.workspaceSecret&&(async()=>{try{const w=`https://console.integration.app/w/${await Cs(e)}`,h=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Xi(`${h} "${w}"`)}catch(g){console.error("Failed to open workspace:",g),s()}})(),f==="s"&&l(!0))}),ye(()=>(d.current=!0,()=>{d.current=!1}),[]),r?m(ms,{onExit:c(()=>o(!1),"onExit")}):u?m(Or,{onExit:c(()=>p(!1),"onExit"),onComplete:c(()=>p(!1),"onComplete")}):a||!t?m(ys,{onComplete:c(()=>l(!1),"onComplete")},Date.now()):I(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(xr,{})}),m(Jn,{onExit:s,children:m(ya,{})}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})}c(Ca,"Main");const Di=Wi(process.argv.slice(2)),ka=Di.cwd?Bi(Di.cwd):process.cwd(),va=c(()=>process.exit(0),"onExit"),Ea=c(()=>m(mt,{cwd:ka,children:m(Ca,{onExit:va})}),"App");function Ta(){dt(m(Ea,{}))}c(Ta,"runAgent");function Ia(s){s.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
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=Wt(e),n=He(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Wt(e),n=He(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.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(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Ti||null,prettyErrors:e}}c(Oi,"parseOptions");function oa(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Kt(s,t)),a.warnings.forEach(Kt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(oa,"parseAllDocuments");function $i(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Un(t?.addNewLine),r=new Kn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ae(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Kt(s,t)),o.warnings.forEach(Kt(s,t))),o}c($i,"parseDocument");function aa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=$i(s,t);if(!i)return null;if(i.warnings.forEach(r=>Bs(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:n},t))}c(aa,"parse");function ca(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=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(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Ee(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(ca,"stringify");var la=Object.freeze({__proto__:null,Alias:Ct,CST:sa,Composer:Kn,Document:Qe,Lexer:Ei,LineCounter:Ti,Pair:Y,Parser:Un,Scalar:L,Schema:Ht,YAMLError:xn,YAMLMap:ee,YAMLParseError:Ae,YAMLSeq:Ce,YAMLWarning:ui,isAlias:Se,isCollection:q,isDocument:Ee,isMap:Re,isNode:J,isPair:_,isScalar:R,isSeq:Ke,parse:aa,parseAllDocuments:oa,parseDocument:$i,stringify:ca,visit:Te,visitAsync:St});const Z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},ua={ignored:zr,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 fa extends ws{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=bt(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=dr.watch(this.membraneDir,ua),this.watcher.on("add",e=>this.handleFileSystemEvent(Z.Added,e)).on("change",e=>this.handleFileSystemEvent(Z.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(Z.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(Z.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=D.relative(this.membraneDir,t);if(e===Z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};$.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&($.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=D.relative(this.membraneDir,e);let i;try{i=t?la.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return Zi.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]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=D.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=D.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}const z={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"};class ft{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=re}fileWatcher=void 0;notifier;changes=[];hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new fa({cwd:process.cwd()}),this.fileWatcher.on(Z.Added,e=>this.handleLocalEvent(e,Z.Added)),this.fileWatcher.on(Z.Changed,e=>this.handleLocalEvent(e,Z.Changed)),this.fileWatcher.on(Z.Deleted,e=>this.handleLocalEvent(e,Z.Deleted)),await this.fileWatcher.start(),$.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){let n=V.fromPathAndData(e.filePath,e.data);if(!n){const r=V.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch($.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case Z.Added:case Z.Changed:await i.putElement(n);break;case Z.Deleted:await i.deleteElement(n);break}}detectIncomingChanges(){this.clearChanges();const e=ft.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=ft.getChanges(fe.OUTGOING,this.localManager.cache,this.remoteManager.cache);return this.updateChanges(e),e}getChange(e){const t=this.localManager.cache.get(e.id),n=this.remoteManager.cache.get(e.id);return!t&&n?{type:z.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:z.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:z.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){this.hasChanges()&&($.info("[resolver] Resolving changes.."),await Promise.all(this.changes.map(e=>this.resolveChange(e))),$.success(`[resolver] Resolved ${this.changes.length} changes`))}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case z.DELETE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case z.CREATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case z.UPDATE:return $.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),t.putElement(e.element)}}getManager(e){return e===fe.INCOMING?this.localManager:this.remoteManager}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),d=ft.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)$.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);$.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case fe.INCOMING:return"local\u2190remote";case fe.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case z.CREATE:return"ADD";case z.UPDATE:return"UPD";case z.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:z.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:z.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:z.UPDATE,element:e,direction:n,isConflict:!0}:null}}class da{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=re,this.local=new Ss(new Xr),this.remote=new Ss(new Zr),this.syncService=new ft(this.local,this.remote)}async push(e={}){if(this.notifier.setState(P.PUSHING),await this.refreshElements(),this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Ur(),await this.resolveChanges({watch:e.watch})}async pull(e={}){if(this.notifier.setState(P.PULLING),await this.refreshElements(),this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(P.CONFLICTS);await Br({integrations:this.remote.cache.getElementsByType(U.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.resolveChanges({watch:e.watch})}async resolveChanges(e={}){this.notifier.setState(P.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),this.notifier.setState(P.SYNCED),e.watch&&(this.notifier.setState(P.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}async refreshElements(){return Promise.all([this.remote.refresh(),this.local.refresh()])}updateStats(){const e={};for(const t of this.local.cache.getAll())e[t.type]=(e[t.type]||0)+1;this.notifier.setStats(e)}}const qn=new da,Li=zt(null);function Jn({children:s,onExit:e}){const{config:t,isLoading:n}=Ze(),{data:i}=ns("/account"),[r,o]=K(P.NOT_SYNCED),[a,l]=K([]),[u,p]=K({}),[d,f]=K([]),w=i?.workspaces?.find(T=>T.key===t?.workspaceKey)||null,h=t?.workspaceKey&&t?.workspaceSecret;function y(T){if(h)try{qn.resolveChanges(T||{})}catch(N){console.error("Failed to resolve conflicts:",N),A()}}c(y,"resolveConflicts");function C(T){if(h)try{qn.pull(T||{})}catch(N){console.error("Failed to pull:",N),A()}}c(C,"pull");function v(T){if(h)try{qn.push(T||{})}catch(N){console.error("Failed to push:",N),A()}}c(v,"push");function A(){h&&e()}return c(A,"exit"),ye(()=>{const T=c(({state:E})=>o(E),"handleStateChanged"),N=c(({stats:E})=>p(E),"handleStatsChanged"),O=c(({log:E})=>f(W=>[...W,E]),"handleLogAdded"),M=c(({conflicts:E})=>l(E),"handleConflictsUpdated");return re.on(te.StateChanged,T),re.on(te.StatsChanged,N),re.on(te.LogAdded,O),re.on(te.ConflictsChanged,M),()=>{re.off(te.StateChanged,T),re.off(te.StatsChanged,N),re.off(te.LogAdded,O),re.off(te.ConflictsChanged,M)}},[]),n?null:h?m(Li.Provider,{value:{state:r,stats:u,logs:d,currentWorkspace:w,conflicts:a,resolveConflicts:y,pull:C,push:v,exit:A},children:s}):m(b,{children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})})}c(Jn,"WorkspaceServiceProvider");function $e(){const s=Qt(Li);if(!s)throw new Error("useWorkspaceService must be used within WorkspaceServiceProvider");return s}c($e,"useWorkspaceService");function Wn(){const{stats:s}=$e(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:I(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>I(b,{children:[m(b,{width:20,children:I(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(Wn,"ElementStats");const Gn=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function xi(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(xi,"truncateText");const Vn=5,ha=6;function pa(){const{logs:s}=$e(),[e,t]=K(0),n=Math.min(100,process.stdout.columns||100),i=Vn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-ha,u=e<s.length-i,p=e>0;return xe((d,f)=>{if(s.length!==0)if(f.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else f.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),I(b,{flexDirection:"column",paddingTop:1,children:[I(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>Vn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,f)=>m(b,{marginLeft:1,children:m(S,{color:Gn(d.type),children:xi(d.message,l)})},d.timestamp+f)),s.length>Vn&&I(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(pa,"Logs");const Gt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function ma(){const{state:s,resolveConflicts:e,exit:t}=$e(),[n,i]=K(0),[r,o]=K(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Gt.length-1):l.downArrow?i(u=>u<Gt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Gt[n].value==="sync"?e({watch:!0}):t()))}),ye(()=>{s!==P.CONFLICTS&&r&&o(!1)},[s,r]),I(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(Hn,{})}),I(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?I(b,{flexDirection:"row",gap:1,children:[m(ht,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Gt.map((a,l)=>m(b,{flexDirection:"column",children:I(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(ma,"ResolveChangesUI");const ga={[z.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[z.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[z.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Hn(){const{conflicts:s}=$e(),e=Yi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=ga[i][r];return I(b,{flexDirection:"column",children:[I(b,{flexDirection:"row",gap:1,children:[I(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:I(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(Hn,"Conflicts");function ya(){const{config:s}=Ze(),{state:e,logs:t,currentWorkspace:n,pull:i}=$e(),r=n?.name,o=r?xi(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ye(()=>{i({allConnectors:!1,force:!1,watch:!0})},[]),I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:I(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),I(S,{color:ba(e),children:[" [",wa(e),"] "]})]})}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?I(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):I(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(ma,{}):I(Yt,{children:[m(b,{paddingTop:1,children:m(Wn,{})}),t.length>0&&m(pa,{})]})]})}c(ya,"Workspace");function wa(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced"}}c(wa,"getStatusDisplay");function ba(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey"}}c(ba,"getStatusColor");const Sa=c(()=>{const{isSetupComplete:s}=gs(),{config:e}=Ze();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e}},"useStatus");function Ca({onExit:s}){const e=fs(),{isSetupComplete:t,workspaceKey:n,config:i}=Sa(),[r,o]=K(null),a=zi(!0),l=r??(t?"main":"setup");return xe(u=>{l==="main"&&(u==="w"&&o("workspace-selection"),u==="a"&&o("add-mcp-server"),u==="o"&&n&&i?.workspaceSecret&&(async()=>{try{const d=`https://console.integration.app/w/${await Cs(e)}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Xi(`${f} "${d}"`)}catch(p){console.error("Failed to open workspace:",p),s()}})(),u==="s"&&o("setup"))}),ye(()=>(a.current=!0,()=>{a.current=!1}),[]),l==="workspace-selection"?m(ms,{onExit:c(()=>o(null),"onExit")}):l==="add-mcp-server"?m(Or,{onExit:c(()=>o(null),"onExit"),onComplete:c(()=>o(null),"onComplete")}):l==="setup"?m(ys,{onComplete:c(()=>o(null),"onComplete")},Date.now()):I(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(xr,{})}),m(Jn,{onExit:s,children:m(ya,{})}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})}c(Ca,"Main");const Di=Wi(process.argv.slice(2)),ka=Di.cwd?Bi(Di.cwd):process.cwd(),va=c(()=>process.exit(0),"onExit"),Ea=c(()=>m(mt,{cwd:ka,children:m(Ca,{onExit:va})}),"App");function Ta(){dt(m(Ea,{}))}c(Ta,"runAgent");function Ia(s){s.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
141
141
  `)).action(()=>{dt(De.createElement(mt,null,De.createElement(ys,{onComplete:c(()=>process.exit(0),"onComplete")})))})}c(Ia,"setupInitCommand");async function Pi(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return tn.sign(t,e)}c(Pi,"generateAdminAccessToken");async function Na(s,e){return(await nn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Na,"fetchOpenApiSchema");function Mi(s,e=!0){if(!s)return e?B.string():B.string().optional();let t;switch(s.type){case"integer":t=B.coerce.number().int();break;case"number":t=B.coerce.number();break;case"boolean":t=B.coerce.boolean();break;case"string":default:t=B.string();break}return s.format==="uuid"?t=B.string().uuid():s.format==="email"?t=B.string().email():s.format==="date"?t=B.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=B.string().datetime()),s.enum&&(t=B.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}c(Mi,"convertOpenApiSchemaToZod");function ji(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(ji,"extractPathParameters");function Aa(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,l={},u={},p={};if(s.parameters){for(const f of s.parameters)if(f.in==="path")u[f.name]=Mi(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const g=f.required===!0;p[f.name]=Mi(f.schema,g).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(u).length>0&&(l.params=B.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=B.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=B.any().describe("Request body"));const d=Object.keys(l).length>0?B.object(l):B.object({});return{name:o,description:a,parameters:d,async execute(f){try{const g=ji(e);if(g.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const T=g.filter(N=>!(N in f.params));if(T.length>0)throw new Error(`Missing required path parameters: ${T.join(", ")}`)}let w=`${n}${e}`;if(f.params)for(const[T,N]of Object.entries(f.params)){const O=`{${T}}`;w.includes(O)&&(w=w.replace(O,String(N)))}const h=ji(w);if(h.length>0)throw new Error(`Unresolved path parameters: ${h.join(", ")}`);const y=new URLSearchParams;if(f.query)for(const[T,N]of Object.entries(f.query))N!=null&&y.append(T,String(N));y.toString()&&(w+=`?${y.toString()}`);const C=await Pi(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(v.data=f.body);const A=await nn.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return nn.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Aa,"createApiTool");function Oa(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,l]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&l&&typeof l=="object"){const u=Aa(l,r,a,e,t,n);i.push(u)}}return i}c(Oa,"convertOpenApiToTools");function $a(s){s.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(`
142
142
  `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Pe();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||rn,n=await Pi(e.workspaceKey,e.workspaceSecret),i=await Na(t,n),r=Oa(i,t,e.workspaceKey,e.workspaceSecret),o=new mr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
143
143
  Use it for anything related to Membrane or integrations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "0.3.0",
3
+ "version": "0.5.0",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",