@membranehq/cli 1.2.5 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -141,7 +141,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
141
141
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
142
142
  `,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 r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.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,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),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):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,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(Je(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(wa(t.key)&&!Je(t.sep,"newline")){const o=Rt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Je(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||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Je(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);r||t.value?(e.items.push({start:i,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&&!Je(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:i});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 r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.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||Je(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 r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,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 r=ds(n),i=Rt(r);ba(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:i,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(`
143
143
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
144
- `,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=ds(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=ds(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 Sa(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new ga||null,prettyErrors:e}}c(Sa,"parseOptions");function Sd(s,e={}){const{lineCounter:t,prettyErrors:n}=Sa(e),r=new jr(t?.addNewLine),i=new Rr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(rs(s,t)),a.warnings.forEach(rs(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Sd,"parseAllDocuments");function Ca(s,e={}){const{lineCounter:t,prettyErrors:n}=Sa(e),r=new jr(t?.addNewLine),i=new Rr(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new ct(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(rs(s,t)),o.warnings.forEach(rs(s,t))),o}c(Ca,"parseDocument");function Cd(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Ca(s,t);if(!r)return null;if(r.warnings.forEach(i=>xo(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Cd,"parse");function vd(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 r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return rt(s)&&!n?s.toString(t):new Jt(s,n,t).toString(t)}c(vd,"stringify");var kd=Object.freeze({__proto__:null,Alias:Bn,CST:yd,Composer:Rr,Document:Jt,Lexer:ma,LineCounter:ga,Pair:re,Parser:jr,Scalar:M,Schema:Ds,YAMLError:Ar,YAMLMap:ue,YAMLParseError:ct,YAMLSeq:We,YAMLWarning:ta,isAlias:Ue,isCollection:Y,isDocument:rt,isMap:kt,isNode:X,isPair:z,isScalar:V,isSeq:Tt,parse:Cd,parseAllDocuments:Sd,parseDocument:Ca,stringify:vd,visit:it,visitAsync:qn});class Fr extends Cl{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const de={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Td={ignored:zl,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 Ed extends Fr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=pe(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(A.existsSync(this.membraneDir)||A.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Sl.watch(this.membraneDir,Td),this.watcher.on("add",e=>this.handleFileSystemEvent(de.Updated,e)).on("change",e=>this.handleFileSystemEvent(de.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(de.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(de.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=P.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=P.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+P.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=P.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===de.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 r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return A.readFileSync(e,"utf8")}processFileEvent(e,t){const n=P.relative(this.membraneDir,e);let r;try{r=t?kd.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return wl.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(){A.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=A.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=P.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=A.readFileSync(r,"utf8"),o=P.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var qr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(qr||{});const _d={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class Id extends Fr{static{c(this,"RemoteElementWatcher")}constructor(e=_d){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await F.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.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new vl(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==rl.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class va{static{c(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 r=this.typeIndex.get(e.type);r&&(r.delete(t),r.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())}}const Mt="connectors",Le="development",Br={};async function ka(){const e=(await F.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await F.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=He(),i=(U.existsSync(n)?U.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=K.join(n,o);try{return U.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=U.readdirSync(K.join(n,o)),l=await Kr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await F.withClient(f=>f.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await F.withClient(f=>f.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await F.withClient(f=>f.patch(`connectors/${u.id}`,{...l,workspaceId:e}));else if(!t[l.id]){let f=!1;try{const h=await Ur({connectorId:l.id});h&&h.isPublic&&(f=!0)}catch{}if(!f){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await F.withClient(m=>m.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const d=a.filter(f=>U.statSync(K.join(n,o,f)).isDirectory());for(const f of d)await $d({connector:l,version:f,connectorId:t[l.id]})}return t}c(ka,"pushConnectors");async function Ta({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Fi(),o=await Ur({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Nd({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await xd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(Ta,"pullRemoteConnector");function He(){const s=ar();return K.join(s.membraneDirPath,Mt)}c(He,"getConnectorsPath");async function Kr(s){const e=K.join(He(),s,`${s}.yml`);return ur(e,!1)}c(Kr,"readConnector");async function Ad(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=U.createWriteStream(e),i=Ri("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=U.readdirSync(s);for(const a of o){const l=K.join(s,a),u=U.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Ad,"createZipArchive");async function Od(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Li.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=K.join(e,o);U.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=K.join(e,o),u=K.dirname(l);U.mkdirSync(u,{recursive:!0});const d=U.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(Od,"extractZipArchive");async function $d({connector:s,version:e,connectorId:t}){const n=K.join(He(),De(s),Ea(e)),r=K.join(n,"src"),i=K.join(n,"src.zip"),o=U.existsSync(i);if(U.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Ad(r,i)),!U.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Mi;if(a.append("file",U.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Le)b.info(`[connectors] Uploading connector ${t}`),await F.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await F.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 F.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}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&U.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),U.unlinkSync(i))}}c($d,"pushConnectorVersion");async function Ur({connectorId:s}){if(s){if(Br[s])return Br[s];try{const e=await F.withClient(t=>t.get(`connectors/${s}`),!1);return Br[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Ur,"getConnector");async function Nd({basePath:s,connector:e}){const t=De(e),n=K.join(s,Mt,t);U.mkdirSync(n,{recursive:!0});const r=K.join(n,`${De(e)}.yml`);U.writeFileSync(r,Se.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Nd,"pullConnector$1");async function xd({connector:s,connectorVersion:e,basePath:t}){const n=De(s),r=Ea(e),i=K.join(t,"connectors",n,r),o=await F.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));U.mkdirSync(i,{recursive:!0});const a=K.join(i,"src.zip");if(U.writeFileSync(a,o),!e){const l=K.join(i,"src");U.mkdirSync(l,{recursive:!0}),await Od(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(xd,"pullConnectorVersion");function De(s){return s.key}c(De,"getConnectorDirName");function Ea(s){return s??Le}c(Ea,"getConnectorVersionDirName");function Pd(s){const e=Fi(),t=De(s);return K.join(e,Mt,t)}c(Pd,"getConnectorDirPath");function Rd(s){return s.match(`${Mt}/[^/]+/${Le}/src/.*`)!==null}c(Rd,"isConnectorSourceFile");async function Md(s){const e=s.match(`${Mt}/([^/]+)/${Le}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=U.readFileSync(s,"utf-8");await F.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(Md,"putConnectorFile");async function Ld(s){const e=s.match(`${Mt}/([^/]+)/${Le}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await F.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Ld,"deleteConnectorFile");async function Dd(s,e){try{const t=await F.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await F.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=De(t),i=K.join(He(),r,Le,"src",e);U.mkdirSync(K.dirname(i),{recursive:!0}),n!=null?(U.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):U.existsSync(i)&&(U.unlinkSync(i),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}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(Dd,"pullConnectorFile");async function jd(s,e){const t=await F.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=De(t),r=K.join(He(),n,Le,"src",e);U.existsSync(r)&&(U.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(jd,"deleteLocalConnectorFile");async function Fd(s,e,t){if(t&&e!==t)try{const n=await F.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=De(n),i=K.join(He(),r,Le,"src"),o=K.join(i,e),a=K.join(i,t);U.existsSync(o)&&(U.mkdirSync(K.dirname(a),{recursive:!0}),U.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(Fd,"renameLocalConnectorDirectory");async function qd(s,e){try{const t=await F.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=De(t),r=K.join(He(),n,Le,"src",e);if(U.existsSync(r)){const i=K.resolve(He());if(!K.resolve(r).startsWith(i))return;U.rmSync(r,{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}`)}}c(qd,"deleteLocalConnectorDirectory");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Bd extends Fr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await F.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await F.withClient(t=>t.post("/local-clients",{hostname:Pi.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const Ve=new Bd({heartbeatIntervalMs:15e3}),_a=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Tn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Ve,this.localCache=new va,this.remoteCache=new va,this.localRepo=new hu(this.localCache),this.remoteRepo=new pu(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),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Ta({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await ka();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ce.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ce.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Ed({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(de.Updated,e=>this.handleLocalEvent(e,de.Updated)),this.localWatcher.on(de.Deleted,e=>this.handleLocalEvent(e,de.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Id,this.remoteWatcher.on(qr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(qr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),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),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ce.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ce.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ce.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ce.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Ur({connectorId:o});if(!l?.key)return;const u=Pd(l);await this.localWatcher?.executeWithPathLock(u,async()=>Ta({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Us.ConnectorFileDeleted:await jd(e,t);break;case Us.ConnectorDirectoryRenamed:await Fd(e,t,r);break;case Us.ConnectorDirectoryDeleted:await qd(e,t);break;default:await Dd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(Rd(e.filePath))switch(t){case de.Updated:await Md(e.filePath);break;case de.Deleted:await Ld(e.filePath);break}else{let n=Z.fromPathAndData(e.filePath,e.data);if(!n){const r=Z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ce.OUTGOING)}] ${uu.toSentenceCase(t)}: ${n.id}`),t){case de.Updated:await this.updateElement(n,ce.OUTGOING);break;case de.Deleted:await this.deleteElement(n,ce.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Tn.getChanges(ce.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Tn.getChanges(ce.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(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ce.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of _a){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of _a){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case Pe.DELETE:return this.deleteElement(e.element,e.direction);case Pe.CREATE:return this.updateElement(e.element,e.direction);case Pe.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=Tn.detectChangeForElement(u,d,e);f&&a.push(f)}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 ce.INCOMING:return"local\u2190remote";case ce.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Pe.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Pe.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Pe.UPDATE,element:e,direction:n,isConflict:!1}:null}}const ze=P.join(kl.tmpdir(),"membrane-mcp-status"),Ia=3e4;class Kd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fs(void 0,e),n=Aa(e);t&&Ve.setMcpStatus(t),await Ve.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function fs(s,e){try{const t=e||process.cwd();if(!s){const r=Aa(t);return r.length===0?null:r[0]}const n=Hr(s,t);if(A.existsSync(n)){const r=A.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Ia)return sn(s,t),null;const a=A.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Ia)return sn(s,t),null}return l}}catch{s&&e&&sn(s,e)}return null}c(fs,"getMcpStatus");function Aa(s){try{const e=s||process.cwd(),t=Jr(e);if(!A.existsSync(ze))return[];const n=A.readdirSync(ze),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=fs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Aa,"getAllMcpStatusFiles");function Wr(s){try{const t={...fs(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};A.existsSync(ze)||A.mkdirSync(ze,{recursive:!0});const n=Hr(s.processId,s.cwd);A.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Wr,"updateMcpStatus");function sn(s,e){try{const t=e||process.cwd();if(s){const n=Hr(s,t);A.existsSync(n)&&A.unlinkSync(n)}else{const n=Jr(t);if(A.existsSync(ze)){const r=A.readdirSync(ze);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&A.unlinkSync(P.join(ze,i))}}}catch{}}c(sn,"clearMcpStatus");function Ud(s,e){const t=fs(s,e);t&&Wr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Ud,"trackToolExecution");function Jr(s){return bl("md5").update(s).digest("hex").slice(0,8)}c(Jr,"getCwdHash");function Hr(s,e){const t=Jr(e);return P.join(ze,`mcp-${t}-${s}.json`)}c(Hr,"getStatusFilePath");const hs={Agent:"agent",Cli:"cli"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Wd{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Ve,this.mcpStatusService=new Kd,this.syncService=new Tn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&F.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&F.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(D.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),st.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(D.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=st.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 r=st.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===hs.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===hs.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 Oa=Gs(null);function Jd({children:s,membraneCLIService:e}){const{data:t}=xi("/account"),[n,r]=H(D.NOT_INITIALIZED),[i,o]=H([]),[a,l]=H({}),[u,d]=H([]),[f,h]=H(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return pt(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d(x=>[...x,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),$=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,$),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,$)}},[]),g(Oa.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(Jd,"MembraneCLIServiceProvider");function ke(){const s=Ys(Oa);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(ke,"useMembraneCLIService");const Vr=Gs(null),$a=c(()=>{const s=Ys(Vr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Hd=c(s=>et.Children.count(s)>0,"hasChildren");function Vd(s){const e=$a(),{label:t,value:n,isInitiallyExpanded:r}=s,i=fl(),o=Xs(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=H(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:Hd(h)}}c(Vd,"useTreeItem");function Lt(s){const e=$a(),t=Vd(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=Gd}=s,l=t.ref;_n(()=>{function h(m){return s.onInput?.(m)?!0:m.active&&m.key.rightArrow&&!n?(o(!0),!0):m.active&&m.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function d(h){const m=u;return m.nextSibling||(m.nextSibling={parent:l,prevSibling:m,index:m.index+1}),u=m.nextSibling,m.label=h,m}c(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(In,{children:[_(C,{marginLeft:e.depth*2,children:[g(C,{width:2,children:r&&g(v,{children:n?"\u25BC":"\u25B6"})}),zd(t),a(t)]}),n&&g(Vr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Lt,"TreeItem");function zd({active:s,label:e}){return g(C,{width:32,children:g(v,{inverse:s,children:e})})}c(zd,"defaultRenderLabel");function Gd(s){return g(v,{})}c(Gd,"defaultRenderValue");const ut=c(({label:s,onPress:e,hotkey:t})=>g(Lt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>g(C,{children:g(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),Na=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=H(e),[l,u]=H(!1);return _n(()=>{l||a(e)},[l,e]),g(Lt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return g(C,{children:n||!l?g(v,{dimColor:!0,children:f}):_(In,{children:[g(C,{width:f.length+1,children:g(Di,{...i,focus:l,value:d,onChange:a})}),g(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Yd=c(s=>g(Na,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Xs({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=H(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),tt((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),g(Vr.Provider,{value:i,children:_(C,{flexDirection:"column",children:[g(Lt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&g(C,{marginTop:1,flexDirection:"column",children:g(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Lt,ye.TextField=Na;function dt({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=H([]),{fetchElements:a,getSyncedElementsByType:l}=ke();return pt(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),g(Lt,{label:s,children:i.map(u=>g(Lt,{label:u.name,children:e===N.Action&&_(In,{children:[t&&n&&g(ut,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&g(ut,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(dt,"WorkspaceElementsTreeItem");function Xd({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=ke(),[i,o]=H(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,m)=>{try{await t({[h]:m}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),d=c(async()=>{try{if(e){const h=st.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const m=r(N.Action);await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:m.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),f=c(async()=>{try{const h=st.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return _(C,{flexDirection:"column",gap:1,children:[g(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),g(C,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[g(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),g(Yd,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),g(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),g(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>g(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[g(ut,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),g(ut,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),g(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[g(dt,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),g(dt,{label:"Flows",elementType:N.Flow}),g(dt,{label:"Data Sources",elementType:N.DataSource}),g(dt,{label:"Field Mappings",elementType:N.FieldMapping}),g(dt,{label:"Packages",elementType:N.Package}),g(dt,{label:"App Data Schemas",elementType:N.AppDataSchema}),g(dt,{label:"App Event Types",elementType:N.AppEventType})]})]}),g(ut,{label:"Save Configuration",onPress:d,hotkey:"s"}),g(ut,{label:"Reload Configuration",onPress:f,hotkey:"r"}),g(ut,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&g(C,{paddingX:2,children:g(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(Xd,"ConfigManager");const xa=Gs(process.cwd());function Zd({cwd:s,children:e}){return g(xa.Provider,{value:s,children:e})}c(Zd,"CwdProvider");function Qd(){return Ys(xa)}c(Qd,"useCwd");function zr({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(Zd,{cwd:n,children:g(Tl,{value:{fetcher:Hl()},children:g(Jd,{membraneCLIService:t,children:e})})})}c(zr,"Layout");function ef(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
144
+ `,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=ds(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=ds(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 Sa(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new ga||null,prettyErrors:e}}c(Sa,"parseOptions");function Sd(s,e={}){const{lineCounter:t,prettyErrors:n}=Sa(e),r=new jr(t?.addNewLine),i=new Rr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(rs(s,t)),a.warnings.forEach(rs(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Sd,"parseAllDocuments");function Ca(s,e={}){const{lineCounter:t,prettyErrors:n}=Sa(e),r=new jr(t?.addNewLine),i=new Rr(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new ct(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(rs(s,t)),o.warnings.forEach(rs(s,t))),o}c(Ca,"parseDocument");function Cd(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Ca(s,t);if(!r)return null;if(r.warnings.forEach(i=>xo(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Cd,"parse");function vd(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 r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return rt(s)&&!n?s.toString(t):new Jt(s,n,t).toString(t)}c(vd,"stringify");var kd=Object.freeze({__proto__:null,Alias:Bn,CST:yd,Composer:Rr,Document:Jt,Lexer:ma,LineCounter:ga,Pair:re,Parser:jr,Scalar:M,Schema:Ds,YAMLError:Ar,YAMLMap:ue,YAMLParseError:ct,YAMLSeq:We,YAMLWarning:ta,isAlias:Ue,isCollection:Y,isDocument:rt,isMap:kt,isNode:X,isPair:z,isScalar:V,isSeq:Tt,parse:Cd,parseAllDocuments:Sd,parseDocument:Ca,stringify:vd,visit:it,visitAsync:qn});class Fr extends Cl{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const de={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Td={ignored:zl,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 Ed extends Fr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=pe(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(A.existsSync(this.membraneDir)||A.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Sl.watch(this.membraneDir,Td),this.watcher.on("add",e=>this.handleFileSystemEvent(de.Updated,e)).on("change",e=>this.handleFileSystemEvent(de.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(de.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(de.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=P.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=P.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+P.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=P.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===de.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 r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return A.readFileSync(e,"utf8")}processFileEvent(e,t){const n=P.relative(this.membraneDir,e);let r;try{r=t?kd.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return wl.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(){A.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=A.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=P.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=A.readFileSync(r,"utf8"),o=P.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var qr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(qr||{});const _d={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class Id extends Fr{static{c(this,"RemoteElementWatcher")}constructor(e=_d){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await F.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.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new vl(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==rl.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class va{static{c(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 r=this.typeIndex.get(e.type);r&&(r.delete(t),r.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())}}const Mt="connectors",Le="development",Br={};async function ka(){const e=(await F.withClient(o=>o.get("org-workspace-id"))).id,t={};b.info("[connectors] Loading custom connectors"),await F.withClient(o=>o.get(`/connectors?workspaceId=${e}`)),b.info("[connectors] Loading public connectors");const n=He(),i=(U.existsSync(n)?U.readdirSync(n):[]).filter(o=>{if(o.startsWith("."))return!1;const a=K.join(n,o);try{return U.statSync(a).isDirectory()}catch{return!1}});for(const o of i){b.info(`[connectors] Loading connector from: ${o}`);const a=U.readdirSync(K.join(n,o)),l=await Kr(o);if(!l)continue;"baseUri"in l&&delete l.baseUri;let u;if(l.uuid&&(u=await F.withClient(f=>f.get(`/connectors/${l.uuid}`),!1)),u)t[l.id]=u.id,b.info(`[connectors] Matched ${l.name} uuid: ${l.uuid}`),u.isPublic||(u.archivedAt&&(b.info(`[connectors] Restoring archived connector ${l.name}`),await F.withClient(f=>f.post(`connectors/${u.id}/restore`))),b.info(`[connectors] Updating connector ${l.name}`),await F.withClient(f=>f.patch(`connectors/${u.id}`,{...l,workspaceId:e})));else if(!t[l.id]&&!u?.isPublic){let f=!1;try{const h=await Ur({connectorId:l.id});h&&h.isPublic&&(f=!0)}catch{}if(!f){b.info(`[connectors] Creating custom connector ${l.name} (${l.key})`);const h=await F.withClient(m=>m.post("connectors",{...l,workspaceId:e}));t[l.id]=h.id}}const d=a.filter(f=>U.statSync(K.join(n,o,f)).isDirectory());for(const f of d)await $d({connector:l,version:f,connectorId:t[l.id]})}return t}c(ka,"pushConnectors");async function Ta({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=Fi(),o=await Ur({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Nd({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await xd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(Ta,"pullRemoteConnector");function He(){const s=ar();return K.join(s.membraneDirPath,Mt)}c(He,"getConnectorsPath");async function Kr(s){const e=K.join(He(),s,`${s}.yml`);return ur(e,!1)}c(Kr,"readConnector");async function Ad(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=U.createWriteStream(e),i=Ri("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=U.readdirSync(s);for(const a of o){const l=K.join(s,a),u=U.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(Ad,"createZipArchive");async function Od(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Li.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=K.join(e,o);U.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=K.join(e,o),u=K.dirname(l);U.mkdirSync(u,{recursive:!0});const d=U.createWriteStream(l);i.pipe(d),d.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(Od,"extractZipArchive");async function $d({connector:s,version:e,connectorId:t}){const n=K.join(He(),De(s),Ea(e)),r=K.join(n,"src"),i=K.join(n,"src.zip"),o=U.existsSync(i);if(U.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await Ad(r,i)),!U.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Mi;if(a.append("file",U.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Le)b.info(`[connectors] Uploading connector ${t}`),await F.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await F.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 F.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}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&U.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),U.unlinkSync(i))}}c($d,"pushConnectorVersion");async function Ur({connectorId:s}){if(s){if(Br[s])return Br[s];try{const e=await F.withClient(t=>t.get(`connectors/${s}`),!1);return Br[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Ur,"getConnector");async function Nd({basePath:s,connector:e}){const t=De(e),n=K.join(s,Mt,t);U.mkdirSync(n,{recursive:!0});const r=K.join(n,`${De(e)}.yml`);U.writeFileSync(r,Se.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Nd,"pullConnector$1");async function xd({connector:s,connectorVersion:e,basePath:t}){const n=De(s),r=Ea(e),i=K.join(t,"connectors",n,r),o=await F.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));U.mkdirSync(i,{recursive:!0});const a=K.join(i,"src.zip");if(U.writeFileSync(a,o),!e){const l=K.join(i,"src");U.mkdirSync(l,{recursive:!0}),await Od(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(xd,"pullConnectorVersion");function De(s){return s.key}c(De,"getConnectorDirName");function Ea(s){return s??Le}c(Ea,"getConnectorVersionDirName");function Pd(s){const e=Fi(),t=De(s);return K.join(e,Mt,t)}c(Pd,"getConnectorDirPath");function Rd(s){return s.match(`${Mt}/[^/]+/${Le}/src/.*`)!==null}c(Rd,"isConnectorSourceFile");async function Md(s){const e=s.match(`${Mt}/([^/]+)/${Le}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=U.readFileSync(s,"utf-8");await F.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(Md,"putConnectorFile");async function Ld(s){const e=s.match(`${Mt}/([^/]+)/${Le}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Kr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await F.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(Ld,"deleteConnectorFile");async function Dd(s,e){try{const t=await F.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await F.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=De(t),i=K.join(He(),r,Le,"src",e);U.mkdirSync(K.dirname(i),{recursive:!0}),n!=null?(U.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):U.existsSync(i)&&(U.unlinkSync(i),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}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(Dd,"pullConnectorFile");async function jd(s,e){const t=await F.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=De(t),r=K.join(He(),n,Le,"src",e);U.existsSync(r)&&(U.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(jd,"deleteLocalConnectorFile");async function Fd(s,e,t){if(t&&e!==t)try{const n=await F.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=De(n),i=K.join(He(),r,Le,"src"),o=K.join(i,e),a=K.join(i,t);U.existsSync(o)&&(U.mkdirSync(K.dirname(a),{recursive:!0}),U.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(Fd,"renameLocalConnectorDirectory");async function qd(s,e){try{const t=await F.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=De(t),r=K.join(He(),n,Le,"src",e);if(U.existsSync(r)){const i=K.resolve(He());if(!K.resolve(r).startsWith(i))return;U.rmSync(r,{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}`)}}c(qd,"deleteLocalConnectorDirectory");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Bd extends Fr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await F.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await F.withClient(t=>t.post("/local-clients",{hostname:Pi.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const Ve=new Bd({heartbeatIntervalMs:15e3}),_a=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Tn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Ve,this.localCache=new va,this.remoteCache=new va,this.localRepo=new hu(this.localCache),this.remoteRepo=new pu(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),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Ta({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await ka();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ce.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ce.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Ed({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(de.Updated,e=>this.handleLocalEvent(e,de.Updated)),this.localWatcher.on(de.Deleted,e=>this.handleLocalEvent(e,de.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Id,this.remoteWatcher.on(qr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(qr.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),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),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ce.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ce.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ce.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ce.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Ur({connectorId:o});if(!l?.key)return;const u=Pd(l);await this.localWatcher?.executeWithPathLock(u,async()=>Ta({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Us.ConnectorFileDeleted:await jd(e,t);break;case Us.ConnectorDirectoryRenamed:await Fd(e,t,r);break;case Us.ConnectorDirectoryDeleted:await qd(e,t);break;default:await Dd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(Rd(e.filePath))switch(t){case de.Updated:await Md(e.filePath);break;case de.Deleted:await Ld(e.filePath);break}else{let n=Z.fromPathAndData(e.filePath,e.data);if(!n){const r=Z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ce.OUTGOING)}] ${uu.toSentenceCase(t)}: ${n.id}`),t){case de.Updated:await this.updateElement(n,ce.OUTGOING);break;case de.Deleted:await this.deleteElement(n,ce.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Tn.getChanges(ce.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Tn.getChanges(ce.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(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ce.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of _a){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of _a){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case Pe.DELETE:return this.deleteElement(e.element,e.direction);case Pe.CREATE:return this.updateElement(e.element,e.direction);case Pe.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),d=n.get(l),f=Tn.detectChangeForElement(u,d,e);f&&a.push(f)}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 ce.INCOMING:return"local\u2190remote";case ce.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Pe.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Pe.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Pe.UPDATE,element:e,direction:n,isConflict:!1}:null}}const ze=P.join(kl.tmpdir(),"membrane-mcp-status"),Ia=3e4;class Kd{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fs(void 0,e),n=Aa(e);t&&Ve.setMcpStatus(t),await Ve.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function fs(s,e){try{const t=e||process.cwd();if(!s){const r=Aa(t);return r.length===0?null:r[0]}const n=Hr(s,t);if(A.existsSync(n)){const r=A.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Ia)return sn(s,t),null;const a=A.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Ia)return sn(s,t),null}return l}}catch{s&&e&&sn(s,e)}return null}c(fs,"getMcpStatus");function Aa(s){try{const e=s||process.cwd(),t=Jr(e);if(!A.existsSync(ze))return[];const n=A.readdirSync(ze),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=fs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Aa,"getAllMcpStatusFiles");function Wr(s){try{const t={...fs(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};A.existsSync(ze)||A.mkdirSync(ze,{recursive:!0});const n=Hr(s.processId,s.cwd);A.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Wr,"updateMcpStatus");function sn(s,e){try{const t=e||process.cwd();if(s){const n=Hr(s,t);A.existsSync(n)&&A.unlinkSync(n)}else{const n=Jr(t);if(A.existsSync(ze)){const r=A.readdirSync(ze);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&A.unlinkSync(P.join(ze,i))}}}catch{}}c(sn,"clearMcpStatus");function Ud(s,e){const t=fs(s,e);t&&Wr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Ud,"trackToolExecution");function Jr(s){return bl("md5").update(s).digest("hex").slice(0,8)}c(Jr,"getCwdHash");function Hr(s,e){const t=Jr(e);return P.join(ze,`mcp-${t}-${s}.json`)}c(Hr,"getStatusFilePath");const hs={Agent:"agent",Cli:"cli"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Wd{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Ve,this.mcpStatusService=new Kd,this.syncService=new Tn,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&F.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&F.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(D.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(D.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(D.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),st.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(D.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(D.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=st.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 r=st.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===hs.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===hs.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===hs.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 Oa=Gs(null);function Jd({children:s,membraneCLIService:e}){const{data:t}=xi("/account"),[n,r]=H(D.NOT_INITIALIZED),[i,o]=H([]),[a,l]=H({}),[u,d]=H([]),[f,h]=H(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return pt(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),T=c(({log:I})=>d(x=>[...x,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),$=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,T),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,$),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,T),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,$)}},[]),g(Oa.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(Jd,"MembraneCLIServiceProvider");function ke(){const s=Ys(Oa);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(ke,"useMembraneCLIService");const Vr=Gs(null),$a=c(()=>{const s=Ys(Vr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Hd=c(s=>et.Children.count(s)>0,"hasChildren");function Vd(s){const e=$a(),{label:t,value:n,isInitiallyExpanded:r}=s,i=fl(),o=Xs(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=H(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:Hd(h)}}c(Vd,"useTreeItem");function Lt(s){const e=$a(),t=Vd(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=Gd}=s,l=t.ref;_n(()=>{function h(m){return s.onInput?.(m)?!0:m.active&&m.key.rightArrow&&!n?(o(!0),!0):m.active&&m.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function d(h){const m=u;return m.nextSibling||(m.nextSibling={parent:l,prevSibling:m,index:m.index+1}),u=m.nextSibling,m.label=h,m}c(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(In,{children:[_(C,{marginLeft:e.depth*2,children:[g(C,{width:2,children:r&&g(v,{children:n?"\u25BC":"\u25B6"})}),zd(t),a(t)]}),n&&g(Vr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Lt,"TreeItem");function zd({active:s,label:e}){return g(C,{width:32,children:g(v,{inverse:s,children:e})})}c(zd,"defaultRenderLabel");function Gd(s){return g(v,{})}c(Gd,"defaultRenderValue");const ut=c(({label:s,onPress:e,hotkey:t})=>g(Lt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>g(C,{children:g(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),Na=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=H(e),[l,u]=H(!1);return _n(()=>{l||a(e)},[l,e]),g(Lt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return g(C,{children:n||!l?g(v,{dimColor:!0,children:f}):_(In,{children:[g(C,{width:f.length+1,children:g(Di,{...i,focus:l,value:d,onChange:a})}),g(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Yd=c(s=>g(Na,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Xs({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=H(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),tt((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),g(Vr.Provider,{value:i,children:_(C,{flexDirection:"column",children:[g(Lt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&g(C,{marginTop:1,flexDirection:"column",children:g(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Lt,ye.TextField=Na;function dt({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=H([]),{fetchElements:a,getSyncedElementsByType:l}=ke();return pt(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),g(Lt,{label:s,children:i.map(u=>g(Lt,{label:u.name,children:e===N.Action&&_(In,{children:[t&&n&&g(ut,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&g(ut,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(dt,"WorkspaceElementsTreeItem");function Xd({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=ke(),[i,o]=H(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,m)=>{try{await t({[h]:m}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),d=c(async()=>{try{if(e){const h=st.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const m=r(N.Action);await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:m.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),f=c(async()=>{try{const h=st.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return _(C,{flexDirection:"column",gap:1,children:[g(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),g(C,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[g(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),g(Yd,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),g(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),g(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>g(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[g(ut,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),g(ut,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),g(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[g(dt,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await rr({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),g(dt,{label:"Flows",elementType:N.Flow}),g(dt,{label:"Data Sources",elementType:N.DataSource}),g(dt,{label:"Field Mappings",elementType:N.FieldMapping}),g(dt,{label:"Packages",elementType:N.Package}),g(dt,{label:"App Data Schemas",elementType:N.AppDataSchema}),g(dt,{label:"App Event Types",elementType:N.AppEventType})]})]}),g(ut,{label:"Save Configuration",onPress:d,hotkey:"s"}),g(ut,{label:"Reload Configuration",onPress:f,hotkey:"r"}),g(ut,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&g(C,{paddingX:2,children:g(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(Xd,"ConfigManager");const xa=Gs(process.cwd());function Zd({cwd:s,children:e}){return g(xa.Provider,{value:s,children:e})}c(Zd,"CwdProvider");function Qd(){return Ys(xa)}c(Qd,"useCwd");function zr({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(Zd,{cwd:n,children:g(Tl,{value:{fetcher:Hl()},children:g(Jd,{membraneCLIService:t,children:e})})})}c(zr,"Layout");function ef(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
145
145
  `)).action(()=>{Zs(et.createElement(zr,{membraneCLIService:e,children:et.createElement(Xd,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(ef,"setupConfigCommand");function tf({currentPat:s,onSubmit:e}){const[t,n]=H(""),[r,i]=H(!1),[o,a]=H(null);return _(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(C,{marginTop:-1,marginBottom:1,children:g(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(v,{children:"Please provide your Personal Access Token. You can find it here:"}),g(C,{marginTop:1,marginBottom:1,children:g(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Di,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&g(C,{marginTop:1,children:_(v,{children:[g(An,{type:"dots"})," Validating token..."]})}),o&&g(v,{color:"red",children:o})]})}c(tf,"PersonalAccessTokenInput");function Pa({onExit:s,showEscOption:e=!0}){const[t,n]=H(""),{data:r,error:i,isLoading:o}=xi("/account"),{updateConfig:a}=ke(),l=r?.workspaces,u=o;if(tt((p,w)=>{w.escape&&s?.()}),u)return _(C,{children:[g(An,{}),g(v,{children:" Fetching workspaces..."})]});if(i)return _(C,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,m=l?.length??0;async function y(p){const w=d.find($=>$.id===p);if(!w)return;const{key:T,secret:E}=w;!T||!E||(await a({workspaceKey:T,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(C,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(C,{marginTop:-1,children:g(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(C,{marginTop:1,children:[g(v,{children:"Search: "}),g(El,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&_(v,{children:["Showing ",h," of ",m," workspaces."]}),g(C,{marginTop:1,children:g(_l,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&g(C,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Pa,"SelectWorkspace");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const nf={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Gr=[rn.Authenticate,rn.ConnectWorkspace];function Ra({onComplete:s}){const{config:e}=ke(),[t,n]=H(!1),[r,i]=H(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Bi(),l=Gr[r],u=r+1,d=Gr.length,f=Gr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:nf[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Ki;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),Jl(p),i(T=>T+1)}catch(T){console.error(T)}}c(h,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),tt((y,p)=>{o&&p.escape&&s&&s()}),t?g(C,{children:g(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(C,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&g(v,{color:"grey",children:" [esc: go back]"})]})}),g(C,{flexDirection:"column",paddingLeft:2,children:f.map(y=>g(sf,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&g(tf,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&g(Pa,{onExit:m,showEscOption:!1})]})}c(Ra,"Setup");function sf({status:s,label:e}){return _(C,{children:[_(C,{width:2,children:[s==="current"&&g(An,{type:"dots"}),s==="done"&&g(v,{children:"\u2705"})]}),g(v,{dimColor:s!=="current",children:e})]})}c(sf,"StepDisplay");function rf(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(`
146
146
  `)).action(t=>{t.key&&t.secret?st.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)):Zs(et.createElement(zr,{membraneCLIService:e,children:et.createElement(Ra,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(rf,"setupInitCommand");async function Ma(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Qs.sign(n,e)}c(Ma,"generateMcpAccessToken");async function of(s,e){return(await Ht.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(of,"fetchOpenApiSchema");function Ge(s,e=!0,t,n=new Set){if(!s)return e?J.string():J.string().optional();if(Object.keys(s).length===0)return e?J.any():J.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return J.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ge(o,e,t,n)}return J.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Ge(a,l,t,n)}if(Object.keys(i).length>0){if(r=J.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Ge(s.additionalProperties,!1,t,n);r=J.record(J.string(),o)}else r=J.record(J.string(),J.any())}else if(s.type==="array"){const i=s.items?Ge(s.items,!0,t,n):J.any();r=J.array(i)}else if(s.anyOf)r=J.any();else{switch(s.type){case"integer":r=J.coerce.number().int();break;case"number":r=J.coerce.number();break;case"boolean":r=J.coerce.boolean();break;case"string":default:r=J.string();break}s.format==="uuid"?r=J.string().uuid():s.format==="email"?r=J.string().email():s.format==="date"?r=J.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=J.string().datetime()),s.enum&&(r=J.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Ge,"convertOpenApiSchemaToZod");function La(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(La,"extractPathParameters");function af(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ge(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ge(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=J.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=J.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?d.body=Ge(p,y,o).describe("Request body (JSON)"):d.body=J.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?J.string().describe("Request body (binary/text)"):J.string().optional().describe("Request body (binary/text)"):d.body=J.any().describe("Request body")}const m=Object.keys(d).length>0?J.object(d):J.object({});return{name:l,description:u,parameters:m,async execute(y){try{const p=La(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const R=p.filter(j=>!(j in y.params));if(R.length>0)throw new Error(`Missing required path parameters: ${R.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[R,j]of Object.entries(y.params)){const O=`{${R}}`;w.includes(O)&&(w=w.replace(O,String(j)))}const T=La(w);if(T.length>0)throw new Error(`Unresolved path parameters: ${T.join(", ")}`);const E=new URLSearchParams;if(y.query)for(const[R,j]of Object.entries(y.query))j!=null&&E.append(R,String(j));E.toString()&&(w+=`?${E.toString()}`);const $=await Ma(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${$}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(I.headers["Content-Type"]="application/json",I.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(I.headers["Content-Type"]="application/octet-stream",I.data=y.body):s.requestBody?.content?.["text/plain"]?(I.headers["Content-Type"]="text/plain",I.data=y.body):(I.headers["Content-Type"]="application/json",I.data=y.body));const x=await Ht.request({url:w,...I});return{content:[{type:"text",text:x.data===""?"":JSON.stringify(x.data,null,2)}]}}catch(p){return Ht.isAxiosError(p)?{content:[{type:"text",text:`Error: ${p.response?.data?`HTTP ${p.response.status}: ${p.response.statusText} - ${JSON.stringify(p.response.data)}`:`HTTP ${p.response?.status||"unknown"}: ${p.message}`}`}],isError:!0}:p instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${p.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(af,"createApiTool");function cf(s,e,t,n,r){const i=[];if(!s.paths)return i;const o=s.components||{};for(const[a,l]of Object.entries(s.paths))if(typeof l=="object"&&l!==null){for(const[u,d]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&d&&typeof d=="object"){const f=af(d,a,u,e,t,n,o,r);i.push(f)}}return i}c(cf,"convertOpenApiToTools");function lf(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(`
147
147
  `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=$n();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. Please provide them in the configuration file, command line, or environment variables."),process.exit(1));const t=e.apiUri||or,n=await Ma(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await of(t,n),i=cf(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new Al({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
@@ -152,7 +152,7 @@ ${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),consol
152
152
  `)).action(async()=>{try{q.header("Opening Workspace in Browser"),q.info("Loading configuration...");const e=$n();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");q.info("Retrieving workspace ID...");const t=await Hi(process.cwd()),n=`${e.consoleUri||Ul}/w/${t}`;q.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),q.success("Browser opened successfully")}catch(e){e instanceof Error&&(q.error(e.message),process.exit(1)),q.error("An unknown error occurred"),process.exit(1)}})}c(ff,"setupOpenCommand");async function Yr(s,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;b.debug(`[background-job] Started job ${n}`);const o=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:l=3e5,maxRetries:u=3}=t;let d=0;for(;;){if(Date.now()-o>l)throw new Error(`Background job ${n} timed out after ${l}ms`);await new Promise(m=>setTimeout(m,a));let h;try{h=await s.get(`background-jobs/${i}`),d=0}catch(m){if(m instanceof il&&d<u){d++,b.debug(`[background-job] Job ${n} not found, retrying (${d}/${u})`);continue}throw m}if(h.status==="completed"){if(b.debug(`[background-job] Completed job ${n}`),!h.result)throw new Error(`Background job ${n} completed but returned no result`);return h.result}if(h.status==="failed"){const m=h.failedReason||"Unknown error";throw b.error(`[background-job] Failed job ${n}: ${m}`),h.stacktrace&&b.error(`Stacktrace: ${h.stacktrace.join(`
153
153
  `)}`),new Error(`Background job ${n} failed: ${m}`)}b.debug(`[background-job] Polling job ${n} (status: ${h.status})`)}}c(Yr,"pollBackgroundJob");function hf(s,e){Xr(P.dirname(s)),A.writeFileSync(s,e)}c(hf,"writeFile");function pf(s){A.existsSync(s)&&A.rmSync(s)}c(pf,"deleteFile");function Da(s){A.existsSync(s)&&A.rmSync(s,{recursive:!0,force:!0})}c(Da,"deleteDir");function mf(s,e=!0){if(A.existsSync(s))try{const t=A.readFileSync(s,"utf8");return Se.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=P.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(mf,"readYaml");function ja(s,e,t){try{Xr(P.dirname(s));const n=Se.dump(e,t);A.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=P.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}c(ja,"writeYaml");function Xr(s){A.existsSync(s)||A.mkdirSync(s,{recursive:!0})}c(Xr,"ensureDirExists");function Fa(s,e=!0){if(!A.existsSync(s)||!A.statSync(s).isDirectory())return;let t=A.readdirSync(s);t.length>0&&(t.forEach(n=>Fa(P.join(s,n),!1)),t=A.readdirSync(s)),t.length===0&&!e&&A.rmdirSync(s)}c(Fa,"cleanupEmptyFolders");function gf(s){const e=s.split(/[\\/]/).join("/");return e.endsWith("/")?e+"**":e}c(gf,"normalizePattern");async function qa(s,e=[]){return new Promise(async(t,n)=>{const r=e.map(gf),i=Ri("zip",{zlib:{level:9}}),o=[];i.on("data",l=>o.push(l)),i.on("end",()=>t(Buffer.concat(o))),i.on("error",l=>n(l));const a=new Map;for(const l of s[N.Integration]||[])a.set(l.uuid,l.key);for(const[l,u]of Object.entries(s))for(const d of u){const f=d.key,h=a.get(d.integrationUuid),m=ol(l,f,h);if(r.length>0&&!r.some(p=>Ol(m,p)))continue;const y=Se.dump(d);i.append(y,{name:m})}i.finalize()})}c(qa,"createMembraneZip");async function Zr(s,e){const t=await ji.loadAsync(s),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const o=Qe(r);if(!o)continue;const a=await i.async("string"),l=Se.load(a);if(!l)continue;const u=await e(r,l,o);u!==void 0&&n.push(u)}return n}c(Zr,"iterateZipItems");async function yf(s){const e=await ji.loadAsync(s),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=Qe(n);if(!i)continue;const o=await r.async("string"),a=Se.load(o);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}c(yf,"readMembraneZip");async function Ba(s=process.cwd()){const e=await Ka(pe(s)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}c(Ba,"readMembraneDir");async function Ka(s){const e=Ua(s),t=[];for(const n of e){if(n.isDirectory())continue;const r=Qe(n.path);if(!r)continue;const i=await n.readContent(),o=Se.load(i),a=P.join(s,n.path);t.push({filePath:a,data:o,type:r.type})}return t}c(Ka,"iterateMembraneFiles");function Ua(s,e){const t=[];if(e||(e=s),!A.existsSync(e)||e.startsWith(P.join(s,"connectors")))return t;const n=A.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=P.join(e,r.name),o=P.relative(s,i);r.isDirectory()?t.push(...Ua(s,i)):r.isFile()&&Qe(o)&&t.push({path:o,isDirectory:c(()=>!1,"isDirectory"),readContent:c(async()=>A.readFileSync(i,"utf8"),"readContent")})}return t}c(Ua,"getMembraneFiles");function Wa(){const s={},e=P.join(pe(process.cwd()),"connectors");if(!A.existsSync(e))return s;const t=A.readdirSync(e);for(const n of t){const r=P.join(e,n);if(!A.statSync(r).isDirectory())continue;const i=P.join(r,`${n}.yml`),o=mf(i,!1);if(!o?.uuid)continue;const a=new Set,l=A.readdirSync(r);for(const u of l){if(u.endsWith(".yml"))continue;const d=P.join(r,u);A.statSync(d).isDirectory()&&a.add(u=="development"?"":u)}s[o.uuid]={key:n,id:o.id,versions:Array.from(a)}}return s}c(Wa,"readConnectorsDir");function ps(s,e){const t=P.join(pe(process.cwd()),"connectors",s);return e==""||e===Ai?P.join(t,"development"):e?P.join(t,e):t}c(ps,"getConnectorPath");const Ja=300,Ha=6e4;async function wf(){const s=await F.withClient(async t=>Yr(t,()=>t.get("export"),{pollIntervalMs:Ja,timeoutMs:Ha}));if(!s)throw new Error("Failed to export workspace");const e=await Ht.get(s.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}c(wf,"downloadWorkspaceExport");async function Va(s,e={}){const t=new Mi;t.append("file",s,{filename:"membrane.zip",contentType:"application/zip"});const n=await F.withClient(async i=>{const o=`import?dryRun=${e.dryRun??!1}&partial=${e.partial??!1}`,{jobId:a,accessKey:l}=await i.post(o,t,{headers:t.getHeaders()});return Yr(i,()=>Promise.resolve({jobId:a,accessKey:l}),{pollIntervalMs:1e3,timeoutMs:3e5})});if(!n)throw new Error("Failed to import workspace");const r={};for(const[i,o]of Object.entries(n))r[i]=new Set(o||[]);return r}c(Va,"importWorkspace");async function bf(s,e){const t=await F.withClient(async r=>Yr(r,()=>r.get(`connectors/${s}/export`,{version:e}),{pollIntervalMs:Ja,timeoutMs:Ha}));if(!t)throw new Error("Failed to export connector version");const n=await Ht.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}c(bf,"exportConnector");function Sf(s){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
154
154
  `)).action(async e=>{try{const t=await Cf(e);Tf(t.workspaceExport,t.connectors)}catch(t){_f(t),process.exit(1)}})}c(Sf,"setupPullCommand");async function Cf(s){const e=await Ba(),t=await qa(e),n=await wf(),r=await yf(n),{comparison:i}=al(e,r);i[xe.DELETE].size>0&&!s.force&&(await Ef(i,t),q.error("Use --force to delete local elements"),process.exit(1));const a=await Ka(pe(process.cwd()));for(const{filePath:u,data:d}of a)i[xe.DELETE].has(d.uuid)&&pf(u);return Fa(pe(process.cwd())),await Zr(n,(u,d)=>{if(Qe(u)&&(i[xe.CREATE].has(d.uuid)||i[xe.UPDATE].has(d.uuid))){const h=K.join(pe(process.cwd()),u);ja(h,d)}}),{connectors:await vf(r[N.Integration]),workspaceExport:r}}c(Cf,"pullWorkspace");async function vf(s){const e=new Map;for(const r of s??[]){const{connectorUuid:i,connectorVersion:o}=r;i&&(e.has(i)||e.set(i,new Set),e.get(i).add(o??""))}const t=Wa(),n=new Map;for(const[r,{key:i,versions:o}]of Object.entries(t)){if(!e.has(r)){const u=ps(i);Da(u);continue}const a=e.get(r);for(const u of o)if(!a.has(u)){const d=ps(i,u);Da(d)}const l=new Set(o);for(const u of a)l.has(u)||(n.has(r)||n.set(r,new Set),n.get(r).add(u))}for(const[r,i]of e.entries())t[r]||n.set(r,i);return await Promise.all(Array.from(n.entries()).map(([r,i])=>kf(r,Array.from(i)))),Array.from(n.keys())}c(vf,"pullConnectors");async function kf(s,e){const t=await F.withClient(i=>i.get(`connectors/${s}`),!1);if(!t||!t.key)return;const n=ps(t.key),r=K.join(n,`${t.key}.yml`);ja(r,t);for(const i of e){const o=await bf(s,i),a=ps(t.key,i);if(hf(K.join(a,"src.zip"),o),!i||i===Ai){const l=K.join(a,"src");Xr(l),await(await Li.Open.buffer(o)).extract({path:l})}}}c(kf,"pullConnector");function Tf(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;q.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(s)){const r=s[n];q.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&q.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(Tf,"showStats$1");async function Ef(s,e){const t=s[xe.DELETE].size;q.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await Zr(e,(n,r)=>{Qe(n)&&s[xe.DELETE].has(r.uuid)&&q.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}c(Ef,"showConflicts$1");async function _f(s){q.error("\u25A0 Error"),q.error(`\u2514\u2500\u2500 ${s.message}`),q.error(` ${s.stack}`)}c(_f,"showError$1");const se=[];for(let s=0;s<256;++s)se.push((s+256).toString(16).slice(1));function If(s,e=0){return(se[s[e+0]]+se[s[e+1]]+se[s[e+2]]+se[s[e+3]]+"-"+se[s[e+4]]+se[s[e+5]]+"-"+se[s[e+6]]+se[s[e+7]]+"-"+se[s[e+8]]+se[s[e+9]]+"-"+se[s[e+10]]+se[s[e+11]]+se[s[e+12]]+se[s[e+13]]+se[s[e+14]]+se[s[e+15]]).toLowerCase()}c(If,"unsafeStringify");let Qr;const Af=new Uint8Array(16);function Of(){if(!Qr){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Qr=crypto.getRandomValues.bind(crypto)}return Qr(Af)}c(Of,"rng");const $f=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var za={randomUUID:$f};function Nf(s,e,t){if(za.randomUUID&&!s)return za.randomUUID();s=s||{};const n=s.random??s.rng?.()??Of();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,If(n)}c(Nf,"v4");function xf(s){s.command("push").description("Push workspace data to specified workspace").argument("[files...]","Files, directories, or glob patterns to push").option("--force","Overwrite conflicts with local data",!1).addHelpText("after",["","Examples:"," membrane push # Push all workspace elements"," membrane push data-sources/ # Push all data-sources"," membrane push actions/my-action/spec.yaml # Push specific action"," membrane push flows/*-test/spec.yaml # Push flows matching pattern"," membrane push --force # Overwrite conflicts with local data",""].join(`
155
- `)).action(async(e,t)=>{try{await Pf(e,t)}catch(n){Ff(n),process.exit(1)}})}c(xf,"setupPushCommand");async function Pf(s,e){const t=s.length>0,n=await Ba(),r=Wa(),i=Rf(n,r),o=await qa(i,t?s:void 0),a=await Va(o,{dryRun:!0,partial:t});a[xe.DELETE].size>0&&!e.force&&(await jf(a,o),q.error("Use --force to delete remote elements"),process.exit(1)),await ka(),await Va(o,{partial:t}),Df(i),process.exit(0)}c(Pf,"pushWorkspace");function Rf(s,e){const t=Mf(s),n=Lf(t,e),r={};for(const[i,o]of Object.entries(t)){const a=i,l=Ne[a]?.parentFieldKey||"parentId";r[a]=(o||[]).map(u=>{const d={...u};if(d.integrationId&&!d.integrationUuid&&(d.integrationUuid=n.get(d.integrationId.toString())||d.integrationId,delete d.integrationId),d.connectorId&&!d.connectorUuid){const f=n.get(d.connectorId.toString());f&&(d.connectorUuid=f,delete d.connectorId)}if(d[l]){const f=d[l].toString();d.parentUuid=n.get(f)||f}return delete d.id,d})}return r}c(Rf,"resolveLegacyIdReferences");function Mf(s){const e={};for(const[t,n]of Object.entries(s))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:Nf()});return e}c(Mf,"generateMissingUuids");function Lf(s,e){const t=new Map;for(const n of Object.values(s))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}c(Lf,"buildIdToUuidLookup");function Df(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;q.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(s)){const r=s[n];q.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&q.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(Df,"showStats");async function jf(s,e){const t=s[xe.DELETE].size;q.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Zr(e,(n,r)=>{Qe(n)&&s[xe.DELETE].has(r.uuid)&&q.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}c(jf,"showConflicts");async function Ff(s){q.error("\u25A0 Error"),q.error(`\u2514\u2500\u2500 ${s.message}`),q.error(` ${s.stack}`)}c(Ff,"showError");const ei=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=P.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(A.existsSync(s))try{t=JSON.parse(A.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return A.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=P.join(process.cwd(),".cursor"),e=P.join(s,"mcp.json");A.existsSync(s)||A.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(A.existsSync(e))try{n=JSON.parse(A.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return A.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function qf({onExit:s,onComplete:e}){const[t,n]=H(0),[r,i]=H(!1),[o,a]=H(null),[l,u]=H(""),[d,f]=H("");tt((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(ei.length-1,t+1));else if(p.return||y===" "){const w=ei[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"green",children:"Success"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"green",children:l}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(C,{marginTop:1,paddingLeft:2,children:g(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"red",children:"Error"})]})}),g(C,{flexDirection:"column",paddingLeft:2,children:g(v,{color:"red",children:d})}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Confirmation"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",g(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(C,{marginTop:1,children:g(v,{color:"yellow",bold:!0,children:o.actionDescription})}),g(C,{marginTop:2,marginBottom:1,children:_(v,{children:[g(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Select Agent"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(C,{marginTop:1,flexDirection:"column",children:ei.map((y,p)=>_(C,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(qf,"AddMcpServerScreen");function Bf(){const[s,e]=H(null),[t,n]=H([]),[r,i]=H(null);return pt(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Ve.on(Q.McpStatusChanged,o),Ve.on(Q.McpServersChanged,a),()=>{Ve.off(Q.McpStatusChanged,o),Ve.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Bf,"useMcpStatus");function Kf(){const{error:s,serverCount:e,allMcpServers:t}=Bf(),n=Math.min(100,process.stdout.columns||100);return _(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(C,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(v,{color:"red",children:"error reading status"}):e===0?g(v,{color:"yellow",children:"none"}):g(v,{color:"green",children:e})]})}),!s&&e===0&&g(C,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",g(pl,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(C,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(C,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Kf,"Agent");const Ga=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ya(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ya,"truncateText");function Uf({children:s}){const{state:e,logs:t}=ke();return!e||e===D.NOT_INITIALIZED?_(C,{gap:1,flexDirection:"row",children:[g(Il,{type:"dots"}),g(v,{children:"Initializing..."})]}):e===D.SETTING_UP?g(C,{gap:1,flexDirection:"row",children:g(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===D.ERROR?g(C,{flexDirection:"column",children:t.slice().map((n,r)=>g(v,{color:Ga(n.type),children:n.message},n.timestamp+r))}):s}c(Uf,"EnsureInitialized");function Wf(){const{stats:s}=ke(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(C,{flexDirection:"column",children:[g(C,{children:g(C,{width:12,children:g(v,{color:"grey",children:"Elements:"})})}),g(C,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(C,{children:[g(C,{width:20,children:_(v,{children:[t,":"]})}),g(v,{color:"green",children:n})]},t))})]})}c(Wf,"ElementStats");const ti=5,Jf=6;function Hf(){const{logs:s}=ke(),[e,t]=H(0),n=Math.min(100,process.stdout.columns||100),r=ti,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Jf,u=e<s.length-r,d=e>0;return tt((f,h)=>{if(s.length!==0)if(h.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else h.downArrow?t(m=>Math.max(0,m-1)):(f==="G"||f==="g")&&t(0)}),_(C,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>ti&&g(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>g(C,{marginLeft:1,children:g(v,{color:Ga(f.type),children:Ya(f.message,l)})},f.timestamp+h)),s.length>ti&&_(C,{marginLeft:1,flexDirection:"row",children:[u&&g(v,{color:"grey",children:"\u2191 "}),d&&g(v,{color:"grey",children:"\u2193 "})]})]})}c(Hf,"Logs");const ms=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Vf(){const{state:s,resolveConflicts:e,exit:t}=ke(),[n,r]=H(0),[i,o]=H(!1),[a,l]=H(!1);return tt((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:ms.length-1):d.downArrow?r(f=>f<ms.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),ms[n].value==="sync"?e({watch:!0}):t())}}),pt(()=>{s!==D.CONFLICTS&&i&&o(!1)},[s,i]),_(C,{flexDirection:"column",paddingTop:1,children:[g(C,{children:g(C,{flexDirection:"row",gap:2,children:g(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(C,{children:g(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(C,{marginTop:1,marginLeft:2,children:g(Gf,{isExpanded:a})}),_(C,{marginTop:2,flexDirection:"row",gap:1,children:[g(v,{color:"white",bold:!0,children:"What would you like to do?"}),g(v,{color:"grey",children:"[up/down, enter]"})]}),g(C,{children:i?_(C,{flexDirection:"row",gap:1,children:[g(An,{type:"dots"}),g(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(C,{flexDirection:"column",children:ms.map((u,d)=>g(C,{flexDirection:"column",children:_(C,{flexDirection:"row",gap:1,children:[g(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),g(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Vf,"ResolveChangesUI");const zf={[Pe.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Pe.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Pe.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Gf({isExpanded:s,showControls:e=!0}){const{conflicts:t}=ke(),n=5,r=hl(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return g(C,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=zf[a][l];return _(C,{flexDirection:"column",children:[_(C,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),g(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>g(C,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&g(C,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&g(C,{marginLeft:2,children:g(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Gf,"Conflicts");function Yf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=ke(),i=n?.name,o=i?Ya(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return pt(()=>{r({watch:!0})},[]),_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(C,{marginTop:-1,marginBottom:1,children:_(C,{flexDirection:"row",gap:1,children:[g(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Zf(e),children:[" [",Xf(e),"] "]})]})}),_(C,{children:[g(C,{width:12,children:g(v,{color:"grey",children:"Local:"})}),g(v,{color:"grey",children:process.cwd()})]}),_(C,{children:[g(C,{width:12,children:g(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[g(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?g(Vf,{}):_(In,{children:[g(C,{paddingTop:1,children:g(Wf,{})}),t.length>0&&g(Hf,{})]})]})}c(Yf,"Workspace");function Xf(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(Xf,"getStatusDisplay");function Zf(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Zf,"getStatusColor");const Qf="https://console.integration.app/w";function eh(){const s=Qd(),e=Xs(!0),{exit:t,state:n}=ke(),[r,i]=H(null),o=r??(n===D.SETTING_UP?"setup":"main");tt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Hi(s),u=`${Qf}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$l(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),pt(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(Pa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(qf,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(Ra,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Uf,{children:_(C,{flexDirection:"column",children:[g(C,{flexGrow:1,children:g(Kf,{})}),g(Yf,{}),g(C,{paddingLeft:2,children:g(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(eh,"Main");const th=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
155
+ `)).action(async(e,t)=>{try{await Pf(e,t)}catch(n){Ff(n),process.exit(1)}})}c(xf,"setupPushCommand");async function Pf(s,e){const t=s.length>0,n=await Ba(),r=Wa(),i=Rf(n,r),o=await qa(i,t?s:void 0),a=await Va(o,{dryRun:!0,partial:t});a[xe.DELETE].size>0&&!e.force&&(await jf(a,o),q.error("Use --force to delete remote elements"),process.exit(1)),await ka(),await Va(o,{partial:t}),Df(i),process.exit(0)}c(Pf,"pushWorkspace");function Rf(s,e){const t=Mf(s),n=Lf(t,e),r={};for(const[i,o]of Object.entries(t)){const a=i,l=Ne[a]?.parentFieldKey||"parentId";r[a]=(o||[]).map(u=>{const d={...u};if(d.integrationId&&!d.integrationUuid&&(d.integrationUuid=n.get(d.integrationId.toString())||d.integrationId,delete d.integrationId),d.connectorId){if(!d.connectorUuid){const f=n.get(d.connectorId.toString());f&&(d.connectorUuid=f)}delete d.connectorId}if(d[l]){const f=d[l].toString();d.parentUuid=n.get(f)||f}return a===N.Package&&d.elements&&(d.elements=d.elements.map(f=>{if(f.id&&!f.uuid){const h=n.get(f.id.toString());if(h)return{uuid:h,type:f.type}}return f})),delete d.id,d})}return r}c(Rf,"resolveLegacyIdReferences");function Mf(s){const e={};for(const[t,n]of Object.entries(s))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:Nf()});return e}c(Mf,"generateMissingUuids");function Lf(s,e){const t=new Map;for(const n of Object.values(s))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}c(Lf,"buildIdToUuidLookup");function Df(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;q.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(s)){const r=s[n];q.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&q.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(Df,"showStats");async function jf(s,e){const t=s[xe.DELETE].size;q.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Zr(e,(n,r)=>{Qe(n)&&s[xe.DELETE].has(r.uuid)&&q.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}c(jf,"showConflicts");async function Ff(s){q.error("\u25A0 Error"),q.error(`\u2514\u2500\u2500 ${s.message}`),q.error(` ${s.stack}`)}c(Ff,"showError");const ei=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=P.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(A.existsSync(s))try{t=JSON.parse(A.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return A.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=P.join(process.cwd(),".cursor"),e=P.join(s,"mcp.json");A.existsSync(s)||A.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(A.existsSync(e))try{n=JSON.parse(A.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return A.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function qf({onExit:s,onComplete:e}){const[t,n]=H(0),[r,i]=H(!1),[o,a]=H(null),[l,u]=H(""),[d,f]=H("");tt((y,p)=>{if(l||d){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(ei.length-1,t+1));else if(p.return||y===" "){const w=ei[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"green",children:"Success"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"green",children:l}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(C,{marginTop:1,paddingLeft:2,children:g(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"red",children:"Error"})]})}),g(C,{flexDirection:"column",paddingLeft:2,children:g(v,{color:"red",children:d})}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Confirmation"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",g(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(C,{marginTop:1,children:g(v,{color:"yellow",bold:!0,children:o.actionDescription})}),g(C,{marginTop:2,marginBottom:1,children:_(v,{children:[g(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(C,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Select Agent"})]})}),_(C,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(C,{marginTop:1,flexDirection:"column",children:ei.map((y,p)=>_(C,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(qf,"AddMcpServerScreen");function Bf(){const[s,e]=H(null),[t,n]=H([]),[r,i]=H(null);return pt(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Ve.on(Q.McpStatusChanged,o),Ve.on(Q.McpServersChanged,a),()=>{Ve.off(Q.McpStatusChanged,o),Ve.off(Q.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(Bf,"useMcpStatus");function Kf(){const{error:s,serverCount:e,allMcpServers:t}=Bf(),n=Math.min(100,process.stdout.columns||100);return _(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(C,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(v,{color:"red",children:"error reading status"}):e===0?g(v,{color:"yellow",children:"none"}):g(v,{color:"green",children:e})]})}),!s&&e===0&&g(C,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",g(pl,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(C,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(C,{children:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(C,{marginTop:1,children:g(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Kf,"Agent");const Ga=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ya(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ya,"truncateText");function Uf({children:s}){const{state:e,logs:t}=ke();return!e||e===D.NOT_INITIALIZED?_(C,{gap:1,flexDirection:"row",children:[g(Il,{type:"dots"}),g(v,{children:"Initializing..."})]}):e===D.SETTING_UP?g(C,{gap:1,flexDirection:"row",children:g(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===D.ERROR?g(C,{flexDirection:"column",children:t.slice().map((n,r)=>g(v,{color:Ga(n.type),children:n.message},n.timestamp+r))}):s}c(Uf,"EnsureInitialized");function Wf(){const{stats:s}=ke(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(C,{flexDirection:"column",children:[g(C,{children:g(C,{width:12,children:g(v,{color:"grey",children:"Elements:"})})}),g(C,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(C,{children:[g(C,{width:20,children:_(v,{children:[t,":"]})}),g(v,{color:"green",children:n})]},t))})]})}c(Wf,"ElementStats");const ti=5,Jf=6;function Hf(){const{logs:s}=ke(),[e,t]=H(0),n=Math.min(100,process.stdout.columns||100),r=ti,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Jf,u=e<s.length-r,d=e>0;return tt((f,h)=>{if(s.length!==0)if(h.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else h.downArrow?t(m=>Math.max(0,m-1)):(f==="G"||f==="g")&&t(0)}),_(C,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>ti&&g(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>g(C,{marginLeft:1,children:g(v,{color:Ga(f.type),children:Ya(f.message,l)})},f.timestamp+h)),s.length>ti&&_(C,{marginLeft:1,flexDirection:"row",children:[u&&g(v,{color:"grey",children:"\u2191 "}),d&&g(v,{color:"grey",children:"\u2193 "})]})]})}c(Hf,"Logs");const ms=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Vf(){const{state:s,resolveConflicts:e,exit:t}=ke(),[n,r]=H(0),[i,o]=H(!1),[a,l]=H(!1);return tt((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:ms.length-1):d.downArrow?r(f=>f<ms.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),ms[n].value==="sync"?e({watch:!0}):t())}}),pt(()=>{s!==D.CONFLICTS&&i&&o(!1)},[s,i]),_(C,{flexDirection:"column",paddingTop:1,children:[g(C,{children:g(C,{flexDirection:"row",gap:2,children:g(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(C,{children:g(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(C,{marginTop:1,marginLeft:2,children:g(Gf,{isExpanded:a})}),_(C,{marginTop:2,flexDirection:"row",gap:1,children:[g(v,{color:"white",bold:!0,children:"What would you like to do?"}),g(v,{color:"grey",children:"[up/down, enter]"})]}),g(C,{children:i?_(C,{flexDirection:"row",gap:1,children:[g(An,{type:"dots"}),g(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(C,{flexDirection:"column",children:ms.map((u,d)=>g(C,{flexDirection:"column",children:_(C,{flexDirection:"row",gap:1,children:[g(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),g(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Vf,"ResolveChangesUI");const zf={[Pe.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Pe.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Pe.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Gf({isExpanded:s,showControls:e=!0}){const{conflicts:t}=ke(),n=5,r=hl(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return g(C,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=zf[a][l];return _(C,{flexDirection:"column",children:[_(C,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),g(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>g(C,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&g(C,{marginLeft:2,children:_(v,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&g(C,{marginLeft:2,children:g(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Gf,"Conflicts");function Yf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=ke(),i=n?.name,o=i?Ya(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return pt(()=>{r({watch:!0})},[]),_(C,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(C,{marginTop:-1,marginBottom:1,children:_(C,{flexDirection:"row",gap:1,children:[g(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Zf(e),children:[" [",Xf(e),"] "]})]})}),_(C,{children:[g(C,{width:12,children:g(v,{color:"grey",children:"Local:"})}),g(v,{color:"grey",children:process.cwd()})]}),_(C,{children:[g(C,{width:12,children:g(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[g(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?g(Vf,{}):_(In,{children:[g(C,{paddingTop:1,children:g(Wf,{})}),t.length>0&&g(Hf,{})]})]})}c(Yf,"Workspace");function Xf(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(Xf,"getStatusDisplay");function Zf(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Zf,"getStatusColor");const Qf="https://console.integration.app/w";function eh(){const s=Qd(),e=Xs(!0),{exit:t,state:n}=ke(),[r,i]=H(null),o=r??(n===D.SETTING_UP?"setup":"main");tt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Hi(s),u=`${Qf}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";$l(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),pt(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(Pa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(qf,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(Ra,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Uf,{children:_(C,{flexDirection:"column",children:[g(C,{flexGrow:1,children:g(Kf,{})}),g(Yf,{}),g(C,{paddingLeft:2,children:g(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(eh,"Main");const th=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 Real-time agent mode is experimental and subject to changes. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
156
156
  `),"createExperimentalWarning$1");function nh(s,e){s.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
157
157
  `)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const n=t.rps;!isNaN(n)&&n>0&&n<=1e3?F.init({maxRequestsPerSecond:n}):(b.error(`Invalid RPS value: ${n}. Must be between 1 and 1000.`),process.exit(1))}console.warn(th()),Zs(et.createElement(zr,{cwd:process.cwd(),membraneCLIService:e,children:et.createElement(eh)}))})}c(nh,"setupSyncCommand");class sh{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=ar(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}function L(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}c(L,"__classPrivateFieldSet");function S(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}c(S,"__classPrivateFieldGet");let Xa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Xa=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))},"uuid4");function on(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(on,"isAbortError");const ni=c(s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)},"castToError");class B extends Error{static{c(this,"AnthropicError")}}class ie extends B{static{c(this,"APIError")}constructor(e,t,n,r){super(`${ie.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new gs({message:n,cause:ni(t)});const i=t;return e===400?new Qa(e,i,n,r):e===401?new ec(e,i,n,r):e===403?new tc(e,i,n,r):e===404?new nc(e,i,n,r):e===409?new sc(e,i,n,r):e===422?new rc(e,i,n,r):e===429?new ic(e,i,n,r):e>=500?new oc(e,i,n,r):new ie(e,i,n,r)}}class Te extends ie{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class gs extends ie{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Za extends gs{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Qa extends ie{static{c(this,"BadRequestError")}}class ec extends ie{static{c(this,"AuthenticationError")}}class tc extends ie{static{c(this,"PermissionDeniedError")}}class nc extends ie{static{c(this,"NotFoundError")}}class sc extends ie{static{c(this,"ConflictError")}}class rc extends ie{static{c(this,"UnprocessableEntityError")}}class ic extends ie{static{c(this,"RateLimitError")}}class oc extends ie{static{c(this,"InternalServerError")}}const rh=/^[a-z][a-z0-9+.-]*:/i,ih=c(s=>rh.test(s),"isAbsoluteURL");let si=c(s=>(si=Array.isArray,si(s)),"isArray"),ac=si;function cc(s){return typeof s!="object"?{}:s??{}}c(cc,"maybeObj");function oh(s){if(!s)return!0;for(const e in s)return!1;return!0}c(oh,"isEmptyObj");function ah(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(ah,"hasOwn");const ch=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new B(`${s} must be an integer`);if(e<0)throw new B(`${s} must be a positive integer`);return e},"validatePositiveInteger"),lc=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),lh=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Dt="0.62.0",uh=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function dh(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}c(dh,"getDetectedPlatform");const fh=c(()=>{const s=dh();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dt,"X-Stainless-OS":dc(Deno.build.os),"X-Stainless-Arch":uc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dt,"X-Stainless-OS":dc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":uc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=hh();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Dt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function hh(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}c(hh,"getBrowserInfo");const uc=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),dc=c(s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),"normalizePlatform");let fc;const ph=c(()=>fc??(fc=fh()),"getPlatformHeaders");function mh(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}c(mh,"getDefaultFetch");function hc(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}c(hc,"makeReadableStream");function pc(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return hc({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(pc,"ReadableStreamFrom");function ri(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}c(ri,"ReadableStreamToAsyncIterable");async function gh(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}c(gh,"CancelReadableStream");const yh=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function wh(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}c(wh,"concatBytes");let mc;function ii(s){let e;return(mc??(e=new globalThis.TextEncoder,mc=e.encode.bind(e)))(s)}c(ii,"encodeUTF8");let gc;function yc(s){let e;return(gc??(e=new globalThis.TextDecoder,gc=e.decode.bind(e)))(s)}c(yc,"decodeUTF8");var fe,he;class an{static{c(this,"LineDecoder")}constructor(){fe.set(this,void 0),he.set(this,void 0),L(this,fe,new Uint8Array),L(this,he,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ii(e):e;L(this,fe,wh([S(this,fe,"f"),t]));const n=[];let r;for(;(r=bh(S(this,fe,"f"),S(this,he,"f")))!=null;){if(r.carriage&&S(this,he,"f")==null){L(this,he,r.index);continue}if(S(this,he,"f")!=null&&(r.index!==S(this,he,"f")+1||r.carriage)){n.push(yc(S(this,fe,"f").subarray(0,S(this,he,"f")-1))),L(this,fe,S(this,fe,"f").subarray(S(this,he,"f"))),L(this,he,null);continue}const i=S(this,he,"f")!==null?r.preceding-1:r.preceding,o=yc(S(this,fe,"f").subarray(0,i));n.push(o),L(this,fe,S(this,fe,"f").subarray(r.index)),L(this,he,null)}return n}flush(){return S(this,fe,"f").length?this.decode(`
158
158
  `):[]}}fe=new WeakMap,he=new WeakMap,an.NEWLINE_CHARS=new Set([`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "1.2.5",
3
+ "version": "1.2.6",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",