@membranehq/cli 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1 -1
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -138,7 +138,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
138
138
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
139
139
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const 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 c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(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(cr(t.key)&&!ke(t.sep,"newline")){const o=rt(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=rt(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=fn(n),r=rt(i);lr(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(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=fn(e),n=rt(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=fn(e),n=rt(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 ur(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new or||null,prettyErrors:e}}l(ur,"parseOptions");function Qa(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(sn(s,t)),a.warnings.forEach(sn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Qa,"parseAllDocuments");function fr(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(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 xe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(sn(s,t)),o.warnings.forEach(sn(s,t))),o}l(fr,"parseDocument");function Xa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=fr(s,t);if(!i)return null;if(i.warnings.forEach(r=>vi(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))}l(Xa,"parse");function ec(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 $e(s)&&!n?s.toString(t):new lt(s,n,t).toString(t)}l(ec,"stringify");var tc=Object.freeze({__proto__:null,Alias:Ft,CST:Ha,Composer:ts,Document:lt,Lexer:rr,LineCounter:or,Pair:Q,Parser:rs,Scalar:D,Schema:yn,YAMLError:Hn,YAMLMap:se,YAMLParseError:xe,YAMLSeq:ve,YAMLWarning:Wi,isAlias:Ce,isCollection:J,isDocument:$e,isMap:ze,isNode:W,isPair:U,isScalar:q,isSeq:He,parse:Xa,parseAllDocuments:Qa,parseDocument:fr,stringify:ec,visit:Le,visitAsync:Kt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},nc={ignored:Po,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 sc extends Nn{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Ve(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Xr.watch(this.membraneDir,nc),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.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.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=j.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=j.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=j.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=j.relative(this.membraneDir,e);let i;try{i=t?tc.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Zr.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=j.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=j.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var os=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(os||{});const ic={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class rc extends Nn{static{l(this,"RemoteElementWatcher")}constructor(e=ic){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new eo(n),this.setupEventSourceHandlers()}catch(e){b.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.info("[remote-watcher] Connected to workspace events"),this.reconnectAttempts=0,this.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Br.ElementUpdate)return;const{elementId:t,elementType:n,data:i={}}=e;if(!(!t||!n)){if(n===_.Connector){const{filePath:r,eventType:o,newPath:a}=i;return b.info(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${r}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,r,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleConnectorFileUpdate(e,t,n,i){const r=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(r);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(r),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:i})},this.config.debounceMs);this.debounceTimeouts.set(r,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&b.error("[remote-watcher] Max reconnect attempts reached, giving up");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);b.info(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class dr{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=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),e.data?.id&&this.internalIdIndex.set(e.data.id,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)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}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(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function oc(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await K.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>as("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];b.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await K.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>as(n,a))),i.integrationSpecific)for(const a of t){const c=await K.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,as(n,u))))}r.length>0&&s=="full"&&(console.table(r.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,c)=>(a||(a={}),a[c.key]||(a[c.key]={}),c.universal&&(a[c.key].universal=!0),c.integrationKey&&(a[c.key].integration?a[c.key].integration+=` ${c.integrationKey}`:a[c.key].integration=c.integrationKey),a),{})),console.groupEnd()),e[n]=r}return b.success("[connectors] Remote workspace data retrieved successfully"),e}l(oc,"getWorkspaceData");function as(s,e){return e=Lo(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(as,"cleanUpForExport");const Ct="connectors",ye="development",cs={};async function ac({integrations:s,allConnectors:e=!1}){const t=Mo(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(!i[o]?.has(r.connectorVersion)){const c=await hr({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){b.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await dc({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await hc({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(ac,"pullConnectors");async function cc(){const s=await oc("minified"),t=(await K.withClient(c=>c.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const i=await K.withClient(c=>c.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=i;const r=Te(),a=(P.existsSync(r)?P.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=M.join(r,c);try{return P.statSync(u).isDirectory()}catch{return!1}});for(const c of a){b.info(`[connectors] Loading connector from: ${c}`);const u=P.readdirSync(M.join(r,c)),f=await ls(c);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await hr({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await K.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const d=u.filter(p=>P.statSync(M.join(r,c,p)).isDirectory());for(const p of d)await fc({connector:f,version:p,connectorId:n[f.id]})}return n}l(cc,"pushConnectors");function Te(){const s=Ln();return M.join(s.membraneDirPath,Ct)}l(Te,"getConnectorsPath");async function ls(s){const e=M.join(Te(),s,`${s}.yml`);if(P.existsSync(e))return Ne.load(P.readFileSync(e,"utf8"))}l(ls,"readConnector");async function lc(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=P.createWriteStream(e),r=to("zip",{zlib:{level:9}});i.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{b.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=P.readdirSync(s);for(const a of o){const c=M.join(s,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(lc,"createZipArchive");async function uc(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=so.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=M.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=M.join(e,o),u=M.dirname(c);P.mkdirSync(u,{recursive:!0});const f=P.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(uc,"extractZipArchive");async function fc({connector:s,version:e,connectorId:t}){const n=M.join(Te(),Ee(s),pr(e)),i=M.join(n,"src"),r=M.join(n,"src.zip"),o=P.existsSync(r);if(P.existsSync(i)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await lc(i,r)),!P.existsSync(r)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new no;if(a.append("file",P.createReadStream(r),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ye)b.info(`[connectors] Uploading connector ${t}`),await K.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&P.existsSync(r)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),P.unlinkSync(r))}}l(fc,"pushConnectorVersion");async function hr({connectorId:s}){if(cs[s])return cs[s];const e=await K.withClient(t=>t.get(`connectors/${s}`));return cs[s]=e,e}l(hr,"getConnector");async function dc({basePath:s,connector:e}){const t=Ee(e),n=M.join(s,Ct,t);P.mkdirSync(n,{recursive:!0});const i=M.join(n,`${Ee(e)}.yml`);P.writeFileSync(i,Ne.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}l(dc,"pullConnector");async function hc({connector:s,connectorVersion:e,basePath:t}){const n=Ee(s),i=pr(e),r=M.join(t,"connectors",n,i),o=await K.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(r,{recursive:!0});const a=M.join(r,"src.zip");if(P.writeFileSync(a,o),!e){const c=M.join(r,"src");P.mkdirSync(c,{recursive:!0}),await uc(o,c)}b.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(hc,"pullConnectorVersion");function Ee(s){return s.key}l(Ee,"getConnectorDirName");function pr(s){return s??ye}l(pr,"getConnectorVersionDirName");function pc(s){return s.match(`${Ct}/[^/]+/${ye}/src/.*`)!==null}l(pc,"isConnectorSourceFile");async function mc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=P.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(mc,"putConnectorFile");async function gc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await K.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(gc,"deleteConnectorFile");async function yc(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),i=Ee(t),r=M.join(Te(),i,ye,"src",e);P.mkdirSync(M.dirname(r),{recursive:!0}),n!=null?(P.writeFileSync(r,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(r)&&(P.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}l(yc,"pullConnectorFile");async function wc(s,e){const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);P.existsSync(i)&&(P.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(wc,"deleteLocalConnectorFile");async function bc(s,e,t){if(t&&e!==t)try{const n=await K.withClient(c=>c.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const i=Ee(n),r=M.join(Te(),i,ye,"src"),o=M.join(r,e),a=M.join(r,t);P.existsSync(o)&&(P.mkdirSync(M.dirname(a),{recursive:!0}),P.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${i}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}l(bc,"renameLocalConnectorDirectory");async function Sc(s,e){try{const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);if(P.existsSync(i)){const r=M.resolve(Te());if(!M.resolve(i).startsWith(r))return;P.rmSync(i,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}l(Sc,"deleteLocalConnectorDirectory");const mr=[_.DataSource,_.FieldMapping,_.Action,_.Flow];class Et{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new dr,this.remoteCache=new dr,this.localRepo=new Wo(this.localCache),this.remoteRepo=new Vo(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw b.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw b.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await ac({integrations:this.remoteCache.getElementsByType(_.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await cc();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ee.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ee.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new sc({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ie.Updated,e=>this.handleLocalEvent(e,ie.Updated)),this.localWatcher.on(ie.Deleted,e=>this.handleLocalEvent(e,ie.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new rc,this.remoteWatcher.on(os.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(os.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:i})=>this.handleRemoteConnectorFileEvent(e,t,n,i)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,i){try{switch(n){case Sn.ConnectorFileDeleted:await wc(e,t);break;case Sn.ConnectorDirectoryRenamed:await bc(e,t,i);break;case Sn.ConnectorDirectoryDeleted:await Sc(e,t);break;default:await yc(e,t);break}}catch(r){b.error(`[sync] Error handling remote connector file event: ${r}`)}}async handleLocalEvent(e,t){try{if(pc(e.filePath))switch(t){case ie.Updated:await mc(e.filePath);break;case ie.Deleted:await gc(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const i=z.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(b.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${$o.toSentenceCase(t)}: ${n.id}`),t){case ie.Updated:await this.updateElement(n,ee.OUTGOING);break;case ie.Deleted:await this.deleteElement(n,ee.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Et.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Et.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(i=>i.element.type===_.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ee.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==_.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(i=>!i.element.hasParent());for(const i of mr){const r=t.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(i=>i.element.hasParent());for(const i of mr){const r=n.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case he.DELETE:return this.deleteElement(e.element,e.direction);case he.CREATE:return this.updateElement(e.element,e.direction);case he.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),d=Et.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:he.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:he.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:he.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ie=j.join(io.tmpdir(),"membrane-mcp-status"),gr=3e4;class Cc{static{l(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=dn(void 0,e),n=yr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function dn(s,e){try{const t=e||process.cwd();if(!s){const i=yr(t);return i.length===0?null:i[0]}const n=ds(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>gr)return vt(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>gr)return vt(s,t),null}return c}}catch{s&&e&&vt(s,e)}return null}l(dn,"getMcpStatus");function yr(s){try{const e=s||process.cwd(),t=fs(e);if(!x.existsSync(Ie))return[];const n=x.readdirSync(Ie),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=dn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yr,"getAllMcpStatusFiles");function us(s){try{const t={...dn(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(Ie)||x.mkdirSync(Ie,{recursive:!0});const n=ds(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(us,"updateMcpStatus");function vt(s,e){try{const t=e||process.cwd();if(s){const n=ds(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=fs(t);if(x.existsSync(Ie)){const i=x.readdirSync(Ie);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(j.join(Ie,r))}}}catch{}}l(vt,"clearMcpStatus");function vc(s,e){const t=dn(s,e);t&&us({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(vc,"trackToolExecution");function fs(s){return Qr("md5").update(s).digest("hex").slice(0,8)}l(fs,"getCwdHash");function ds(s,e){const t=fs(e);return j.join(Ie,`mcp-${t}-${s}.json`)}l(ds,"getStatusFilePath");const kt={Agent:"agent",Cli:"cli"},L={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"};class wr{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=pe,this.mcpStatusService=new Cc,this.syncService=new Et,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=ft.loadConfig(this.cwd),this.notifier.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=ft.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===kt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===kt.Agent&&(await this.notifier.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 br=Es(null);function kc({children:s,membraneCLIService:e}){const{data:t}=Os("/account"),[n,i]=B(L.NOT_INITIALIZED),[r,o]=B([]),[a,c]=B({}),[u,f]=B([]),[d,p]=B(null),w=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ae(()=>{const h=l(({state:O})=>i(O),"handleStateChanged"),y=l(({stats:O})=>c(O),"handleStatsChanged"),v=l(({log:O})=>f(N=>[...N,O]),"handleLogAdded"),k=l(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=l(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(V.StateChanged,h),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,v),e.notifier.on(V.ConflictsChanged,k),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,h),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,v),e.notifier.off(V.ConflictsChanged,k),e.notifier.off(V.ConfigChanged,A)}},[]),m(br.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:l(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:l(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:l(h=>e.pullWorkspace(h),"pull"),push:l(h=>e.pushWorkspace(h),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(kc,"MembraneCLIServiceProvider");function le(){const s=Is(br);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const Sr=Es(process.cwd());function Tc({cwd:s,children:e}){return m(Sr.Provider,{value:s,children:e})}l(Tc,"CwdProvider");function Ec(){return Is(Sr)}l(Ec,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Tc,{cwd:n,children:m(Mr,{value:{fetcher:Fo()},children:m(kc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const hs=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=j.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:l(()=>{const s=j.join(process.cwd(),".cursor"),e=j.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 Ic({onExit:s,onComplete:e}){const[t,n]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[f,d]=B("");Me((w,h)=>{if(c||f){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?p(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(hs.length-1,t+1));else if(h.return||w===" "){const y=hs[t];a(y),r(!0)}});const p=l(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"green",children:"Success"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"green",children:c}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(C,{color:"red",children:f})}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Confirmation"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",m(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(C,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:E(C,{children:[m(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Select Agent"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:hs.map((w,h)=>E(S,{children:[E(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),E(C,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(Ic,"AddMcpServerScreen");function Oc(){const[s,e]=B(null),[t,n]=B([]),[i,r]=B(null);return Ae(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.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}}l(Oc,"useMcpStatus");function Ac(){const{error:s,serverCount:e,allMcpServers:t}=Oc(),n=Math.min(100,process.stdout.columns||100);return E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(C,{color:"red",children:"error reading status"}):e===0?m(C,{color:"yellow",children:"none"}):m(C,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",m(Rr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(S,{children:E(C,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(Ac,"Agent");const pn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Cr(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(Cr,"truncateText");function ps({children:s}){const{state:e,logs:t}=le();return!e||e===L.NOT_INITIALIZED?E(S,{gap:1,flexDirection:"row",children:[m(oo,{type:"dots"}),m(C,{children:"Initializing..."})]}):e===L.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===L.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,i)=>m(C,{color:pn(n.type),children:n.message},n.timestamp+i))}):s}l(ps,"EnsureInitialized");function vr({onExit:s,showEscOption:e=!0}){const[t,n]=B(""),{data:i,error:r,isLoading:o}=Os("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(Me((h,y)=>{y.escape&&s?.()}),u)return E(S,{children:[m(At,{}),m(C,{children:" Fetching workspaces..."})]});if(r)return E(S,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",r.message]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,g=c?.length??0;async function w(h){const y=f.find(A=>A.id===h);if(!y)return;const{key:v,secret:k}=y;!v||!k||(await a({workspaceKey:v,workspaceSecret:k}),s?.())}return l(w,"handleSelect"),E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(S,{marginTop:1,children:[m(C,{children:"Search: "}),m(ao,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(C,{children:["Showing ",p," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(co,{options:d,onChange:l(h=>{h&&w(h)},"onChange")})}),e&&m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]})}l(vr,"SelectWorkspace");function Nc({currentPat:s,onSubmit:e}){const[t,n]=B(""),[i,r]=B(!1),[o,a]=B(null);return E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(C,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(lo,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(S,{marginTop:1,children:E(C,{children:[m(At,{type:"dots"})," Validating token..."]})}),o&&m(C,{color:"red",children:o})]})}l(Nc,"PersonalAccessTokenInput");var Tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Tt||{});const $c={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},ms=[Tt.Authenticate,Tt.ConnectWorkspace];function kr({onComplete:s}){const{config:e}=le(),[t,n]=B(!1),[i,r]=B(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=si(),c=ms[i],u=i+1,f=ms.length,d=ms.map((w,h)=>{let y="pending";return h<i?y="done":h===i&&(y="current"),{id:w,label:$c[w],status:y}});async function p(w){const h=a&&w===""?a:w,y=new ii;try{await y.request("/account",{headers:{Authorization:`Bearer ${h}`}}),Ko(h),r(v=>v+1)}catch(v){console.error(v)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),Me((w,h)=>{o&&h.escape&&s&&s()}),t?m(S,{children:m(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(C,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Lc,{status:w.status,label:w.label},w.id))})]}),c===Tt.Authenticate&&m(Nc,{currentPat:a,onSubmit:p}),c===Tt.ConnectWorkspace&&m(vr,{onExit:g,showEscOption:!1})]})}l(kr,"Setup");function Lc({status:s,label:e}){return E(S,{children:[E(S,{width:2,children:[s==="current"&&m(At,{type:"dots"}),s==="done"&&m(C,{children:"\u2705"})]}),m(C,{dimColor:s!=="current",children:e})]})}l(Lc,"StepDisplay");function gs(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(C,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(S,{children:[m(S,{width:20,children:E(C,{children:[t,":"]})}),m(C,{color:"green",children:n})]},t))})]})}l(gs,"ElementStats");const ys=5,Dc=6;function Pc(){const{logs:s}=le(),[e,t]=B(0),n=Math.min(100,process.stdout.columns||100),i=ys,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-Dc,u=e<s.length-i,f=e>0;return Me((d,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(S,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>ys&&m(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>m(S,{marginLeft:1,children:m(C,{color:pn(d.type),children:Cr(d.message,c)})},d.timestamp+p)),s.length>ys&&E(S,{marginLeft:1,flexDirection:"row",children:[u&&m(C,{color:"grey",children:"\u2191 "}),f&&m(C,{color:"grey",children:"\u2193 "})]})]})}l(Pc,"Logs");const mn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function xc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=B(0),[r,o]=B(!1),[a,c]=B(!1);return Me((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(d=>d>0?d-1:mn.length-1):f.downArrow?i(d=>d<mn.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),mn[n].value==="sync"?e({watch:!0}):t())}}),Ae(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),E(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(ws,{isExpanded:a})}),E(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(C,{color:"white",bold:!0,children:"What would you like to do?"}),m(C,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:r?E(S,{flexDirection:"row",gap:1,children:[m(At,{type:"dots"}),m(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:mn.map((u,f)=>m(S,{flexDirection:"column",children:E(S,{flexDirection:"row",gap:1,children:[m(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(xc,"ResolveChangesUI");const Rc={[he.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[he.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[he.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ws({isExpanded:s}){const{conflicts:e}=le(),t=5,n=jr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(S,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=Rc[o][a];return E(S,{flexDirection:"column",children:[E(S,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[c.label," (",r.length,")"]}),m(C,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(S,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(S,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(S,{marginLeft:2,children:m(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ws,"Conflicts");function _c(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?Cr(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ae(()=>{i({watch:!0})},[]),E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:E(S,{flexDirection:"row",gap:1,children:[m(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:jc(e),children:[" [",Mc(e),"] "]})]})}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Local:"})}),m(C,{color:"grey",children:process.cwd()})]}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[m(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(xc,{}):E(wn,{children:[m(S,{paddingTop:1,children:m(gs,{})}),t.length>0&&m(Pc,{})]})]})}l(_c,"Workspace");function Mc(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}l(Mc,"getStatusDisplay");function jc(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}l(jc,"getStatusColor");const Kc="https://console.integration.app/w";function Fc(){const s=Ec(),e=Kr(!0),{exit:t,state:n}=le(),[i,r]=B(null),o=i??(n===L.SETTING_UP?"setup":"main");Me(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===L.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ri(s),u=`${Kc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ro(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ae(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(vr,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Ic,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(kr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(ps,{children:E(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Ac,{})}),m(_c,{}),m(S,{paddingLeft:2,children:m(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(Fc,"Main");const Tr=_r(process.argv.slice(2)),Er=Tr.cwd?Pr(Tr.cwd):process.cwd(),qc=new wr(kt.Agent,Er),Bc=l(()=>m(hn,{cwd:Er,membraneCLIService:qc,children:m(Fc,{})}),"App");function Uc(){It(m(Bc,{}))}l(Uc,"runAgent");function Jc(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
+ `,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=fn(e),n=rt(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=fn(e),n=rt(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 ur(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new or||null,prettyErrors:e}}l(ur,"parseOptions");function Qa(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(sn(s,t)),a.warnings.forEach(sn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Qa,"parseAllDocuments");function fr(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(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 xe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(sn(s,t)),o.warnings.forEach(sn(s,t))),o}l(fr,"parseDocument");function Xa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=fr(s,t);if(!i)return null;if(i.warnings.forEach(r=>vi(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))}l(Xa,"parse");function ec(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 $e(s)&&!n?s.toString(t):new lt(s,n,t).toString(t)}l(ec,"stringify");var tc=Object.freeze({__proto__:null,Alias:Ft,CST:Ha,Composer:ts,Document:lt,Lexer:rr,LineCounter:or,Pair:Q,Parser:rs,Scalar:D,Schema:yn,YAMLError:Hn,YAMLMap:se,YAMLParseError:xe,YAMLSeq:ve,YAMLWarning:Wi,isAlias:Ce,isCollection:J,isDocument:$e,isMap:ze,isNode:W,isPair:U,isScalar:q,isSeq:He,parse:Xa,parseAllDocuments:Qa,parseDocument:fr,stringify:ec,visit:Le,visitAsync:Kt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},nc={ignored:Po,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 sc extends Nn{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Ve(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Xr.watch(this.membraneDir,nc),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.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.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=j.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=j.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=j.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=j.relative(this.membraneDir,e);let i;try{i=t?tc.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Zr.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=j.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=j.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var os=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(os||{});const ic={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class rc extends Nn{static{l(this,"RemoteElementWatcher")}constructor(e=ic){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new eo(n),this.setupEventSourceHandlers()}catch(e){b.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.info("[remote-watcher] Connected to workspace events"),this.reconnectAttempts=0,this.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Br.ElementUpdate)return;const{elementId:t,elementType:n,data:i={}}=e;if(!(!t||!n)){if(n===_.Connector){const{filePath:r,eventType:o,newPath:a}=i;return b.info(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${r}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,r,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleConnectorFileUpdate(e,t,n,i){const r=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(r);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(r),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:i})},this.config.debounceMs);this.debounceTimeouts.set(r,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&b.error("[remote-watcher] Max reconnect attempts reached, giving up");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);b.info(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class dr{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=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),e.data?.id&&this.internalIdIndex.set(e.data.id,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)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}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(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function oc(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await K.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>as("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];b.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await K.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>as(n,a))),i.integrationSpecific)for(const a of t){const c=await K.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,as(n,u))))}r.length>0&&s=="full"&&(console.table(r.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,c)=>(a||(a={}),a[c.key]||(a[c.key]={}),c.universal&&(a[c.key].universal=!0),c.integrationKey&&(a[c.key].integration?a[c.key].integration+=` ${c.integrationKey}`:a[c.key].integration=c.integrationKey),a),{})),console.groupEnd()),e[n]=r}return b.success("[connectors] Remote workspace data retrieved successfully"),e}l(oc,"getWorkspaceData");function as(s,e){return e=Lo(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(as,"cleanUpForExport");const Ct="connectors",ye="development",cs={};async function ac({integrations:s,allConnectors:e=!1}){const t=Mo(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(o&&!i[o]?.has(r.connectorVersion)){const c=await hr({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){b.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await dc({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await hc({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(ac,"pullConnectors");async function cc(){const s=await oc("minified"),t=(await K.withClient(c=>c.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const i=await K.withClient(c=>c.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=i;const r=Te(),a=(P.existsSync(r)?P.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=M.join(r,c);try{return P.statSync(u).isDirectory()}catch{return!1}});for(const c of a){b.info(`[connectors] Loading connector from: ${c}`);const u=P.readdirSync(M.join(r,c)),f=await ls(c);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await hr({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await K.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const d=u.filter(p=>P.statSync(M.join(r,c,p)).isDirectory());for(const p of d)await fc({connector:f,version:p,connectorId:n[f.id]})}return n}l(cc,"pushConnectors");function Te(){const s=Ln();return M.join(s.membraneDirPath,Ct)}l(Te,"getConnectorsPath");async function ls(s){const e=M.join(Te(),s,`${s}.yml`);if(P.existsSync(e))return Ne.load(P.readFileSync(e,"utf8"))}l(ls,"readConnector");async function lc(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=P.createWriteStream(e),r=to("zip",{zlib:{level:9}});i.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{b.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=P.readdirSync(s);for(const a of o){const c=M.join(s,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(lc,"createZipArchive");async function uc(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=so.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=M.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=M.join(e,o),u=M.dirname(c);P.mkdirSync(u,{recursive:!0});const f=P.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(uc,"extractZipArchive");async function fc({connector:s,version:e,connectorId:t}){const n=M.join(Te(),Ee(s),pr(e)),i=M.join(n,"src"),r=M.join(n,"src.zip"),o=P.existsSync(r);if(P.existsSync(i)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await lc(i,r)),!P.existsSync(r)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new no;if(a.append("file",P.createReadStream(r),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ye)b.info(`[connectors] Uploading connector ${t}`),await K.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&P.existsSync(r)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),P.unlinkSync(r))}}l(fc,"pushConnectorVersion");async function hr({connectorId:s}){if(cs[s])return cs[s];const e=await K.withClient(t=>t.get(`connectors/${s}`));return cs[s]=e,e}l(hr,"getConnector");async function dc({basePath:s,connector:e}){const t=Ee(e),n=M.join(s,Ct,t);P.mkdirSync(n,{recursive:!0});const i=M.join(n,`${Ee(e)}.yml`);P.writeFileSync(i,Ne.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}l(dc,"pullConnector");async function hc({connector:s,connectorVersion:e,basePath:t}){const n=Ee(s),i=pr(e),r=M.join(t,"connectors",n,i),o=await K.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(r,{recursive:!0});const a=M.join(r,"src.zip");if(P.writeFileSync(a,o),!e){const c=M.join(r,"src");P.mkdirSync(c,{recursive:!0}),await uc(o,c)}b.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(hc,"pullConnectorVersion");function Ee(s){return s.key}l(Ee,"getConnectorDirName");function pr(s){return s??ye}l(pr,"getConnectorVersionDirName");function pc(s){return s.match(`${Ct}/[^/]+/${ye}/src/.*`)!==null}l(pc,"isConnectorSourceFile");async function mc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=P.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(mc,"putConnectorFile");async function gc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await K.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(gc,"deleteConnectorFile");async function yc(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),i=Ee(t),r=M.join(Te(),i,ye,"src",e);P.mkdirSync(M.dirname(r),{recursive:!0}),n!=null?(P.writeFileSync(r,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(r)&&(P.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}l(yc,"pullConnectorFile");async function wc(s,e){const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);P.existsSync(i)&&(P.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(wc,"deleteLocalConnectorFile");async function bc(s,e,t){if(t&&e!==t)try{const n=await K.withClient(c=>c.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const i=Ee(n),r=M.join(Te(),i,ye,"src"),o=M.join(r,e),a=M.join(r,t);P.existsSync(o)&&(P.mkdirSync(M.dirname(a),{recursive:!0}),P.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${i}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}l(bc,"renameLocalConnectorDirectory");async function Sc(s,e){try{const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);if(P.existsSync(i)){const r=M.resolve(Te());if(!M.resolve(i).startsWith(r))return;P.rmSync(i,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}l(Sc,"deleteLocalConnectorDirectory");const mr=[_.DataSource,_.FieldMapping,_.Action,_.Flow];class Et{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new dr,this.remoteCache=new dr,this.localRepo=new Wo(this.localCache),this.remoteRepo=new Vo(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw b.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw b.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await ac({integrations:this.remoteCache.getElementsByType(_.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await cc();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ee.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ee.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new sc({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ie.Updated,e=>this.handleLocalEvent(e,ie.Updated)),this.localWatcher.on(ie.Deleted,e=>this.handleLocalEvent(e,ie.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new rc,this.remoteWatcher.on(os.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(os.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:i})=>this.handleRemoteConnectorFileEvent(e,t,n,i)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,i){try{switch(n){case Sn.ConnectorFileDeleted:await wc(e,t);break;case Sn.ConnectorDirectoryRenamed:await bc(e,t,i);break;case Sn.ConnectorDirectoryDeleted:await Sc(e,t);break;default:await yc(e,t);break}}catch(r){b.error(`[sync] Error handling remote connector file event: ${r}`)}}async handleLocalEvent(e,t){try{if(pc(e.filePath))switch(t){case ie.Updated:await mc(e.filePath);break;case ie.Deleted:await gc(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const i=z.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(b.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${$o.toSentenceCase(t)}: ${n.id}`),t){case ie.Updated:await this.updateElement(n,ee.OUTGOING);break;case ie.Deleted:await this.deleteElement(n,ee.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Et.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Et.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(i=>i.element.type===_.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ee.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==_.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(i=>!i.element.hasParent());for(const i of mr){const r=t.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(i=>i.element.hasParent());for(const i of mr){const r=n.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case he.DELETE:return this.deleteElement(e.element,e.direction);case he.CREATE:return this.updateElement(e.element,e.direction);case he.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),d=Et.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:he.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:he.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:he.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ie=j.join(io.tmpdir(),"membrane-mcp-status"),gr=3e4;class Cc{static{l(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=dn(void 0,e),n=yr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function dn(s,e){try{const t=e||process.cwd();if(!s){const i=yr(t);return i.length===0?null:i[0]}const n=ds(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>gr)return vt(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>gr)return vt(s,t),null}return c}}catch{s&&e&&vt(s,e)}return null}l(dn,"getMcpStatus");function yr(s){try{const e=s||process.cwd(),t=fs(e);if(!x.existsSync(Ie))return[];const n=x.readdirSync(Ie),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=dn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yr,"getAllMcpStatusFiles");function us(s){try{const t={...dn(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(Ie)||x.mkdirSync(Ie,{recursive:!0});const n=ds(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(us,"updateMcpStatus");function vt(s,e){try{const t=e||process.cwd();if(s){const n=ds(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=fs(t);if(x.existsSync(Ie)){const i=x.readdirSync(Ie);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(j.join(Ie,r))}}}catch{}}l(vt,"clearMcpStatus");function vc(s,e){const t=dn(s,e);t&&us({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(vc,"trackToolExecution");function fs(s){return Qr("md5").update(s).digest("hex").slice(0,8)}l(fs,"getCwdHash");function ds(s,e){const t=fs(e);return j.join(Ie,`mcp-${t}-${s}.json`)}l(ds,"getStatusFilePath");const kt={Agent:"agent",Cli:"cli"},L={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"};class wr{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=pe,this.mcpStatusService=new Cc,this.syncService=new Et,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=ft.loadConfig(this.cwd),this.notifier.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=ft.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===kt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===kt.Agent&&(await this.notifier.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 br=Es(null);function kc({children:s,membraneCLIService:e}){const{data:t}=Os("/account"),[n,i]=B(L.NOT_INITIALIZED),[r,o]=B([]),[a,c]=B({}),[u,f]=B([]),[d,p]=B(null),w=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ae(()=>{const h=l(({state:O})=>i(O),"handleStateChanged"),y=l(({stats:O})=>c(O),"handleStatsChanged"),v=l(({log:O})=>f(N=>[...N,O]),"handleLogAdded"),k=l(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=l(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(V.StateChanged,h),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,v),e.notifier.on(V.ConflictsChanged,k),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,h),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,v),e.notifier.off(V.ConflictsChanged,k),e.notifier.off(V.ConfigChanged,A)}},[]),m(br.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:l(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:l(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:l(h=>e.pullWorkspace(h),"pull"),push:l(h=>e.pushWorkspace(h),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(kc,"MembraneCLIServiceProvider");function le(){const s=Is(br);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const Sr=Es(process.cwd());function Tc({cwd:s,children:e}){return m(Sr.Provider,{value:s,children:e})}l(Tc,"CwdProvider");function Ec(){return Is(Sr)}l(Ec,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Tc,{cwd:n,children:m(Mr,{value:{fetcher:Fo()},children:m(kc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const hs=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=j.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:l(()=>{const s=j.join(process.cwd(),".cursor"),e=j.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 Ic({onExit:s,onComplete:e}){const[t,n]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[f,d]=B("");Me((w,h)=>{if(c||f){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?p(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(hs.length-1,t+1));else if(h.return||w===" "){const y=hs[t];a(y),r(!0)}});const p=l(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"green",children:"Success"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"green",children:c}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(C,{color:"red",children:f})}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Confirmation"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",m(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(C,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:E(C,{children:[m(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Select Agent"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:hs.map((w,h)=>E(S,{children:[E(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),E(C,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(Ic,"AddMcpServerScreen");function Oc(){const[s,e]=B(null),[t,n]=B([]),[i,r]=B(null);return Ae(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.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}}l(Oc,"useMcpStatus");function Ac(){const{error:s,serverCount:e,allMcpServers:t}=Oc(),n=Math.min(100,process.stdout.columns||100);return E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(C,{color:"red",children:"error reading status"}):e===0?m(C,{color:"yellow",children:"none"}):m(C,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",m(Rr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(S,{children:E(C,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(Ac,"Agent");const pn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Cr(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(Cr,"truncateText");function ps({children:s}){const{state:e,logs:t}=le();return!e||e===L.NOT_INITIALIZED?E(S,{gap:1,flexDirection:"row",children:[m(oo,{type:"dots"}),m(C,{children:"Initializing..."})]}):e===L.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===L.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,i)=>m(C,{color:pn(n.type),children:n.message},n.timestamp+i))}):s}l(ps,"EnsureInitialized");function vr({onExit:s,showEscOption:e=!0}){const[t,n]=B(""),{data:i,error:r,isLoading:o}=Os("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(Me((h,y)=>{y.escape&&s?.()}),u)return E(S,{children:[m(At,{}),m(C,{children:" Fetching workspaces..."})]});if(r)return E(S,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",r.message]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,g=c?.length??0;async function w(h){const y=f.find(A=>A.id===h);if(!y)return;const{key:v,secret:k}=y;!v||!k||(await a({workspaceKey:v,workspaceSecret:k}),s?.())}return l(w,"handleSelect"),E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(S,{marginTop:1,children:[m(C,{children:"Search: "}),m(ao,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(C,{children:["Showing ",p," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(co,{options:d,onChange:l(h=>{h&&w(h)},"onChange")})}),e&&m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]})}l(vr,"SelectWorkspace");function Nc({currentPat:s,onSubmit:e}){const[t,n]=B(""),[i,r]=B(!1),[o,a]=B(null);return E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(C,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(lo,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(S,{marginTop:1,children:E(C,{children:[m(At,{type:"dots"})," Validating token..."]})}),o&&m(C,{color:"red",children:o})]})}l(Nc,"PersonalAccessTokenInput");var Tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Tt||{});const $c={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},ms=[Tt.Authenticate,Tt.ConnectWorkspace];function kr({onComplete:s}){const{config:e}=le(),[t,n]=B(!1),[i,r]=B(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=si(),c=ms[i],u=i+1,f=ms.length,d=ms.map((w,h)=>{let y="pending";return h<i?y="done":h===i&&(y="current"),{id:w,label:$c[w],status:y}});async function p(w){const h=a&&w===""?a:w,y=new ii;try{await y.request("/account",{headers:{Authorization:`Bearer ${h}`}}),Ko(h),r(v=>v+1)}catch(v){console.error(v)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),Me((w,h)=>{o&&h.escape&&s&&s()}),t?m(S,{children:m(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(C,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Lc,{status:w.status,label:w.label},w.id))})]}),c===Tt.Authenticate&&m(Nc,{currentPat:a,onSubmit:p}),c===Tt.ConnectWorkspace&&m(vr,{onExit:g,showEscOption:!1})]})}l(kr,"Setup");function Lc({status:s,label:e}){return E(S,{children:[E(S,{width:2,children:[s==="current"&&m(At,{type:"dots"}),s==="done"&&m(C,{children:"\u2705"})]}),m(C,{dimColor:s!=="current",children:e})]})}l(Lc,"StepDisplay");function gs(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(C,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(S,{children:[m(S,{width:20,children:E(C,{children:[t,":"]})}),m(C,{color:"green",children:n})]},t))})]})}l(gs,"ElementStats");const ys=5,Dc=6;function Pc(){const{logs:s}=le(),[e,t]=B(0),n=Math.min(100,process.stdout.columns||100),i=ys,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-Dc,u=e<s.length-i,f=e>0;return Me((d,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(S,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>ys&&m(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>m(S,{marginLeft:1,children:m(C,{color:pn(d.type),children:Cr(d.message,c)})},d.timestamp+p)),s.length>ys&&E(S,{marginLeft:1,flexDirection:"row",children:[u&&m(C,{color:"grey",children:"\u2191 "}),f&&m(C,{color:"grey",children:"\u2193 "})]})]})}l(Pc,"Logs");const mn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function xc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=B(0),[r,o]=B(!1),[a,c]=B(!1);return Me((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(d=>d>0?d-1:mn.length-1):f.downArrow?i(d=>d<mn.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),mn[n].value==="sync"?e({watch:!0}):t())}}),Ae(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),E(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(ws,{isExpanded:a})}),E(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(C,{color:"white",bold:!0,children:"What would you like to do?"}),m(C,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:r?E(S,{flexDirection:"row",gap:1,children:[m(At,{type:"dots"}),m(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:mn.map((u,f)=>m(S,{flexDirection:"column",children:E(S,{flexDirection:"row",gap:1,children:[m(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(xc,"ResolveChangesUI");const Rc={[he.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[he.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[he.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ws({isExpanded:s}){const{conflicts:e}=le(),t=5,n=jr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(S,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=Rc[o][a];return E(S,{flexDirection:"column",children:[E(S,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[c.label," (",r.length,")"]}),m(C,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(S,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(S,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(S,{marginLeft:2,children:m(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ws,"Conflicts");function _c(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?Cr(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ae(()=>{i({watch:!0})},[]),E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:E(S,{flexDirection:"row",gap:1,children:[m(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:jc(e),children:[" [",Mc(e),"] "]})]})}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Local:"})}),m(C,{color:"grey",children:process.cwd()})]}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[m(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(xc,{}):E(wn,{children:[m(S,{paddingTop:1,children:m(gs,{})}),t.length>0&&m(Pc,{})]})]})}l(_c,"Workspace");function Mc(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}l(Mc,"getStatusDisplay");function jc(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}l(jc,"getStatusColor");const Kc="https://console.integration.app/w";function Fc(){const s=Ec(),e=Kr(!0),{exit:t,state:n}=le(),[i,r]=B(null),o=i??(n===L.SETTING_UP?"setup":"main");Me(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===L.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ri(s),u=`${Kc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ro(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ae(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(vr,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Ic,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(kr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(ps,{children:E(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Ac,{})}),m(_c,{}),m(S,{paddingLeft:2,children:m(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(Fc,"Main");const Tr=_r(process.argv.slice(2)),Er=Tr.cwd?Pr(Tr.cwd):process.cwd(),qc=new wr(kt.Agent,Er),Bc=l(()=>m(hn,{cwd:Er,membraneCLIService:qc,children:m(Fc,{})}),"App");function Uc(){It(m(Bc,{}))}l(Uc,"runAgent");function Jc(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(`
142
142
  `)).action(t=>{t.key&&t.secret?ft.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)):It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(kr,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Jc,"setupInitCommand");async function Ir(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Tn.sign(n,e)}l(Ir,"generateAdminAccessToken");async function Wc(s,e){return(await En.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(Wc,"fetchOpenApiSchema");function Or(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()}l(Or,"convertOpenApiSchemaToZod");function Ar(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(Ar,"extractPathParameters");function Vc(s,e,t,n,i,r,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,c=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},f={},d={};if(s.parameters){for(const g of s.parameters)if(g.in==="path")f[g.name]=Or(g.schema,!0).describe(g.description||`Path parameter: ${g.name}`);else if(g.in==="query"){const w=g.required===!0;d[g.name]=Or(g.schema,w).describe(g.description||`Query parameter: ${g.name}`)}}Object.keys(f).length>0&&(u.params=Z.object(f).describe("Path parameters")),Object.keys(d).length>0&&(u.query=Z.object(d).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=Z.any().describe("Request body"));const p=Object.keys(u).length>0?Z.object(u):Z.object({});return{name:a,description:c,parameters:p,async execute(g){try{const w=Ar(e);if(w.length>0){if(!g.params)throw new Error(`Missing required path parameters: ${w.join(", ")}`);const N=w.filter($=>!($ in g.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let h=`${n}${e}`;if(g.params)for(const[N,$]of Object.entries(g.params)){const F=`{${N}}`;h.includes(F)&&(h=h.replace(F,String($)))}const y=Ar(h);if(y.length>0)throw new Error(`Unresolved path parameters: ${y.join(", ")}`);const v=new URLSearchParams;if(g.query)for(const[N,$]of Object.entries(g.query))$!=null&&v.append(N,String($));v.toString()&&(h+=`?${v.toString()}`);const k=await Ir(i,r,o),A={method:t.toUpperCase(),headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"}};g.body&&t.toLowerCase()!=="get"&&(A.data=g.body);const O=await En.request({url:h,...A});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(w){return En.isAxiosError(w)?{content:[{type:"text",text:`Error: ${w.response?.data?`HTTP ${w.response.status}: ${w.response.statusText} - ${JSON.stringify(w.response.data)}`:`HTTP ${w.response?.status||"unknown"}: ${w.message}`}`}],isError:!0}:w instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${w.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(Vc,"createApiTool");function Gc(s,e,t,n,i){const r=[];if(!s.paths)return r;for(const[o,a]of Object.entries(s.paths))if(typeof a=="object"&&a!==null){for(const[c,u]of Object.entries(a))if(["get","post","put","delete","patch"].includes(c)&&u&&typeof u=="object"){const f=Vc(u,o,c,e,t,n,i);r.push(f)}}return r}l(Gc,"convertOpenApiToTools");function zc(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(`
143
143
  `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=jt();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||$n,n=await Ir(e.workspaceKey,e.workspaceSecret,e.testCustomerId),i=await Wc(t,n),r=Gc(i,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new ho({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
144
144
  Use it for anything related to Membrane or integrations.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",