@membranehq/cli 0.10.6 → 0.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +15 -15
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Bi=Object.defineProperty;var c=(s,e)=>Bi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as Zt}from"react/jsx-runtime";import*as R from"node:path";import{resolve as Ui,dirname as qi,join as Ji}from"node:path";import{useInput as xe,Box as b,Text as S,Newline as Wi,render as mt}from"ink";import Gi from"minimist";import{SWRConfig as Vi}from"swr";import Pe,{createContext as ns,useState as F,useEffect as Ee,useContext as ss,useMemo as Hi,useRef as Yi}from"react";import is from"swr/immutable";import rs from"os";import B from"path";import zi from"conf";import{exec as Qi}from"node:child_process";import*as x from"node:fs";import{readFileSync as Xi}from"node:fs";import{EventEmitter as Zi}from"events";import{MembraneConfigLoader as er,MembraneClient as os,WorkspaceElementType as P,extractMembraneErrorData as te,WorkspaceElementSpecs as ye,setValueAtLocator as en,getDataCollectionCreateFields as tn,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as gt,getRequiredFieldsFromSchema as tr,getValueAtLocator as nr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as nn}from"@membranehq/sdk";import sn from"jsonwebtoken";import{Spinner as sr,TextInput as ir,Select as rr}from"@inkjs/ui";import yt from"ink-spinner";import or from"ink-text-input";import*as ar from"node:crypto";import{createHash as cr}from"node:crypto";import*as lr from"node:os";import M from"fs";import ur from"archiver";import fr from"form-data";import Ie from"js-yaml";import hr from"unzipper";import dr from"lodash/isEqual.js";import pr from"chokidar";import{fileURLToPath as mr}from"node:url";import k from"chalk";import{Command as gr}from"commander";import rn from"axios";import{FastMCP as yr}from"fastmcp";import{z}from"zod";import on from"lodash/merge.js";import wr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import br from"lodash/template.js";import Sr from"lodash/templateSettings.js";const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},us=ns(null);function Cr({children:s,membraneCLIService:e}){const{data:t}=is("/account"),[n,i]=F(D.NOT_INITIALIZED),[r,o]=F([]),[a,l]=F({}),[u,p]=F([]),[d,h]=F(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ee(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),v=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifications.on(J.StateChanged,f),e.notifications.on(J.StatsChanged,y),e.notifications.on(J.LogAdded,C),e.notifications.on(J.ConflictsChanged,v),e.notifications.on(J.ConfigChanged,A),e.init(),()=>{e.notifications.off(J.StateChanged,f),e.notifications.off(J.StatsChanged,y),e.notifications.off(J.LogAdded,C),e.notifications.off(J.ConflictsChanged,v),e.notifications.off(J.ConfigChanged,A)}},[]),m(us.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(Cr,"MembraneCLIServiceProvider");function oe(){const s=ss(us);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const kr="membrane",vr="membrane.config.yml",an="https://api.integration.app";function cn(){const s=process.cwd(),e=R.join(s,kr),t=R.join(s,vr),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(cn,"getPaths");function Er(){return cn().membraneDirPath}c(Er,"getBasePath");const Ir={pat:{type:"string"},workspace:{type:"object"}},fs=new zi({schema:Ir,configName:"config",cwd:B.join(rs.homedir(),".membrane")}),Tr=c(s=>{fs.set("pat",s)},"setPat"),hs=c(()=>fs.get("pat"),"getPat");class ds{static{c(this,"AccountApiClient")}constructor(e=an){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=hs();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 Nr=c(s=>{const e=new ds(an);return t=>e.get(t)},"createAccountApiFetcher"),ps=ns(process.cwd());function Ar({cwd:s,children:e}){return m(ps.Provider,{value:s,children:e})}c(Ar,"CwdProvider");function Or(){return ss(ps)}c(Or,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ar,{cwd:n,children:m(Vi,{value:{fetcher:Nr()},children:m(Cr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const ln=[{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=R.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=R.join(process.cwd(),".cursor"),e=R.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 $r({onExit:s,onComplete:e}){const[t,n]=F(0),[i,r]=F(!1),[o,a]=F(null),[l,u]=F(""),[p,d]=F("");xe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(ln.length-1,t+1));else if(f.return||w===" "){const y=ln[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(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?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(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?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(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:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(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:ln.map((w,f)=>E(b,{children:[E(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),E(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($r,"AddMcpServerScreen");class ms extends Zi{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 He{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new er}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}isCacheDefined(e){return this.sdkLoader.hasValidConfig()}}const Ze=He.getInstance();function bt(s){return Ze.loadConfig(s)}c(bt,"readProjectConfig");class Lr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return sn.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=bt(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 os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: 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 le=new Lr;async function gs(s){const e=await le.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(gs,"getWorkspaceId");class Dr extends ms{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await le.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){if(this.clientId)return;const t=await(await le.getClient(process.cwd())).post("/local-clients",{hostname:rs.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await le.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await le.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const ue=new Dr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=F(null),[t,n]=F([]),[i,r]=F(null);return Ee(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return ue.on(J.McpStatusChanged,o),ue.on(J.McpServersChanged,a),()=>{ue.off(J.McpStatusChanged,o),ue.off(J.McpServersChanged,a)}},[]),{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(xr,"useMcpStatus");function Pr(){const{error:s,serverCount:e,allMcpServers:t}=xr(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(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:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Wi,{}),"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:E(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(Pr,"Agent");const St=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ys(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ys,"truncateText");function un({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(sr,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===D.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===D.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:St(i.type),children:i.message},i.timestamp+r))})}return s}c(un,"EnsureInitialized");function ws({onExit:s,showEscOption:e=!0}){const[t,n]=F(""),{data:i,error:r,isLoading:o}=is("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(xe((f,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return c(w,"handleSelect"),E(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"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(ir,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(rr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ws,"SelectWorkspace");function Mr({currentPat:s,onSubmit:e}){const[t,n]=F(""),[i,r]=F(!1),[o,a]=F(null);return E(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(or,{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:E(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Mr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const Rr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},fn=[et.Authenticate,et.ConnectWorkspace];function bs({onComplete:s}){const{config:e}=oe(),[t,n]=F(!1),[i,r]=F(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=hs(),l=fn[i],u=i+1,p=fn.length,d=fn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:Rr[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ds;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Tr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),xe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Kr,{status:w.status,label:w.label},w.id))})]}),l===et.Authenticate&&m(Mr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(ws,{onExit:g,showEscOption:!1})]})}c(bs,"Setup");function Kr({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Kr,"StepDisplay");function hn(){const{stats:s}=oe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(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])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(hn,"ElementStats");const dn=5,_r=6;function jr(){const{logs:s}=oe(),[e,t]=F(0),n=Math.min(100,process.stdout.columns||100),i=dn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-_r,u=e<s.length-i,p=e>0;return xe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>dn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:St(d.type),children:ys(d.message,l)})},d.timestamp+h)),s.length>dn&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(jr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"},Ct=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Fr(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=F(0),[r,o]=F(!1);return xe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Ct.length-1):l.downArrow?i(u=>u<Ct.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Ct[n].value==="sync"?e({watch:!0}):t()))}),Ee(()=>{s!==D.CONFLICTS&&r&&o(!1)},[s,r]),E(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(pn,{})}),E(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?E(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Ct.map((a,l)=>m(b,{flexDirection:"column",children:E(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(Fr,"ResolveChangesUI");const Br={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function pn(){const{conflicts:s}=oe(),e=Hi(()=>{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=Br[i][r];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(pn,"Conflicts");function Ur(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?ys(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Jr(e),children:[" [",qr(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Fr,{}):E(Zt,{children:[m(b,{paddingTop:1,children:m(hn,{})}),t.length>0&&m(jr,{})]})]})}c(Ur,"Workspace");function qr(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(qr,"getStatusDisplay");function Jr(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Jr,"getStatusColor");const Wr="https://console.integration.app/w";function Gr(){const s=Or(),e=Yi(!0),{exit:t,state:n}=oe(),[i,r]=F(null),o=i??(n===D.SETTING_UP?"setup":"main");xe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await gs(s),u=`${Wr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Qi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(ws,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m($r,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(bs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(un,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Pr,{})}),m(Ur,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Gr,"Main");class Vr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=ue}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 T=new Vr,we=R.join(lr.tmpdir(),"membrane-mcp-status"),Ss=3e4;class Hr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kt(void 0,e),n=Cs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function kt(s,e){try{const t=e||process.cwd();if(!s){const i=Cs(t);return i.length===0?null:i[0]}const n=yn(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ss)return tt(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>Ss)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(kt,"getMcpStatus");function Cs(s){try{const e=s||process.cwd(),t=gn(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=kt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Cs,"getAllMcpStatusFiles");function mn(s){try{const t={...kt(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=yn(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(mn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=yn(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=gn(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(R.join(we,r))}}}catch{}}c(tt,"clearMcpStatus");function Yr(s,e){const t=kt(s,e);t&&mn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Yr,"trackToolExecution");function gn(s){return cr("md5").update(s).digest("hex").slice(0,8)}c(gn,"getCwdHash");function yn(s,e){const t=gn(e);return R.join(we,`mcp-${t}-${s}.json`)}c(yn,"getStatusFilePath");const se={[P.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")},[P.Connector]:{element:"connector",elements:"connectors",exportable:!1},[P.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[P.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[P.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[P.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[P.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[P.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[P.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function zr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(zr,"baseExportCleanup");class ks{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 vs{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new ks,this.handler=e}async refresh(){try{const e=new ks,t=await this.handler.getIntegrations();e.addAll(t);const n=[P.Integration,P.Connector],i=Object.keys(se),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){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function Qr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>wn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>wn(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,wn(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 T.success("[connectors] Remote workspace data retrieved successfully"),t}c(Qr,"getWorkspaceData");function wn(s,e){return e=zr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(wn,"cleanUpForExport");const nt="connectors",st="development",bn={};async function Xr({integrations:s,allConnectors:e=!1}){const t=Er(),n=await le.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){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await so({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await io({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Xr,"pullConnectors");async function Zr(){const s=await le.getClient(process.cwd()),e=await Qr(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=Sn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return M.statSync(d).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const d=M.readdirSync(B.join(a,p)),h=await Cn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,T.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Es({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>M.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await no({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(Zr,"pushConnectors");function Sn(){const s=cn();return B.join(s.membraneDirPath,nt)}c(Sn,"getConnectorsPath");async function Cn(s){return Ie.load(M.readFileSync(B.join(Sn(),s,`${s}.yml`),"utf8"))}c(Cn,"readConnector");async function eo(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=ur("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.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=M.readdirSync(s);for(const a of o){const l=B.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(eo,"createZipArchive");async function to(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=hr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(to,"extractZipArchive");async function no({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Sn(),vt(e),Is(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await eo(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new fr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==st)T.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)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(no,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(bn[e])return bn[e];const t=await s.get(`connectors/${e}`);return bn[e]=t,t}c(Es,"getConnector");async function so({basePath:s,connector:e}){const t=vt(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${vt(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(so,"pullConnector");async function io({client:s,connector:e,connectorVersion:t,basePath:n}){const i=vt(e),r=Is(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=B.join(o,"src");M.mkdirSync(u,{recursive:!0}),await to(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(io,"pullConnectorVersion");function vt(s){return s.key}c(vt,"getConnectorDirName");function Is(s){return s??st}c(Is,"getConnectorVersionDirName");function ro(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(ro,"isConnectorSourceFile");async function oo(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await le.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(oo,"putConnectorFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await le.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(ao,"deleteConnectorFile");const co="membrane",lo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Et(s){return R.join(s,co)}c(Et,"getMembraneDir");const uo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state"],Ts=[P.Action,P.FieldMapping,P.Flow,P.DataSource];class G{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||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[P.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(Et(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return dr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return uo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(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 G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===P.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).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 getElementTypeFromPath(e){return Object.values(P).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return R.relative(Et(process.cwd()),e)}static isIntegrationSpecific(e){return Ts.includes(e)}static canBeIntegrationSpecific(e){return Ts.includes(e)}}class fo{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=Et(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,ye[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,ye[P.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,ye[P.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return G.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=R.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(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ho{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.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&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=G.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=G.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>G.fromData(P.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===P.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===P.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===P.Integration).map(r=>r.key).join(", ")}`)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const kn=Symbol.for("yaml.alias"),vn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[ie]===kn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===be,"isMap"),j=c(s=>!!s&&typeof s=="object"&&s[ie]===Ns,"isPair"),K=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case be:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case kn:case be:case he:case Me:return!0}return!1}c(q,"isNode");const As=c(s=>(K(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Os=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=$s(e);Te(s)?_e(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Os,Ne.REMOVE=de;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(U(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===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=_e("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(_e,"visit_");async function It(s,e){const t=$s(e);Te(s)?await je(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await je(null,s,t,Object.freeze([]))}c(It,"visitAsync"),It.BREAK=ee,It.SKIP=Os,It.REMOVE=de;async function je(s,e,t,n){const i=await Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=await je("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await je("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(je,"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(j(e))return t.Pair?.(s,e,n);if(K(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function Ds(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(j(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(Ds,"replaceNode");const po={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mo=c(s=>s.replace(/[!,[\]{}]/g,e=>po[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.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+mo(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&&q(e.contents)){const r={};Ne(e.contents,(o,a)=>{q(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
|
-
`)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function
|
|
2
|
+
var Bi=Object.defineProperty;var c=(s,e)=>Bi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as Zt}from"react/jsx-runtime";import*as R from"node:path";import{resolve as Ui,dirname as qi,join as Ji}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Wi,render as mt}from"ink";import Gi from"minimist";import{SWRConfig as Vi}from"swr";import xe,{createContext as ns,useState as F,useEffect as Ee,useContext as ss,useMemo as Hi,useRef as Yi}from"react";import is from"swr/immutable";import rs from"os";import B from"path";import zi from"conf";import{exec as Qi}from"node:child_process";import*as P from"node:fs";import{readFileSync as Xi}from"node:fs";import{EventEmitter as Zi}from"events";import{MembraneConfigLoader as er,MembraneClient as os,WorkspaceElementType as x,extractMembraneErrorData as te,WorkspaceElementSpecs as ye,setValueAtLocator as en,getDataCollectionCreateFields as tn,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as gt,getRequiredFieldsFromSchema as tr,getValueAtLocator as nr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as nn}from"@membranehq/sdk";import sn from"jsonwebtoken";import{Spinner as sr,TextInput as ir,Select as rr}from"@inkjs/ui";import yt from"ink-spinner";import or from"ink-text-input";import*as ar from"node:crypto";import{createHash as cr}from"node:crypto";import*as lr from"node:os";import M from"fs";import ur from"archiver";import fr from"form-data";import Ie from"js-yaml";import hr from"unzipper";import dr from"lodash/isEqual.js";import pr from"chokidar";import{fileURLToPath as mr}from"node:url";import k from"chalk";import{Command as gr}from"commander";import rn from"axios";import{FastMCP as yr}from"fastmcp";import{z}from"zod";import on from"lodash/merge.js";import wr from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import br from"lodash/template.js";import Sr from"lodash/templateSettings.js";const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},us=ns(null);function Cr({children:s,membraneCLIService:e}){const{data:t}=is("/account"),[n,i]=F(D.NOT_INITIALIZED),[r,o]=F([]),[a,l]=F({}),[u,p]=F([]),[d,h]=F(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ee(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),v=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifications.on(J.StateChanged,f),e.notifications.on(J.StatsChanged,y),e.notifications.on(J.LogAdded,C),e.notifications.on(J.ConflictsChanged,v),e.notifications.on(J.ConfigChanged,A),e.init(),()=>{e.notifications.off(J.StateChanged,f),e.notifications.off(J.StatsChanged,y),e.notifications.off(J.LogAdded,C),e.notifications.off(J.ConflictsChanged,v),e.notifications.off(J.ConfigChanged,A)}},[]),m(us.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(Cr,"MembraneCLIServiceProvider");function oe(){const s=ss(us);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const kr="membrane",vr="membrane.config.yml",an="https://api.integration.app";function cn(){const s=process.cwd(),e=R.join(s,kr),t=R.join(s,vr),n=e,i=R.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(cn,"getPaths");function Er(){return cn().membraneDirPath}c(Er,"getBasePath");const Ir={pat:{type:"string"},workspace:{type:"object"}},fs=new zi({schema:Ir,configName:"config",cwd:B.join(rs.homedir(),".membrane")}),Tr=c(s=>{fs.set("pat",s)},"setPat"),hs=c(()=>fs.get("pat"),"getPat");class ds{static{c(this,"AccountApiClient")}constructor(e=an){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=hs();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 Nr=c(s=>{const e=new ds(an);return t=>e.get(t)},"createAccountApiFetcher"),ps=ns(process.cwd());function Ar({cwd:s,children:e}){return m(ps.Provider,{value:s,children:e})}c(Ar,"CwdProvider");function Or(){return ss(ps)}c(Or,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ar,{cwd:n,children:m(Vi,{value:{fetcher:Nr()},children:m(Cr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const ln=[{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=R.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.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=R.join(process.cwd(),".cursor"),e=R.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function $r({onExit:s,onComplete:e}){const[t,n]=F(0),[i,r]=F(!1),[o,a]=F(null),[l,u]=F(""),[p,d]=F("");Pe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(ln.length-1,t+1));else if(f.return||w===" "){const y=ln[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(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?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(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?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(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:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(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:ln.map((w,f)=>E(b,{children:[E(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),E(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($r,"AddMcpServerScreen");class ms extends Zi{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 He{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new er}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}isCacheDefined(e){return this.sdkLoader.hasValidConfig()}}const Ze=He.getInstance();function bt(s){return Ze.loadConfig(s)}c(bt,"readProjectConfig");class Lr{static{c(this,"MembraneClientManager")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return sn.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=bt(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 os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: 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 le=new Lr;async function gs(s){const e=await le.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(gs,"getWorkspaceId");class Dr extends ms{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await le.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){if(this.clientId)return;const t=await(await le.getClient(process.cwd())).post("/local-clients",{hostname:rs.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await le.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await le.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const ue=new Dr({heartbeatIntervalMs:15e3});function Pr(){const[s,e]=F(null),[t,n]=F([]),[i,r]=F(null);return Ee(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return ue.on(J.McpStatusChanged,o),ue.on(J.McpServersChanged,a),()=>{ue.off(J.McpStatusChanged,o),ue.off(J.McpServersChanged,a)}},[]),{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(Pr,"useMcpStatus");function xr(){const{error:s,serverCount:e,allMcpServers:t}=Pr(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(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:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Wi,{}),"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:E(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");const St=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ys(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ys,"truncateText");function un({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(sr,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===D.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===D.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:St(i.type),children:i.message},i.timestamp+r))})}return s}c(un,"EnsureInitialized");function ws({onExit:s,showEscOption:e=!0}){const[t,n]=F(""),{data:i,error:r,isLoading:o}=is("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(Pe((f,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return c(w,"handleSelect"),E(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"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(ir,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(rr,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(ws,"SelectWorkspace");function Mr({currentPat:s,onSubmit:e}){const[t,n]=F(""),[i,r]=F(!1),[o,a]=F(null);return E(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(or,{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:E(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Mr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const Rr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},fn=[et.Authenticate,et.ConnectWorkspace];function bs({onComplete:s}){const{config:e}=oe(),[t,n]=F(!1),[i,r]=F(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=hs(),l=fn[i],u=i+1,p=fn.length,d=fn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:Rr[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ds;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Tr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Kr,{status:w.status,label:w.label},w.id))})]}),l===et.Authenticate&&m(Mr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(ws,{onExit:g,showEscOption:!1})]})}c(bs,"Setup");function Kr({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Kr,"StepDisplay");function hn(){const{stats:s}=oe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(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])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(hn,"ElementStats");const dn=5,_r=6;function jr(){const{logs:s}=oe(),[e,t]=F(0),n=Math.min(100,process.stdout.columns||100),i=dn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-_r,u=e<s.length-i,p=e>0;return Pe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>dn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:St(d.type),children:ys(d.message,l)})},d.timestamp+h)),s.length>dn&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(jr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"},Ct=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Fr(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=F(0),[r,o]=F(!1);return Pe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:Ct.length-1):l.downArrow?i(u=>u<Ct.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),Ct[n].value==="sync"?e({watch:!0}):t()))}),Ee(()=>{s!==D.CONFLICTS&&r&&o(!1)},[s,r]),E(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(pn,{})}),E(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?E(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:Ct.map((a,l)=>m(b,{flexDirection:"column",children:E(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(Fr,"ResolveChangesUI");const Br={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function pn(){const{conflicts:s}=oe(),e=Hi(()=>{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=Br[i][r];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(pn,"Conflicts");function Ur(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?ys(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Jr(e),children:[" [",qr(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Fr,{}):E(Zt,{children:[m(b,{paddingTop:1,children:m(hn,{})}),t.length>0&&m(jr,{})]})]})}c(Ur,"Workspace");function qr(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(qr,"getStatusDisplay");function Jr(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Jr,"getStatusColor");const Wr="https://console.integration.app/w";function Gr(){const s=Or(),e=Yi(!0),{exit:t,state:n}=oe(),[i,r]=F(null),o=i??(n===D.SETTING_UP?"setup":"main");Pe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await gs(s),u=`${Wr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Qi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(ws,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m($r,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(bs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(un,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(xr,{})}),m(Ur,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Gr,"Main");class Vr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=ue}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 T=new Vr,we=R.join(lr.tmpdir(),"membrane-mcp-status"),Ss=3e4;class Hr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kt(void 0,e),n=Cs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function kt(s,e){try{const t=e||process.cwd();if(!s){const i=Cs(t);return i.length===0?null:i[0]}const n=yn(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ss)return tt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>Ss)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(kt,"getMcpStatus");function Cs(s){try{const e=s||process.cwd(),t=gn(e);if(!P.existsSync(we))return[];const n=P.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=kt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(Cs,"getAllMcpStatusFiles");function mn(s){try{const t={...kt(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};P.existsSync(we)||P.mkdirSync(we,{recursive:!0});const n=yn(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(mn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=yn(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=gn(t);if(P.existsSync(we)){const i=P.readdirSync(we);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(R.join(we,r))}}}catch{}}c(tt,"clearMcpStatus");function Yr(s,e){const t=kt(s,e);t&&mn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Yr,"trackToolExecution");function gn(s){return cr("md5").update(s).digest("hex").slice(0,8)}c(gn,"getCwdHash");function yn(s,e){const t=gn(e);return R.join(we,`mcp-${t}-${s}.json`)}c(yn,"getStatusFilePath");const se={[x.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")},[x.Connector]:{element:"connector",elements:"connectors",exportable:!1},[x.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[x.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[x.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[x.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[x.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[x.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[x.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function zr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(zr,"baseExportCleanup");class ks{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 vs{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new ks,this.handler=e}async refresh(){try{const e=new ks,t=await this.handler.getIntegrations();e.addAll(t);const n=[x.Integration,x.Connector],i=Object.keys(se),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){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function Qr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>wn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>wn(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,wn(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 T.success("[connectors] Remote workspace data retrieved successfully"),t}c(Qr,"getWorkspaceData");function wn(s,e){return e=zr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(wn,"cleanUpForExport");const nt="connectors",st="development",bn={};async function Xr({integrations:s,allConnectors:e=!1}){const t=Er(),n=await le.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){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await so({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await io({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Xr,"pullConnectors");async function Zr(){const s=await le.getClient(process.cwd()),e=await Qr(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=Sn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return M.statSync(d).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const d=M.readdirSync(B.join(a,p)),h=await Cn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,T.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Es({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>M.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await no({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(Zr,"pushConnectors");function Sn(){const s=cn();return B.join(s.membraneDirPath,nt)}c(Sn,"getConnectorsPath");async function Cn(s){return Ie.load(M.readFileSync(B.join(Sn(),s,`${s}.yml`),"utf8"))}c(Cn,"readConnector");async function eo(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=ur("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.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=M.readdirSync(s);for(const a of o){const l=B.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(eo,"createZipArchive");async function to(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=hr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(to,"extractZipArchive");async function no({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Sn(),vt(e),Is(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await eo(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new fr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==st)T.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)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(no,"pushConnectorVersion");async function Es({client:s,connectorId:e}){if(bn[e])return bn[e];const t=await s.get(`connectors/${e}`);return bn[e]=t,t}c(Es,"getConnector");async function so({basePath:s,connector:e}){const t=vt(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${vt(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(so,"pullConnector");async function io({client:s,connector:e,connectorVersion:t,basePath:n}){const i=vt(e),r=Is(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=B.join(o,"src");M.mkdirSync(u,{recursive:!0}),await to(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(io,"pullConnectorVersion");function vt(s){return s.key}c(vt,"getConnectorDirName");function Is(s){return s??st}c(Is,"getConnectorVersionDirName");function ro(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(ro,"isConnectorSourceFile");async function oo(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await le.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(oo,"putConnectorFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await Cn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await le.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(ao,"deleteConnectorFile");const co="membrane",lo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Et(s){return R.join(s,co)}c(Et,"getMembraneDir");const uo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state"],Ts=[x.Action,x.FieldMapping,x.Flow,x.DataSource];class G{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||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[x.Integration].apiPath;return R.join(t,this.integrationKey,e,this.key)}return R.join(e,this.key)}get path(){return R.join(this.dirPath,"spec.yaml")}get relativePath(){return R.relative(Et(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return dr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return uo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(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 G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===x.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).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 getElementTypeFromPath(e){return Object.values(x).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return R.relative(Et(process.cwd()),e)}static isIntegrationSpecific(e){return Ts.includes(e)}static canBeIntegrationSpecific(e){return Ts.includes(e)}}class fo{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=Et(process.cwd())}async getElementsByType(e,t){const n=[],i=R.join(this.basePath,ye[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=R.join(this.basePath,ye[x.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=R.join(this.basePath,t.dirPath),i=R.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=R.join(this.basePath,e.path),n=R.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=R.join(this.basePath,ye[x.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return G.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=R.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(R.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class ho{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.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&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=G.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=G.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>G.fromData(x.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===x.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===x.Integration).map(r=>r.key).join(", ")}`)}if(e.type===x.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===x.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===x.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===x.Integration).map(r=>r.key).join(", ")}`)}this.transformParentDependency(e,t,n)}transformParentDependency(e,t,n){if(!e.hasParent())return;const i=e.getParentKey();if(!i)return;const r=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(r)t[i]=r.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const kn=Symbol.for("yaml.alias"),vn=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),Ns=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Se=c(s=>!!s&&typeof s=="object"&&s[ie]===kn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===be,"isMap"),j=c(s=>!!s&&typeof s=="object"&&s[ie]===Ns,"isPair"),K=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),Ke=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case be:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case kn:case be:case he:case Me:return!0}return!1}c(q,"isNode");const As=c(s=>(K(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Os=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=$s(e);Te(s)?_e(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):_e(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Os,Ne.REMOVE=de;function _e(s,e,t,n){const i=Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),_e(s,i,t,n);if(typeof i!="symbol"){if(U(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===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=_e("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=_e("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(_e,"visit_");async function It(s,e){const t=$s(e);Te(s)?await je(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await je(null,s,t,Object.freeze([]))}c(It,"visitAsync"),It.BREAK=ee,It.SKIP=Os,It.REMOVE=de;async function je(s,e,t,n){const i=await Ls(s,e,t,n);if(q(i)||j(i))return Ds(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(j(e)){n=Object.freeze(n.concat(e));const r=await je("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await je("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(je,"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(j(e))return t.Pair?.(s,e,n);if(K(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}c(Ls,"callVisitor");function Ds(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(j(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(Ds,"replaceNode");const po={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},mo=c(s=>s.replace(/[!,[\]{}]/g,e=>po[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.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+mo(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&&q(e.contents)){const r={};Ne(e.contents,(o,a)=>{q(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
|
+
`)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function Ps(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(Ps,"anchorIsValid");function xs(s){const e=new Set;return Ne(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(xs,"anchorNames");function Ms(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Ms,"findNewAnchor");function go(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=xs(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&&(K(o.node)||U(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(go,"createNodeAnchors");function Fe(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=Fe(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=Fe(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=Fe(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=Fe(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Fe,"applyReviver");function re(s,e,t){if(Array.isArray(s))return s.map((n,i)=>re(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(re,"toJS");class En{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,ie,{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(!Te(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=re(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Fe(r,{"":a},"",a):a}}class Tt extends En{static{c(this,"Alias")}constructor(e){super(kn),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=[],Ne(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||(re(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=Nt(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(Ps(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 Nt(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(U(e)){let n=0;for(const i of e.items){const r=Nt(s,i,t);r>n&&(n=r)}return n}else if(j(e)){const n=Nt(s,e.key,t),i=Nt(s,e.value,t);return Math.max(n,i)}return 1}c(Nt,"getAliasCount");const Rs=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends En{static{c(this,"Scalar")}constructor(e){super(he),this.value=e}toJSON(e,t){return t?.keep?this.value:re(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 yo="tag:yaml.org,2002:";function wo(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(wo,"findTagObject");function it(s,e,t){if(Te(s)&&(s=s.contents),q(s))return s;if(j(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 Tt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=yo+e.slice(2));let u=wo(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[Me]: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(it,"createNode");function At(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 it(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(At,"collectionFromPath");const rt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Ks extends En{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=>q(n)||j(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(rt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(U(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,At(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(U(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&&K(r)?r.value:r:U(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!j(t))return!1;const n=t.value;return n==null||e&&K(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 U(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(U(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,At(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const bo=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 Ae=c((s,e,t)=>s.endsWith(`
|
|
4
4
|
`)?pe(t,e):t.includes(`
|
|
5
5
|
`)?`
|
|
6
6
|
`+pe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),_s="flow",In="block",Ot="quoted";function $t(s,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return s;i<r&&(r=0);const l=Math.max(1+r,1+i-e.length);if(s.length<=l)return s;const u=[],p={};let d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let h,g,w=!1,f=-1,y=-1,C=-1;t===In&&(f=js(s,f,e.length),f!==-1&&(d=f+l));for(let A;A=s[f+=1];){if(t===Ot&&A==="\\"){switch(y=f,s[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}C=f}if(A===`
|
|
@@ -18,7 +18,7 @@ ${e}${s.slice(I+1,O)}`)}return v}c($t,"foldFlowLines");function js(s,e,t){let n=
|
|
|
18
18
|
${t}`)+"'";return e.implicitKey?n:$t(n,t,_s,Lt(e,!1))}c(Tn,"singleQuotedString");function Be(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=ot;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=Tn:r&&!i?n=ot:n=t?Tn:ot}return n(s,e)}c(Be,"quotedString");let Nn;try{Nn=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{Nn=/\n+(?!\n|$)/g}function
|
|
21
|
+
|$)`,"g")}catch{Nn=/\n+(?!\n|$)/g}function Pt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Be(t,n);const u=n.indent||(n.forceBlockIndent||Dt(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===L.BLOCK_FOLDED?!1:e===L.BLOCK_LITERAL?!0:!So(t,l,u.length);if(!t)return p?`|
|
|
22
22
|
`:`>
|
|
23
23
|
`;let d,h;for(h=t.length;h>0;--h){const O=t[h-1];if(O!==`
|
|
24
24
|
`&&O!==" "&&O!==" ")break}let g=t.substring(h);const w=g.indexOf(`
|
|
@@ -27,11 +27,11 @@ ${t}`)+"'";return e.implicitKey?n:$t(n,t,_s,Lt(e,!1))}c(Tn,"singleQuotedString")
|
|
|
27
27
|
`)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let I=(f?u?"2":"1":"")+d;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!p){const O=t.replace(/\n+/g,`
|
|
28
28
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const _=Lt(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(_.onOverflow=()=>{$=!0});const N=$t(`${v}${O}${g}`,u,In,_);if(!$)return`>${I}
|
|
29
29
|
${u}${N}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
|
|
30
|
-
${u}${v}${t}${g}`}c(
|
|
30
|
+
${u}${v}${t}${g}`}c(Pt,"blockString");function Co(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:p}=e;if(a&&r.includes(`
|
|
31
31
|
`)||p&&/[[\]{},]/.test(r))return Be(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
|
|
32
|
-
`)?Be(r,e):
|
|
33
|
-
`))return
|
|
34
|
-
${l}`);if(o){const h=c(f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return Be(r,e)}return a?d:$t(d,l,_s,Lt(e,!1))}c(Co,"plainString");function at(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const l=c(p=>{switch(p){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?Be(o.value,e):
|
|
32
|
+
`)?Be(r,e):Pt(s,e,t,n);if(!a&&!p&&i!==L.PLAIN&&r.includes(`
|
|
33
|
+
`))return Pt(s,e,t,n);if(Dt(r)){if(l==="")return e.forceBlockIndent=!0,Pt(s,e,t,n);if(a&&l===u)return Be(r,e)}const d=r.replace(/\n+/g,`$&
|
|
34
|
+
${l}`);if(o){const h=c(f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return Be(r,e)}return a?d:$t(d,l,_s,Lt(e,!1))}c(Co,"plainString");function at(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const l=c(p=>{switch(p){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?Be(o.value,e):Pt(o,e,t,n);case L.QUOTE_DOUBLE:return ot(o.value,e);case L.QUOTE_SINGLE:return Tn(o.value,e);case L.PLAIN:return Co(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:d}=e.options,h=i&&p||d;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(at,"stringifyString");function Fs(s,e){const t=Object.assign({blockQuote:!0,commentString:bo,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}c(Fs,"createStringifyContext");function ko(s,e){if(e.tag){const i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(K(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}c(ko,"getTagObject");function vo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(K(s)||U(s))&&s.anchor;r&&Ps(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}c(vo,"stringifyProps");function Ue(s,e,t,n){if(j(s))return s.toString(e,t,n);if(Se(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let i;const r=q(s)?s:e.doc.createNode(s,{onTagObj:c(l=>i=l,"onTagObj")});i??(i=ko(e.doc.schema.tags,r));const o=vo(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):K(r)?at(r,e,t,n):r.toString(e,t,n);return o?K(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
35
35
|
${e.indent}${a}`:a}c(Ue,"stringify$2");function Eo({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:p,simpleKeys:d}}=t;let h=q(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(U(s)||!q(s)&&typeof s=="object"){const _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||U(s)||(K(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+l});let w=!1,f=!1,y=Ue(s,t,()=>w=!0,()=>f=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!d||e==null&&g)return y=`? ${y}`,h&&!w?y+=Ae(y,t.indent,u(h)):f&&i&&i(),y;w&&(h=null),g?(h&&(y+=Ae(y,t.indent,u(h))),y=`? ${y}
|
|
36
36
|
${a}:`):(y=`${y}:`,h&&(y+=Ae(y,t.indent,u(h))));let C,v,A;q(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&K(e)&&(t.indentAtStart=y.length+1),f=!1,!p&&l.length>=2&&!t.inFlow&&!g&&Ke(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const O=Ue(e,t,()=>I=!0,()=>f=!0);let $=" ";if(h||C||v){if($=C?`
|
|
37
37
|
`:"",v){const _=u(v);$+=`
|
|
@@ -42,7 +42,7 @@ ${pe(_,t.indent)}`}O===""&&!t.inFlow?$===`
|
|
|
42
42
|
${t.indent}`}else if(!g&&U(e)){const _=O[0],N=O.indexOf(`
|
|
43
43
|
`),V=N!==-1,ge=t.inFlow??e.flow??e.items.length===0;if(V||!ge){let De=!1;if(V&&(_==="&"||_==="!")){let H=O.indexOf(" ");_==="&"&&H!==-1&&H<N&&O[H+1]==="!"&&(H=O.indexOf(" ",H+1)),(H===-1||N<H)&&(De=!0)}De||($=`
|
|
44
44
|
${t.indent}`)}}else(O===""||O[0]===`
|
|
45
|
-
`)&&($="");return y+=$+O,t.inFlow?I&&n&&n():A&&!I?y+=Ae(y,t.indent,u(A)):f&&i&&i(),y}c(Eo,"stringifyPair");function Bs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Bs,"warn");const
|
|
45
|
+
`)&&($="");return y+=$+O,t.inFlow?I&&n&&n():A&&!I?y+=Ae(y,t.indent,u(A)):f&&i&&i(),y}c(Eo,"stringifyPair");function Bs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Bs,"warn");const xt="<<",me={identify:c(s=>s===xt||typeof s=="symbol"&&s.description===xt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new L(Symbol(xt)),{addToJSMap:Us}),"resolve"),stringify:c(()=>xt,"stringify")},Io=c((s,e)=>(me.identify(e)||K(e)&&(!e.type||e.type===L.PLAIN)&&me.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===me.tag&&t.default),"isMergeKey");function Us(s,e,t){if(t=s&&Se(t)?t.resolve(s.doc):t,Ke(t))for(const n of t.items)An(s,e,n);else if(Array.isArray(t))for(const n of t)An(s,e,n);else An(s,e,t)}c(Us,"addMergeToJSMap");function An(s,e,t){const n=s&&Se(t)?t.resolve(s.doc):t;if(!Re(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(An,"mergeValue");function qs(s,e,{key:t,value:n}){if(q(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Io(s,t))Us(s,e,n);else{const i=re(t,"",s);if(e instanceof Map)e.set(i,re(n,i,s));else if(e instanceof Set)e.add(i);else{const r=To(t,i,s),o=re(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}c(qs,"addPairToJSMap");function To(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(q(s)&&t?.doc){const n=Fs(t.doc,{});n.anchors=new Set;for(const r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),Bs(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}c(To,"stringifyKey");function On(s,e,t){const n=it(s,void 0,t),i=it(e,void 0,t);return new Q(n,i)}c(On,"createPair");class Q{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,ie,{value:Ns}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return q(t)&&(t=t.clone(e)),q(n)&&(n=n.clone(e)),new Q(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return qs(t,n,this)}toString(e,t,n){return e?.doc?Eo(this,e,t,n):JSON.stringify(this)}}function Js(s,e,t){return(e.inFlow??s.flow?Ao:No)(s,e,t)}c(Js,"stringifyCollection");function No({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,p=Object.assign({},t,{indent:r,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const f=e[w];let y=null;if(q(f))!d&&f.spaceBefore&&h.push(""),Mt(t,h,f.commentBefore,d),f.comment&&(y=f.comment);else if(j(f)){const v=q(f.key)?f.key:null;v&&(!d&&v.spaceBefore&&h.push(""),Mt(t,h,v.commentBefore,d))}d=!1;let C=Ue(f,p,()=>y=null,()=>d=!0);y&&(C+=Ae(C,r,u(y))),d&&y&&(d=!1),h.push(n+C)}let g;if(h.length===0)g=i.start+i.end;else{g=h[0];for(let w=1;w<h.length;++w){const f=h[w];g+=f?`
|
|
46
46
|
${l}${f}`:`
|
|
47
47
|
`}}return s?(g+=`
|
|
48
48
|
`+pe(u(s),l),a&&a()):d&&o&&o(),g}c(No,"stringifyBlockCollection");function Ao({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,p=0;const d=[];for(let w=0;w<s.length;++w){const f=s[w];let y=null;if(q(f))f.spaceBefore&&d.push(""),Mt(e,d,f.commentBefore,!1),f.comment&&(y=f.comment);else if(j(f)){const v=q(f.key)?f.key:null;v&&(v.spaceBefore&&d.push(""),Mt(e,d,v.commentBefore,!1),v.comment&&(u=!0));const A=q(f.value)?f.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):f.value==null&&v?.comment&&(y=v.comment)}y&&(u=!0);let C=Ue(f,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ae(C,n,a(y))),!u&&(d.length>p||C.includes(`
|
|
@@ -52,10 +52,10 @@ ${r}${i}${f}`:`
|
|
|
52
52
|
${i}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}c(Ao,"stringifyFlowCollection");function Mt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=pe(e(n),s);t.push(r.trimStart())}}c(Mt,"addCommentBefore");function Oe(s,e){const t=K(e)?e.value:e;for(const n of s)if(j(n)&&(n.key===e||n.key===t||K(n.key)&&n.key.value===t))return n}c(Oe,"findPair");class ne extends Ks{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(be,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=c((l,u)=>{if(typeof r=="function")u=r.call(t,l,u);else if(Array.isArray(r)&&!r.includes(l))return;(u!==void 0||i)&&o.items.push(On(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;j(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Q(e,e?.value):n=new Q(e.key,e.value);const i=Oe(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);K(i.value)&&Rs(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=Oe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=Oe(this.items,e)?.value;return(!t&&K(i)?i.value:i)??void 0}has(e){return!!Oe(this.items,e)}set(e,t){this.add(new Q(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)qs(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!j(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Js(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const qe={collection:"map",default:!0,nodeClass:ne,tag:"tag:yaml.org,2002:map",resolve(s,e){return Re(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ne.from(s,e,t),"createNode")};class Ce extends Ks{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Me,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Rt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Rt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&K(i)?i.value:i}has(e){const t=Rt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Rt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];K(i)&&Rs(t)?i.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let i=0;for(const r of this.items)n.push(re(r,String(i++),t));return n}toString(e,t,n){return e?Js(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const l=t instanceof Set?a:String(o++);a=i.call(t,l,a)}r.items.push(it(a,void 0,n))}}return r}}function Rt(s){let e=K(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Rt,"asItemIndex");const Je={collection:"seq",default:!0,nodeClass:Ce,tag:"tag:yaml.org,2002:seq",resolve(s,e){return Ke(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ce.from(s,e,t),"createNode")},Kt={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),at(s,e,t,n)}},_t={identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new L(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&_t.test.test(s)?s:e.options.nullStr,"stringify")},$n={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&$n.test.test(s)){const n=s[0]==="t"||s[0]==="T";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}};function ae({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}c(ae,"stringifyNumber");const Ws={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},Gs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Vs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},jt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Ln=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Hs(s,e,t){const{value:n}=s;return jt(n)&&n>=0?t+n.toString(e):ae(s)}c(Hs,"intStringify$1");const Ys={identify:c(s=>jt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>Ln(s,2,8,t),"resolve"),stringify:c(s=>Hs(s,8,"0o"),"stringify")},zs={identify:jt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>Ln(s,0,10,t),"resolve"),stringify:ae},Qs={identify:c(s=>jt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>Ln(s,2,16,t),"resolve"),stringify:c(s=>Hs(s,16,"0x"),"stringify")},Oo=[qe,Je,Kt,_t,$n,Ys,zs,Qs,Ws,Gs,Vs];function Xs(s){return typeof s=="bigint"||Number.isInteger(s)}c(Xs,"intIdentify$1");const Ft=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),$o=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Ft},{identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Ft},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:Ft},{identify:Xs,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>Xs(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:c(s=>parseFloat(s),"resolve"),stringify:Ft}],Lo={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Do=[qe,Je].concat($o,Lo),Dn={identify:c(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),p=new Array(u);for(let d=0,h=0;d<u;++d,h+=l)p[d]=a.substr(h,l);a=p.join(e===L.BLOCK_LITERAL?`
|
|
53
53
|
`:" ")}return at({comment:s,type:e,value:a},n,i,r)}};function Zs(s,e){if(Ke(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!j(n)){if(Re(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
|
|
54
54
|
${i.key.commentBefore}`:n.commentBefore),n.comment){const r=i.value??i.key;r.comment=r.comment?`${n.comment}
|
|
55
|
-
${r.comment}`:n.comment}n=i}s.items[t]=j(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}c(Zs,"resolvePairs");function ei(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(On(a,l,t))}return i}c(ei,"createPairs");const xn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zs,createNode:ei};class Ye extends Ce{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ne.prototype.add.bind(this),this.delete=ne.prototype.delete.bind(this),this.get=ne.prototype.get.bind(this),this.has=ne.prototype.has.bind(this),this.set=ne.prototype.set.bind(this),this.tag=Ye.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(j(i)?(r=re(i.key,"",t),o=re(i.value,r,t)):r=re(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=ei(e,t,n),r=new this;return r.items=i.items,r}}Ye.tag="tag:yaml.org,2002:omap";const Pn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Zs(s,e),n=[];for(const{key:i}of t.items)K(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ye,t)},createNode:c((s,e,t)=>Ye.from(s,e,t),"createNode")};function ti({value:s,source:e},t){return e&&(s?ni:si).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(ti,"boolStringify");const ni={identify:c(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:c(()=>new L(!0),"resolve"),stringify:ti},si={identify:c(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:c(()=>new L(!1),"resolve"),stringify:ti},xo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},Po={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Mo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},ct=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Bt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}c(Bt,"intResolve");function Mn(s,e,t){const{value:n}=s;if(ct(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}c(Mn,"intStringify");const Ro={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Bt(s,2,2,t),"resolve"),stringify:c(s=>Mn(s,2,"0b"),"stringify")},Ko={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Bt(s,1,8,t),"resolve"),stringify:c(s=>Mn(s,8,"0"),"stringify")},_o={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Bt(s,0,10,t),"resolve"),stringify:ae},jo={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Bt(s,2,16,t),"resolve"),stringify:c(s=>Mn(s,16,"0x"),"stringify")};class ze extends ne{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=ze.tag}add(e){let t;j(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),Oe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Oe(this.items,e);return!t&&j(n)?K(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=Oe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(On(o,null,n));return r}}ze.tag="tag:yaml.org,2002:set";const Rn={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>ze.from(s,e,t),"createNode"),resolve(s,e){if(Re(s)){if(s.hasAllNullValues(!0))return Object.assign(new ze,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Kn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}c(Kn,"parseSexagesimal");function ii(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ae(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(ii,"stringifySexagesimal");const ri={identify:c(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:c((s,e,{intAsBigInt:t})=>Kn(s,t),"resolve"),stringify:ii},oi={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:c(s=>Kn(s,!1),"resolve"),stringify:ii},Ut={identify:c(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(Ut.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let d=Kn(p,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},ai=[qe,Je,Kt,_t,ni,si,Ro,Ko,_o,jo,xo,Po,Mo,Dn,me,Pn,xn,Rn,ri,oi,Ut],ci=new Map([["core",Oo],["failsafe",[qe,Je,Kt]],["json",Do],["yaml11",ai],["yaml-1.1",ai]]),li={binary:Dn,bool:$n,float:Vs,floatExp:Gs,floatNaN:Ws,floatTime:oi,int:zs,intHex:Qs,intOct:Ys,intTime:ri,map:qe,merge:me,null:_t,omap:Pn,pairs:xn,seq:Je,set:Rn,timestamp:Ut},Fo={"tag:yaml.org,2002:binary":Dn,"tag:yaml.org,2002:merge":me,"tag:yaml.org,2002:omap":Pn,"tag:yaml.org,2002:pairs":xn,"tag:yaml.org,2002:set":Rn,"tag:yaml.org,2002:timestamp":Ut};function _n(s,e,t){const n=ci.get(e);if(n&&!s)return t&&!n.includes(me)?n.concat(me):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(ci.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(me)),i.reduce((r,o)=>{const a=typeof o=="string"?li[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(li).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(_n,"getTags");const Bo=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Xt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?_n(e,"compat"):e?_n(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?Fo:{},this.tags=_n(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:qe}),Object.defineProperty(this,he,{value:Kt}),Object.defineProperty(this,Me,{value:Je}),this.sortMapEntries=typeof o=="function"?o:o===!0?Bo:null}clone(){const e=Object.create(Xt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Uo(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Fs(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(pe(l,""))}let o=!1,a=null;if(s.contents){if(q(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(pe(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=Ue(s.contents,i,()=>a=null,l);a&&(u+=Ae(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
|
|
55
|
+
${r.comment}`:n.comment}n=i}s.items[t]=j(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}c(Zs,"resolvePairs");function ei(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(On(a,l,t))}return i}c(ei,"createPairs");const Pn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Zs,createNode:ei};class Ye extends Ce{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ne.prototype.add.bind(this),this.delete=ne.prototype.delete.bind(this),this.get=ne.prototype.get.bind(this),this.has=ne.prototype.has.bind(this),this.set=ne.prototype.set.bind(this),this.tag=Ye.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(j(i)?(r=re(i.key,"",t),o=re(i.value,r,t)):r=re(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=ei(e,t,n),r=new this;return r.items=i.items,r}}Ye.tag="tag:yaml.org,2002:omap";const xn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Zs(s,e),n=[];for(const{key:i}of t.items)K(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ye,t)},createNode:c((s,e,t)=>Ye.from(s,e,t),"createNode")};function ti({value:s,source:e},t){return e&&(s?ni:si).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(ti,"boolStringify");const ni={identify:c(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:c(()=>new L(!0),"resolve"),stringify:ti},si={identify:c(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:c(()=>new L(!1),"resolve"),stringify:ti},Po={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},xo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Mo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},ct=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Bt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}c(Bt,"intResolve");function Mn(s,e,t){const{value:n}=s;if(ct(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}c(Mn,"intStringify");const Ro={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Bt(s,2,2,t),"resolve"),stringify:c(s=>Mn(s,2,"0b"),"stringify")},Ko={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Bt(s,1,8,t),"resolve"),stringify:c(s=>Mn(s,8,"0"),"stringify")},_o={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Bt(s,0,10,t),"resolve"),stringify:ae},jo={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Bt(s,2,16,t),"resolve"),stringify:c(s=>Mn(s,16,"0x"),"stringify")};class ze extends ne{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=ze.tag}add(e){let t;j(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),Oe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Oe(this.items,e);return!t&&j(n)?K(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=Oe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(On(o,null,n));return r}}ze.tag="tag:yaml.org,2002:set";const Rn={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>ze.from(s,e,t),"createNode"),resolve(s,e){if(Re(s)){if(s.hasAllNullValues(!0))return Object.assign(new ze,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Kn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}c(Kn,"parseSexagesimal");function ii(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ae(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(ii,"stringifySexagesimal");const ri={identify:c(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:c((s,e,{intAsBigInt:t})=>Kn(s,t),"resolve"),stringify:ii},oi={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:c(s=>Kn(s,!1),"resolve"),stringify:ii},Ut={identify:c(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(Ut.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let d=Kn(p,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},ai=[qe,Je,Kt,_t,ni,si,Ro,Ko,_o,jo,Po,xo,Mo,Dn,me,xn,Pn,Rn,ri,oi,Ut],ci=new Map([["core",Oo],["failsafe",[qe,Je,Kt]],["json",Do],["yaml11",ai],["yaml-1.1",ai]]),li={binary:Dn,bool:$n,float:Vs,floatExp:Gs,floatNaN:Ws,floatTime:oi,int:zs,intHex:Qs,intOct:Ys,intTime:ri,map:qe,merge:me,null:_t,omap:xn,pairs:Pn,seq:Je,set:Rn,timestamp:Ut},Fo={"tag:yaml.org,2002:binary":Dn,"tag:yaml.org,2002:merge":me,"tag:yaml.org,2002:omap":xn,"tag:yaml.org,2002:pairs":Pn,"tag:yaml.org,2002:set":Rn,"tag:yaml.org,2002:timestamp":Ut};function _n(s,e,t){const n=ci.get(e);if(n&&!s)return t&&!n.includes(me)?n.concat(me):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(ci.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(me)),i.reduce((r,o)=>{const a=typeof o=="string"?li[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(li).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(_n,"getTags");const Bo=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Xt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?_n(e,"compat"):e?_n(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?Fo:{},this.tags=_n(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:qe}),Object.defineProperty(this,he,{value:Kt}),Object.defineProperty(this,Me,{value:Je}),this.sortMapEntries=typeof o=="function"?o:o===!0?Bo:null}clone(){const e=Object.create(Xt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Uo(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Fs(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(pe(l,""))}let o=!1,a=null;if(s.contents){if(q(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(pe(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=Ue(s.contents,i,()=>a=null,l);a&&(u+=Ae(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
|
|
56
56
|
`)?(t.push("..."),t.push(pe(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(pe(r(l),"")))}return t.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}c(Uo,"stringifyDocument");class Qe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:vn});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Z({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Qe.prototype,{[ie]:{value:vn}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=q(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){We(this.contents)&&this.contents.add(e)}addIn(e,t){We(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=
|
|
58
|
+
`}c(Uo,"stringifyDocument");class Qe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:vn});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Z({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Qe.prototype,{[ie]:{value:vn}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=q(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){We(this.contents)&&this.contents.add(e)}addIn(e,t){We(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=xs(this);e.anchor=!t||n.has(t)?Ms(t||"a",n):t}return new Tt(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=c(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=go(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},f=it(e,p,w);return a&&U(f)&&(f.flow=!0),h(),f}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Q(i,r)}delete(e){return We(this.contents)?this.contents.delete(e):!1}deleteIn(e){return rt(e)?this.contents==null?!1:(this.contents=null,!0):We(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return U(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return rt(e)?!t&&K(this.contents)?this.contents.value:this.contents:U(this.contents)?this.contents.getIn(e,t):void 0}has(e){return U(this.contents)?this.contents.has(e):!1}hasIn(e){return rt(e)?this.contents!==void 0:U(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=At(this.schema,[e],t):We(this.contents)&&this.contents.set(e,t)}setIn(e,t){rt(e)?this.contents=t:this.contents==null?this.contents=At(this.schema,Array.from(e),t):We(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Z({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Z({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new Xt(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},l=re(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:p}of a.anchors.values())r(p,u);return typeof o=="function"?Fe(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Uo(this,e)}}function We(s){if(U(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(We,"assertCollection");class jn extends Error{static{c(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class $e extends jn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class ui extends jn{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const qt=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
59
59
|
`),o=a+o}if(/[^ ]/.test(o)){let a=1;const l=t.linePos[1];l&&l.line===n&&l.col>i&&(a=Math.max(1,Math.min(l.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
|
|
60
60
|
|
|
61
61
|
${o}
|
|
@@ -137,16 +137,16 @@ ${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=Ve(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=Ve(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=zt(n),r=Ve(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=zt(e),n=Ve(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=zt(e),n=Ve(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 Ii||null,prettyErrors:e}}c(Oi,"parseOptions");function ba(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Yn(t?.addNewLine),r=new Wn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(qt(s,t)),a.warnings.forEach(qt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(ba,"parseAllDocuments");function $i(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Yn(t?.addNewLine),r=new Wn(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 $e(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(qt(s,t)),o.warnings.forEach(qt(s,t))),o}c($i,"parseDocument");function Sa(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(Sa,"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 Te(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(Ca,"stringify");var ka=Object.freeze({__proto__:null,Alias:Tt,CST:ga,Composer:Wn,Document:Qe,Lexer:Ei,LineCounter:Ii,Pair:Q,Parser:Yn,Scalar:L,Schema:Xt,YAMLError:jn,YAMLMap:ne,YAMLParseError:$e,YAMLSeq:Ce,YAMLWarning:ui,isAlias:Se,isCollection:U,isDocument:Te,isMap:Re,isNode:q,isPair:j,isScalar:K,isSeq:Ke,parse:Sa,parseAllDocuments:ba,parseDocument:$i,stringify:Ca,visit:Ne,visitAsync:It});const Y={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},va={ignored:lo,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ea extends ms{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Et(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=pr.watch(this.membraneDir,va),this.watcher.on("add",e=>this.handleFileSystemEvent(Y.Added,e)).on("change",e=>this.handleFileSystemEvent(Y.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(Y.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(Y.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=R.relative(this.membraneDir,t);if(e===Y.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.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&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=R.relative(this.membraneDir,e);let i;try{i=t?ka.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 ar.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}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=R.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=R.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}class pt{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=ue}fileWatcher=void 0;notifier;changes=[];clear(){this.changes=[]}hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new Ea({cwd:process.cwd()}),this.fileWatcher.on(Y.Added,e=>this.handleLocalEvent(e,Y.Added)),this.fileWatcher.on(Y.Changed,e=>this.handleLocalEvent(e,Y.Changed)),this.fileWatcher.on(Y.Deleted,e=>this.handleLocalEvent(e,Y.Deleted)),await this.fileWatcher.start(),T.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(ro(e.filePath))switch(t){case Y.Added:case Y.Changed:await oo(e.filePath);break;case Y.Deleted:await ao(e.filePath);break}else{let n=G.fromPathAndData(e.filePath,e.data);if(!n){const r=G.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch(T.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case Y.Added:case Y.Changed:await i.putElement(n);break;case Y.Deleted:await i.deleteElement(n);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=pt.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=pt.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:X.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:X.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:X.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){if(!this.hasChanges())return;T.info("[resolver] Resolving changes..");const e=this.changes.filter(n=>n.element.type===P.Integration),t=this.changes.filter(n=>n.element.type!==P.Integration);await Promise.all(e.map(async n=>this.resolveChange(n))),await Promise.all(t.map(async n=>this.resolveChange(n))),T.success(`[resolver] Resolved ${this.changes.length} changes`)}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case X.DELETE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case X.CREATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case X.UPDATE:return T.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=pt.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)T.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);T.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 X.CREATE:return"ADD";case X.UPDATE:return"UPD";case X.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:X.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:X.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:X.UPDATE,element:e,direction:n,isConflict:!0}:null}}class Li{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=ue,this.local=new vs(new fo),this.remote=new vs(new ho),this.syncService=new pt(this.local,this.remote)}async reset(){this.local.cache.clear(),this.remote.cache.clear(),this.updateStats(),this.syncService.clear()}async push(e={}){await this.notifier.setState(D.PUSHING);try{await this.refreshElements()}catch(n){return T.error(`Failed to refresh elements: ${te(n)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return await this.notifier.setState(D.CONFLICTS);const t=await Zr();this.remote.setConnectorsMapping(t),await this.syncLocalAndRemoteWorkspaces(e)}async notifyRemote(){await this.notifier.connectToRemote()}async pull(e={}){await this.notifier.setState(D.PULLING);try{await this.refreshElements()}catch(t){return T.error(`Failed to refresh elements: ${te(t)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(D.CONFLICTS);await Xr({integrations:this.remote.cache.getElementsByType(P.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.syncLocalAndRemoteWorkspaces(e)}async syncLocalAndRemoteWorkspaces(e={}){await this.notifier.setState(D.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.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)}}new Li;const dt={Agent:"agent",Cli:"cli"};class Di{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifications=ue,this.workspaceService=new Li,this.mcpStatusService=new Hr,this.setupProcessCleanup()}initialized=!1;notifications;workspaceService;mcpStatusService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{return this.workspaceService.pull(e)}catch(t){throw T.error(`Failed to pull workspace: ${t}`),t}}async pushWorkspace(e={}){try{return this.workspaceService.push(e)}catch(t){throw T.error(`Failed to push workspace: ${t}`),t}}async syncWorkspaces(e={}){try{return this.workspaceService.syncLocalAndRemoteWorkspaces(e)}catch(t){throw T.error(`Failed to sync workspaces: ${t}`),t}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifications.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),Ze.isCacheDefined(this.currentConfig)?(await this.initServices(),this.initialized=!0,await this.notifications.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifications.setState(D.SETTING_UP))}catch(t){T.error(`Failed to initialize services: ${t}`),await this.notifications.setState(D.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ze.loadConfig(this.cwd),this.notifications.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const i=Ze.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===dt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===dt.Agent&&(await this.notifications.connectToRemote(),await this.mcpStatusService.start()),await this.workspaceService.reset()}async stopServices(){this.mode===dt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const xi=Gi(process.argv.slice(2)),Pi=xi.cwd?Ui(xi.cwd):process.cwd(),Ia=new Di(dt.Agent,Pi),Ta=c(()=>m(wt,{cwd:Pi,membraneCLIService:Ia,children:m(Gr,{})}),"App");function Na(){mt(m(Ta,{}))}c(Na,"runAgent");function Aa(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
|
|
141
|
-
`)).action(t=>{t.key&&t.secret?Ze.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):mt(
|
|
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=zt(e),n=Ve(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=zt(e),n=Ve(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 Ii||null,prettyErrors:e}}c(Oi,"parseOptions");function ba(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Yn(t?.addNewLine),r=new Wn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(qt(s,t)),a.warnings.forEach(qt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(ba,"parseAllDocuments");function $i(s,e={}){const{lineCounter:t,prettyErrors:n}=Oi(e),i=new Yn(t?.addNewLine),r=new Wn(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 $e(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(qt(s,t)),o.warnings.forEach(qt(s,t))),o}c($i,"parseDocument");function Sa(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(Sa,"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 Te(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(Ca,"stringify");var ka=Object.freeze({__proto__:null,Alias:Tt,CST:ga,Composer:Wn,Document:Qe,Lexer:Ei,LineCounter:Ii,Pair:Q,Parser:Yn,Scalar:L,Schema:Xt,YAMLError:jn,YAMLMap:ne,YAMLParseError:$e,YAMLSeq:Ce,YAMLWarning:ui,isAlias:Se,isCollection:U,isDocument:Te,isMap:Re,isNode:q,isPair:j,isScalar:K,isSeq:Ke,parse:Sa,parseAllDocuments:ba,parseDocument:$i,stringify:Ca,visit:Ne,visitAsync:It});const Y={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},va={ignored:lo,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ea extends ms{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Et(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(P.existsSync(this.membraneDir)||P.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=pr.watch(this.membraneDir,va),this.watcher.on("add",e=>this.handleFileSystemEvent(Y.Added,e)).on("change",e=>this.handleFileSystemEvent(Y.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(Y.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(Y.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=R.relative(this.membraneDir,t);if(e===Y.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.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&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return P.readFileSync(e,"utf8")}processFileEvent(e,t){const n=R.relative(this.membraneDir,e);let i;try{i=t?ka.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 ar.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){P.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=P.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=R.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=P.readFileSync(i,"utf8"),o=R.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}class pt{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=ue}fileWatcher=void 0;notifier;changes=[];clear(){this.changes=[]}hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new Ea({cwd:process.cwd()}),this.fileWatcher.on(Y.Added,e=>this.handleLocalEvent(e,Y.Added)),this.fileWatcher.on(Y.Changed,e=>this.handleLocalEvent(e,Y.Changed)),this.fileWatcher.on(Y.Deleted,e=>this.handleLocalEvent(e,Y.Deleted)),await this.fileWatcher.start(),T.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(ro(e.filePath))switch(t){case Y.Added:case Y.Changed:await oo(e.filePath);break;case Y.Deleted:await ao(e.filePath);break}else{let n=G.fromPathAndData(e.filePath,e.data);if(!n){const r=G.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch(T.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case Y.Added:case Y.Changed:await i.putElement(n);break;case Y.Deleted:await i.deleteElement(n);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=pt.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=pt.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:X.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:X.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:X.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){if(!this.hasChanges())return;T.info("[resolver] Resolving changes..");const e=this.changes.filter(r=>r.element.type===x.Integration),t=this.changes.filter(r=>r.element.type!==x.Integration),n=t.filter(r=>r.element.hasParent()),i=t.filter(r=>!r.element.hasParent());await Promise.all(e.map(async r=>this.resolveChange(r))),await Promise.all(i.map(async r=>this.resolveChange(r))),await Promise.all(n.map(async r=>this.resolveChange(r))),T.success(`[resolver] Resolved ${this.changes.length} changes`)}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case X.DELETE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case X.CREATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case X.UPDATE:return T.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=pt.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)T.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);T.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 X.CREATE:return"ADD";case X.UPDATE:return"UPD";case X.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:X.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:X.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:X.UPDATE,element:e,direction:n,isConflict:!0}:null}}class Li{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=ue,this.local=new vs(new fo),this.remote=new vs(new ho),this.syncService=new pt(this.local,this.remote)}async reset(){this.local.cache.clear(),this.remote.cache.clear(),this.updateStats(),this.syncService.clear()}async push(e={}){await this.notifier.setState(D.PUSHING);try{await this.refreshElements()}catch(n){return T.error(`Failed to refresh elements: ${te(n)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return await this.notifier.setState(D.CONFLICTS);const t=await Zr();this.remote.setConnectorsMapping(t),await this.syncLocalAndRemoteWorkspaces(e)}async notifyRemote(){await this.notifier.connectToRemote()}async pull(e={}){await this.notifier.setState(D.PULLING);try{await this.refreshElements()}catch(t){return T.error(`Failed to refresh elements: ${te(t)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(D.CONFLICTS);await Xr({integrations:this.remote.cache.getElementsByType(x.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.syncLocalAndRemoteWorkspaces(e)}async syncLocalAndRemoteWorkspaces(e={}){await this.notifier.setState(D.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.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)}}new Li;const dt={Agent:"agent",Cli:"cli"};class Di{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifications=ue,this.workspaceService=new Li,this.mcpStatusService=new Hr,this.setupProcessCleanup()}initialized=!1;notifications;workspaceService;mcpStatusService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{return this.workspaceService.pull(e)}catch(t){throw T.error(`Failed to pull workspace: ${t}`),t}}async pushWorkspace(e={}){try{return this.workspaceService.push(e)}catch(t){throw T.error(`Failed to push workspace: ${t}`),t}}async syncWorkspaces(e={}){try{return this.workspaceService.syncLocalAndRemoteWorkspaces(e)}catch(t){throw T.error(`Failed to sync workspaces: ${t}`),t}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifications.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),Ze.isCacheDefined(this.currentConfig)?(await this.initServices(),this.initialized=!0,await this.notifications.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifications.setState(D.SETTING_UP))}catch(t){T.error(`Failed to initialize services: ${t}`),await this.notifications.setState(D.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ze.loadConfig(this.cwd),this.notifications.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const i=Ze.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===dt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===dt.Agent&&(await this.notifications.connectToRemote(),await this.mcpStatusService.start()),await this.workspaceService.reset()}async stopServices(){this.mode===dt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Pi=Gi(process.argv.slice(2)),xi=Pi.cwd?Ui(Pi.cwd):process.cwd(),Ia=new Di(dt.Agent,xi),Ta=c(()=>m(wt,{cwd:xi,membraneCLIService:Ia,children:m(Gr,{})}),"App");function Na(){mt(m(Ta,{}))}c(Na,"runAgent");function Aa(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
|
|
141
|
+
`)).action(t=>{t.key&&t.secret?Ze.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(bs,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Aa,"setupInitCommand");async function Mi(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return sn.sign(t,e)}c(Mi,"generateAdminAccessToken");async function Oa(s,e){return(await rn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Oa,"fetchOpenApiSchema");function Ri(s,e=!0){if(!s)return e?z.string():z.string().optional();let t;switch(s.type){case"integer":t=z.coerce.number().int();break;case"number":t=z.coerce.number();break;case"boolean":t=z.coerce.boolean();break;case"string":default:t=z.string();break}return s.format==="uuid"?t=z.string().uuid():s.format==="email"?t=z.string().email():s.format==="date"?t=z.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=z.string().datetime()),s.enum&&(t=z.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(Ri,"convertOpenApiSchemaToZod");function Ki(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Ki,"extractPathParameters");function $a(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 h of s.parameters)if(h.in==="path")u[h.name]=Ri(h.schema,!0).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const g=h.required===!0;p[h.name]=Ri(h.schema,g).describe(h.description||`Query parameter: ${h.name}`)}}Object.keys(u).length>0&&(l.params=z.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=z.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=z.any().describe("Request body"));const d=Object.keys(l).length>0?z.object(l):z.object({});return{name:o,description:a,parameters:d,async execute(h){try{const g=Ki(e);if(g.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const I=g.filter(O=>!(O in h.params));if(I.length>0)throw new Error(`Missing required path parameters: ${I.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[I,O]of Object.entries(h.params)){const $=`{${I}}`;w.includes($)&&(w=w.replace($,String(O)))}const f=Ki(w);if(f.length>0)throw new Error(`Unresolved path parameters: ${f.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[I,O]of Object.entries(h.query))O!=null&&y.append(I,String(O));y.toString()&&(w+=`?${y.toString()}`);const C=await Mi(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};h.body&&t.toLowerCase()!=="get"&&(v.data=h.body);const A=await rn.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return rn.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($a,"createApiTool");function La(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=$a(l,r,a,e,t,n);i.push(u)}}return i}c(La,"convertOpenApiToTools");function Da(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
|
|
142
142
|
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=bt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||an,n=await Mi(e.workspaceKey,e.workspaceSecret),i=await Oa(t,n),r=La(i,t,e.workspaceKey,e.workspaceSecret),o=new yr({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.
|
|
144
|
-
`,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>(Yr(process.pid,process.cwd()),p(d)),o.addTool(u)}mn({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{mn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),tt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{tt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Da,"setupMcpCommand");const
|
|
144
|
+
`,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>(Yr(process.pid,process.cwd()),p(d)),o.addTool(u)}mn({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{mn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),tt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{tt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Da,"setupMcpCommand");const Pa={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},xa={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class W{static{c(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=Pa[t],l=xa[t];return`${i}${a} ${r}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
145
145
|
${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
|
|
146
146
|
${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),i=e.map(r=>{const o={};return n.forEach(a=>{o[a]=r[a]}),o});console.table(i,n)}static divider(){}}function Ma(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
|
|
147
147
|
`)).action(async()=>{try{W.header("Opening Workspace in Browser"),W.info("Loading configuration...");const e=bt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");W.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await gs(process.cwd())}`;W.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),W.success("Browser opened successfully")}catch(e){e instanceof Error&&(W.error(e.message),process.exit(1)),W.error("An unknown error occurred"),process.exit(1)}})}c(Ma,"setupOpenCommand");function Ra(s){return m(un,{children:m(Ka,{options:s})})}c(Ra,"Pull");function Ka({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=oe();Ee(()=>{i(s)},[]);const r=t===D.CONFLICTS;return E(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:St(o.type),children:o.message},o.timestamp+a)),r&&E(Zt,{children:[E(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(pn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(hn,{})]})}c(Ka,"PullActivity");function _i(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(_i,"getWatchModeCallback");function _a(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
|
|
148
|
-
`)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(
|
|
149
|
-
`)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(
|
|
148
|
+
`)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(Ra,{force:t.force,watch:t.watch,allConnectors:t.allConnectors,onComplete:n})}))})}c(_a,"setupPullCommand");function ja(s){return m(un,{children:m(Fa,{options:s})})}c(ja,"Push");function Fa({options:s}){const{logs:e,state:t,conflicts:n,push:i}=oe();Ee(()=>{i(s)},[]);const r=t===D.CONFLICTS;return E(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:St(o.type),children:o.message},o.timestamp+a)),r&&E(Zt,{children:[E(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(pn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(hn,{})]})}c(Fa,"PushActivity");function Ba(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
|
|
149
|
+
`)).action(async t=>{const n=t.watch?_i():()=>process.exit(0);mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(ja,{force:t.force,watch:t.watch,onComplete:n})}))})}c(Ba,"setupPushCommand");class Ua{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=cn(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const qa="claude-sonnet-4-20250514";class es{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=bt();if(!i)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new os({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new wr({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:qa,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new es({client:r,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),on(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId,e);if(M.existsSync(t))return Ie.load(M.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=B.join(this.testsDir,this.testBasePath,this.connectionId,e);M.mkdirSync(B.dirname(n),{recursive:!0}),M.writeFileSync(n,Ie.dump(t,{noRefs:!0}))}writeResults(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId);M.mkdirSync(t,{recursive:!0});const n=B.join(t,"test-results.yaml");M.writeFileSync(n,Ie.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return sn.sign(n,e.workspaceSecret,i)}}Sr.interpolate=/{{([\s\S]+?)}}/g;function zn(s,e){if(typeof s=="string"){const t=br(s),n={state:e,random:{number:c(()=>Xe.number.int(),"number"),alphaNumeric:c(r=>Xe.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:c(()=>Xe.company.name(),"name"),catchPhrase:c(()=>Xe.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Xe.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(s)?s.map(t=>zn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,zn(n,e)])):s}c(zn,"processNode");function Ja(s,e){return zn(s,e)}c(Ja,"handleTemplate");class Wa{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.yellow(e.path)}`);let t=!1,n=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Ja(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),en(this.result,e.path,i)}catch(l){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}en(this.result,e.path,{error:te(l)}),t=!0,i={error:te(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),on(this.result,e.getResult())}}class ve{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(k.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(i){this.assertions.push({message:t,result:!1,details:te(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Qn(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!Xn(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=Qn(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Xn(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(Qn,"getNotMatchingSubFields");function Xn(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}c(Xn,"softCompare");class Ga extends ve{static{c(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=tn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=as(n),a=gt(e.input.fields,o,{skipUnknownFields:!0}),l=gt(r.record.fields,o),u=Qn(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=tr(n);if(i.length>0){const r={};i.forEach(a=>{const l=nr(e.input.fields,a);typeof l<"u"&&en(r,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=tn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=te(t),i=tn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
|
|
150
150
|
|
|
151
151
|
${JSON.stringify(i,null,2)}
|
|
152
152
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@membranehq/cli",
|
|
3
|
-
"version": "0.10.
|
|
3
|
+
"version": "0.10.8",
|
|
4
4
|
"keywords": [
|
|
5
5
|
"cli",
|
|
6
6
|
"integration",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"@buildwithlayer/openapi-to-tools": "^1.3.3",
|
|
34
34
|
"@faker-js/faker": "^9.8.0",
|
|
35
35
|
"@inkjs/ui": "^2.0.0",
|
|
36
|
-
"@membranehq/sdk": "^0.7.
|
|
36
|
+
"@membranehq/sdk": "^0.7.4",
|
|
37
37
|
"@types/jsonwebtoken": "^9.0.10",
|
|
38
38
|
"archiver": "^7.0.1",
|
|
39
39
|
"axios": "^1.10.0",
|