@membranehq/cli 1.1.9 → 1.1.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +10 -10
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var bc=Object.defineProperty;var c=(s,e)=>bc(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as O,Fragment as Rs}from"react/jsx-runtime";import*as K from"node:path";import{join as Ls,resolve as Sc,dirname as vc}from"node:path";import{useInput as rt,Box as v,Text as C,Newline as Cc,render as bn}from"ink";import kc from"minimist";import{SWRConfig as Tc}from"swr";import it,{createContext as mi,useState as H,useEffect as Ge,useContext as gi,useMemo as _c,useRef as Ec}from"react";import yi from"swr/immutable";import wi from"os";import B from"path";import Oc from"conf";import{MembraneConfigLoader as Ac,MembraneAxiosInstance as Ic,MembraneClient as bi,WorkspaceElementType as
|
|
3
|
-
`);return Mc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new dl;class hl{static{c(this,"RequestLogger")}constructor(e=Ic){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class pl{static{c(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new hl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Ks.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=Cn(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new bi({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const U=new pl;async function Ai(s){const{id:e}=await U.withClient(t=>t.get("org-workspace-id"),s);return e}c(Ai,"getWorkspaceId");var q={},kn={},Ii;function $i(){if(Ii)return kn;Ii=1,Object.defineProperty(kn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),kn.default=s,kn}c($i,"requireJsCamelcase");var Tn={},Ni;function xi(){if(Ni)return Tn;Ni=1,Object.defineProperty(Tn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),Tn.default=s,Tn}c(xi,"requireJsSnakecase");var _n={},Pi;function Mi(){if(Pi)return _n;Pi=1,Object.defineProperty(_n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),_n.default=s,_n}c(Mi,"requireJsPascalcase");var En={},Ri;function ml(){if(Ri)return En;Ri=1,Object.defineProperty(En,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),En.default=s,En}c(ml,"requireJsDotcase");var On={},Li;function gl(){if(Li)return On;Li=1,Object.defineProperty(On,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),On.default=s,On}c(gl,"requireJsPathcase");var An={},Di;function yl(){if(Di)return An;Di=1,Object.defineProperty(An,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),An.default=s,An}c(yl,"requireJsTextcase");var In={},ji;function wl(){if(ji)return In;ji=1,Object.defineProperty(In,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),In.default=s,In}c(wl,"requireJsSentencecase");var $n={},Fi;function bl(){if(Fi)return $n;Fi=1,Object.defineProperty($n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),$n.default=s,$n}c(bl,"requireJsHeadercase");var Nn={},qi;function Ki(){if(qi)return Nn;qi=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),Nn.default=s,Nn}c(Ki,"requireJsKebabcase");var at={},zs={},Bi;function ct(){return Bi||(Bi=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(zs)),zs}c(ct,"requireUtils");var Ui;function Sl(){if(Ui)return at;Ui=1;var s=at&&at.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(at,"__esModule",{value:!0});var e=ct();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"lowerKeys"),at.default=t,at}c(Sl,"requireLowercaseKeysObject");var lt={},Wi;function vl(){if(Wi)return lt;Wi=1;var s=lt&<.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(lt,"__esModule",{value:!0});var e=ct();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"upperKeys"),lt.default=t,lt}c(vl,"requireUppercaseKeysObject");var ut={},Ji;function Cl(){if(Ji)return ut;Ji=1;var s=ut&&ut.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ut,"__esModule",{value:!0});var e=ct(),t=$i();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"camelKeys"),ut.default=n,ut}c(Cl,"requireCamelcaseKeysObject");var ft={},Hi;function kl(){if(Hi)return ft;Hi=1;var s=ft&&ft.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ft,"__esModule",{value:!0});var e=ct(),t=xi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"snakeKeys"),ft.default=n,ft}c(kl,"requireSnakecaseKeysObject");var dt={},Vi;function Tl(){if(Vi)return dt;Vi=1;var s=dt&&dt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(dt,"__esModule",{value:!0});var e=ct(),t=Mi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"pascalKeys"),dt.default=n,dt}c(Tl,"requirePascalcaseKeysObject");var ht={},Gi;function _l(){if(Gi)return ht;Gi=1;var s=ht&&ht.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ht,"__esModule",{value:!0});var e=ct(),t=Ki();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"kebabKeys"),ht.default=n,ht}c(_l,"requireKebabcaseKeysObject");var zi;function El(){if(zi)return q;zi=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=$i();q.toCamelCase=s.default;var e=xi();q.toSnakeCase=e.default;var t=Mi();q.toPascalCase=t.default;var n=ml();q.toDotCase=n.default;var r=gl();q.toPathCase=r.default;var i=yl();q.toTextCase=i.default;var o=wl();q.toSentenceCase=o.default;var a=bl();q.toHeaderCase=a.default;var l=Ki();q.toKebabCase=l.default;var u=Sl();q.lowerKeys=u.default;var f=vl();q.upperKeys=f.default;var d=Cl();q.camelKeys=d.default;var p=kl();q.snakeKeys=p.default;var m=Tl();q.pascalKeys=m.default;var y=_l();q.kebabKeys=y.default;var h=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");q.toLowerCase=h;var w=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");q.toUpperCase=w;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:h,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:p.default,pascalKeys:m.default,kebabKeys:y.default};return q.default=k,q}c(El,"requireLib");var Ys,Yi;function Ol(){return Yi||(Yi=1,Ys=El()),Ys}c(Ol,"requireJsConvertCase");var Al=Ol();const Ae={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},le={[L.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[L.Connector]:{element:"connector",elements:"connectors",exportable:!1},[L.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[L.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[L.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[L.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[L.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[L.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[L.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[L.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Il(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Il,"baseExportCleanup");const $l=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Xi=[L.Action,L.FieldMapping,L.Flow,L.DataSource,L.Package];class Z{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||Z.extractIntegrationKey(r)}get id(){return Z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=De[this.type].apiPath;if(this.integrationKey){const t=De[L.Integration].apiPath;return K.join(t,this.integrationKey,e,this.key)}return K.join(e,this.key)}get path(){return K.join(this.dirPath,"spec.yaml")}get relativePath(){return K.relative(ot(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(ot(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Dc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return $l.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return le?.[this.type]?.parentKey&&(e=le?.[this.type]?.parentKey),e}static new(e,t,n,r){return new Z(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new Z(e,t.key,n,t)}static fromPathAndData(e,t){const n=Z.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?Z.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new Z(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=Z.parsePath(e);if(t)return Z.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===L.Integration?`${e}:${t}`:Z.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(De).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,f=this.getElementTypeFromPath(l);if(f)return{type:f,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:f}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:f,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(L).find(t=>De[t].apiPath===e)}static getRelativePath(e){return K.relative(ot(process.cwd()),e)}static isIntegrationSpecific(e){return Xi.includes(e)}static canBeIntegrationSpecific(e){return Xi.includes(e)}}class Qi{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;setConnectorsMapping(e){this.connectorsMapping=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[L.Integration,L.Connector],r=Object.keys(le),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async deleteElement(e,t){}}function Xs(s,e=!0){if(R.existsSync(s))try{const t=R.readFileSync(s,"utf8");return Dt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Xs,"readYaml");function Nl(s,e,t){try{const n=Dt.dump(e,t);R.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Nl,"writeYaml");class xl extends Qi{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ot(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,De[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,De[L.Integration].apiPath,o.key,De[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=K.join(this.basePath,t.dirPath),r=K.join(this.basePath,t.path);return R.existsSync(n)||R.mkdirSync(n,{recursive:!0}),Nl(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);R.existsSync(t)&&R.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,De[L.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Xs(e);if(t)return Z.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!R.existsSync(e))return t;const n=R.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!R.existsSync(e)||R.readdirSync(e).length>0)return;R.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Pl extends Qi{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!Z.canBeIntegrationSpecific(e))return n;for(const r of t){const i=r.key,o=r.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:i});n.push(...a)}return n.length>0&&b.debug(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await U.withClient(n=>n[le[e.type].element](e.data.id).get(),process.cwd());return Z.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await U.withClient(o=>o[le[e.type].elements].create(n),process.cwd()),i=Z.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await U.withClient(a=>a[le[e.type].element](t.data.id).put(r),process.cwd()),o=Z.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await U.withClient(t=>t[le[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await U.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>Z.fromData(L.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await U.withClient(r=>r[le[t].element](e).get())}catch{return}return Z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===L.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===L.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===L.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===L.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformParentDependency(e,t,n)}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){return(await U.withClient(r=>r[le[e].elements].findAll(t),process.cwd())).filter(r=>r.key).map(r=>Z.fromData(e,r))}}const Qs=Symbol.for("yaml.alias"),Zs=Symbol.for("yaml.document"),je=Symbol.for("yaml.map"),Zi=Symbol.for("yaml.pair"),Te=Symbol.for("yaml.scalar"),pt=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Fe=c(s=>!!s&&typeof s=="object"&&s[pe]===Qs,"isAlias"),ze=c(s=>!!s&&typeof s=="object"&&s[pe]===Zs,"isDocument"),mt=c(s=>!!s&&typeof s=="object"&&s[pe]===je,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[pe]===Zi,"isPair"),J=c(s=>!!s&&typeof s=="object"&&s[pe]===Te,"isScalar$1"),gt=c(s=>!!s&&typeof s=="object"&&s[pe]===pt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[pe]){case je:case pt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[pe]){case Qs:case je:case Te:case pt:return!0}return!1}c(Y,"isNode");const eo=c(s=>(J(s)||z(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),to=Symbol("skip children"),_e=Symbol("remove node");function Ye(s,e){const t=no(e);ze(s)?yt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):yt(null,s,t,Object.freeze([]))}c(Ye,"visit$1"),Ye.BREAK=ce,Ye.SKIP=to,Ye.REMOVE=_e;function yt(s,e,t,n){const r=so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),yt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=yt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=yt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=yt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(yt,"visit_");async function xn(s,e){const t=no(e);ze(s)?await wt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await wt(null,s,t,Object.freeze([]))}c(xn,"visitAsync"),xn.BREAK=ce,xn.SKIP=to,xn.REMOVE=_e;async function wt(s,e,t,n){const r=await so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),wt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await wt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await wt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=await wt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(wt,"visitAsync_");function no(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(no,"initVisitor");function so(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(mt(e))return t.Map?.(s,e,n);if(gt(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(J(e))return t.Scalar?.(s,e,n);if(Fe(e))return t.Alias?.(s,e,n)}c(so,"callVisitor");function ro(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(ze(n))n.contents=t;else{const r=Fe(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(ro,"replaceNode");const Ml={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rl=c(s=>s.replace(/[!,[\]{}]/g,e=>Ml[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Rl(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Y(e.contents)){const i={};Ye(e.contents,(o,a)=>{Y(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
2
|
+
var bc=Object.defineProperty;var c=(s,e)=>bc(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as O,Fragment as Rs}from"react/jsx-runtime";import*as K from"node:path";import{join as Ls,resolve as Sc,dirname as vc}from"node:path";import{useInput as rt,Box as v,Text as C,Newline as Cc,render as bn}from"ink";import kc from"minimist";import{SWRConfig as Tc}from"swr";import it,{createContext as mi,useState as H,useEffect as Ge,useContext as gi,useMemo as _c,useRef as Ec}from"react";import yi from"swr/immutable";import wi from"os";import B from"path";import Oc from"conf";import{MembraneConfigLoader as Ac,MembraneAxiosInstance as Ic,MembraneClient as bi,WorkspaceElementType as R,WorkspaceElementSpecs as De,WorkspaceSyncEventType as $c,ConnectorFileUpdateType as Ds,setValueAtLocator as js,extractMembraneErrorData as ke,getDataCollectionCreateFields as Fs,excludeWriteOnlyFieldsFromSchema as Si,valueToSchema as Sn,getRequiredFieldsFromSchema as Nc,getValueAtLocator as xc,walkSchema as vi,makeDataLocationPath as Ci,getDataCollectionUpdateFields as qs}from"@membranehq/sdk";import Ks from"jsonwebtoken";import*as L from"node:fs";import{mkdirSync as Pc,writeFileSync as Mc,readFileSync as Rc}from"node:fs";import{EventEmitter as Lc}from"events";import Dc from"lodash/isEqual.js";import Dt from"js-yaml";import*as jc from"node:crypto";import{createHash as Fc}from"node:crypto";import qc from"chokidar";import{EventSource as Kc}from"eventsource";import F from"fs";import Bc from"archiver";import Uc from"form-data";import Wc from"unzipper";import*as Jc from"node:os";import{exec as Hc}from"node:child_process";import{Spinner as Vc,TextInput as Gc,Select as zc}from"@inkjs/ui";import vn from"ink-spinner";import Yc from"ink-text-input";import{fileURLToPath as Xc}from"node:url";import T from"chalk";import{Command as Qc}from"commander";import Bs from"lodash/camelCase.js";import Us from"lodash/upperFirst.js";import Zc from"code-block-writer";import el from"lodash/uniqBy.js";import{FastMCP as tl}from"fastmcp";import Ws from"axios";import{z as W}from"zod";import Js from"lodash/merge.js";import{faker as jt}from"@faker-js/faker";import nl from"lodash/template.js";import sl from"lodash/templateSettings.js";const rl="membrane",il="membrane.config.yml",Hs="https://api.integration.app";function Vs(){const s=process.cwd(),e=K.join(s,rl),t=K.join(s,il),n=e,r=K.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(Vs,"getPaths");function ki(){return Vs().membraneDirPath}c(ki,"getBasePath");const ol={pat:{type:"string"},workspace:{type:"object"}},Ti=new Oc({schema:ol,configName:"config",cwd:B.join(wi.homedir(),".membrane")}),al=c(s=>{Ti.set("pat",s)},"setPat"),_i=c(()=>Ti.get("pat"),"getPat");class Ei{static{c(this,"AccountApiClient")}constructor(e=Hs){this.apiBaseUrl=e}async request(e,t={}){const n=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!n.has("Authorization")){const o=_i();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const cl=c(s=>{const e=new Ei(Hs);return t=>e.get(t)},"createAccountApiFetcher");class Pt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Ac}static getInstance(){return Pt.instance||(Pt.instance=new Pt),Pt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const Ft=Pt.getInstance();function Cn(s){return Ft.loadConfig(s)}c(Cn,"readProjectConfig");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Gs extends Lc{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class ll extends Gs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(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 U.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 U.withClient(t=>t.post("/local-clients",{hostname:wi.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 U.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await U.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 Oe=new ll({heartbeatIntervalMs:15e3}),ul="membrane",fl=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ot(s){return K.join(s,ul)}c(ot,"getMembraneDir");const Oi=Ls(ot(process.cwd()),".logs");class dl{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Oe}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Pc(Oi,{recursive:!0});const i=Ls(Oi,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
|
|
3
|
+
`);return Mc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new dl;class hl{static{c(this,"RequestLogger")}constructor(e=Ic){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class pl{static{c(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new hl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Ks.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=Cn(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new bi({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const U=new pl;async function Ai(s){const{id:e}=await U.withClient(t=>t.get("org-workspace-id"),s);return e}c(Ai,"getWorkspaceId");var q={},kn={},Ii;function $i(){if(Ii)return kn;Ii=1,Object.defineProperty(kn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),kn.default=s,kn}c($i,"requireJsCamelcase");var Tn={},Ni;function xi(){if(Ni)return Tn;Ni=1,Object.defineProperty(Tn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),Tn.default=s,Tn}c(xi,"requireJsSnakecase");var _n={},Pi;function Mi(){if(Pi)return _n;Pi=1,Object.defineProperty(_n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),_n.default=s,_n}c(Mi,"requireJsPascalcase");var En={},Ri;function ml(){if(Ri)return En;Ri=1,Object.defineProperty(En,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),En.default=s,En}c(ml,"requireJsDotcase");var On={},Li;function gl(){if(Li)return On;Li=1,Object.defineProperty(On,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),On.default=s,On}c(gl,"requireJsPathcase");var An={},Di;function yl(){if(Di)return An;Di=1,Object.defineProperty(An,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),An.default=s,An}c(yl,"requireJsTextcase");var In={},ji;function wl(){if(ji)return In;ji=1,Object.defineProperty(In,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),In.default=s,In}c(wl,"requireJsSentencecase");var $n={},Fi;function bl(){if(Fi)return $n;Fi=1,Object.defineProperty($n,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),$n.default=s,$n}c(bl,"requireJsHeadercase");var Nn={},qi;function Ki(){if(qi)return Nn;qi=1,Object.defineProperty(Nn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),Nn.default=s,Nn}c(Ki,"requireJsKebabcase");var at={},zs={},Bi;function ct(){return Bi||(Bi=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(zs)),zs}c(ct,"requireUtils");var Ui;function Sl(){if(Ui)return at;Ui=1;var s=at&&at.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(at,"__esModule",{value:!0});var e=ct();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"lowerKeys"),at.default=t,at}c(Sl,"requireLowercaseKeysObject");var lt={},Wi;function vl(){if(Wi)return lt;Wi=1;var s=lt&<.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(lt,"__esModule",{value:!0});var e=ct();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"upperKeys"),lt.default=t,lt}c(vl,"requireUppercaseKeysObject");var ut={},Ji;function Cl(){if(Ji)return ut;Ji=1;var s=ut&&ut.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ut,"__esModule",{value:!0});var e=ct(),t=$i();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"camelKeys"),ut.default=n,ut}c(Cl,"requireCamelcaseKeysObject");var ft={},Hi;function kl(){if(Hi)return ft;Hi=1;var s=ft&&ft.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ft,"__esModule",{value:!0});var e=ct(),t=xi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"snakeKeys"),ft.default=n,ft}c(kl,"requireSnakecaseKeysObject");var dt={},Vi;function Tl(){if(Vi)return dt;Vi=1;var s=dt&&dt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(dt,"__esModule",{value:!0});var e=ct(),t=Mi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"pascalKeys"),dt.default=n,dt}c(Tl,"requirePascalcaseKeysObject");var ht={},Gi;function _l(){if(Gi)return ht;Gi=1;var s=ht&&ht.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(ht,"__esModule",{value:!0});var e=ct(),t=Ki();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"kebabKeys"),ht.default=n,ht}c(_l,"requireKebabcaseKeysObject");var zi;function El(){if(zi)return q;zi=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=$i();q.toCamelCase=s.default;var e=xi();q.toSnakeCase=e.default;var t=Mi();q.toPascalCase=t.default;var n=ml();q.toDotCase=n.default;var r=gl();q.toPathCase=r.default;var i=yl();q.toTextCase=i.default;var o=wl();q.toSentenceCase=o.default;var a=bl();q.toHeaderCase=a.default;var l=Ki();q.toKebabCase=l.default;var u=Sl();q.lowerKeys=u.default;var f=vl();q.upperKeys=f.default;var d=Cl();q.camelKeys=d.default;var p=kl();q.snakeKeys=p.default;var m=Tl();q.pascalKeys=m.default;var y=_l();q.kebabKeys=y.default;var h=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");q.toLowerCase=h;var w=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");q.toUpperCase=w;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:h,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:p.default,pascalKeys:m.default,kebabKeys:y.default};return q.default=k,q}c(El,"requireLib");var Ys,Yi;function Ol(){return Yi||(Yi=1,Ys=El()),Ys}c(Ol,"requireJsConvertCase");var Al=Ol();const Ae={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},le={[R.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[R.Connector]:{element:"connector",elements:"connectors",exportable:!1},[R.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[R.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[R.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[R.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[R.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[R.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[R.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[R.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Il(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Il,"baseExportCleanup");const $l=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Xi=[R.Action,R.FieldMapping,R.Flow,R.DataSource,R.Package];class X{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||X.extractIntegrationKey(r)}get id(){return X.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=De[this.type].apiPath;if(this.integrationKey){const t=De[R.Integration].apiPath;return K.join(t,this.integrationKey,e,this.key)}return K.join(e,this.key)}get path(){return K.join(this.dirPath,"spec.yaml")}get relativePath(){return K.relative(ot(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(ot(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Dc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return $l.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return le?.[this.type]?.parentKey&&(e=le?.[this.type]?.parentKey),e}static new(e,t,n,r){return new X(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new X(e,t.key,n,t)}static fromPathAndData(e,t){const n=X.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?X.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new X(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=X.parsePath(e);if(t)return X.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===R.Integration?`${e}:${t}`:X.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(De).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,f=this.getElementTypeFromPath(l);if(f)return{type:f,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:f}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:f,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(R).find(t=>De[t].apiPath===e)}static getRelativePath(e){return K.relative(ot(process.cwd()),e)}static isIntegrationSpecific(e){return Xi.includes(e)}static canBeIntegrationSpecific(e){return Xi.includes(e)}}class Qi{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[R.Integration,R.Connector],r=Object.keys(le),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async deleteElement(e,t){}}function Xs(s,e=!0){if(L.existsSync(s))try{const t=L.readFileSync(s,"utf8");return Dt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Xs,"readYaml");function Nl(s,e,t){try{const n=Dt.dump(e,t);L.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Nl,"writeYaml");class xl extends Qi{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ot(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,De[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,De[R.Integration].apiPath,o.key,De[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=K.join(this.basePath,t.dirPath),r=K.join(this.basePath,t.path);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),Nl(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,De[R.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Xs(e);if(t)return X.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Pl extends Qi{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=X.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!X.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await U.withClient(n=>n[le[e.type].element](e.data.id).get(),process.cwd());return X.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await U.withClient(o=>o[le[e.type].elements].create(n),process.cwd()),i=X.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await U.withClient(a=>a[le[e.type].element](t.data.id).put(r),process.cwd()),o=X.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await U.withClient(t=>t[le[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await U.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>X.fromData(R.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await U.withClient(r=>r[le[t].element](e).get())}catch{return}return X.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===R.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===R.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===R.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===R.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==R.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){return(await U.withClient(i=>i[le[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),X.fromData(e,i)))}}const Qs=Symbol.for("yaml.alias"),Zs=Symbol.for("yaml.document"),je=Symbol.for("yaml.map"),Zi=Symbol.for("yaml.pair"),Te=Symbol.for("yaml.scalar"),pt=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Fe=c(s=>!!s&&typeof s=="object"&&s[pe]===Qs,"isAlias"),ze=c(s=>!!s&&typeof s=="object"&&s[pe]===Zs,"isDocument"),mt=c(s=>!!s&&typeof s=="object"&&s[pe]===je,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[pe]===Zi,"isPair"),J=c(s=>!!s&&typeof s=="object"&&s[pe]===Te,"isScalar$1"),gt=c(s=>!!s&&typeof s=="object"&&s[pe]===pt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[pe]){case je:case pt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[pe]){case Qs:case je:case Te:case pt:return!0}return!1}c(Y,"isNode");const eo=c(s=>(J(s)||z(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),to=Symbol("skip children"),_e=Symbol("remove node");function Ye(s,e){const t=no(e);ze(s)?yt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):yt(null,s,t,Object.freeze([]))}c(Ye,"visit$1"),Ye.BREAK=ce,Ye.SKIP=to,Ye.REMOVE=_e;function yt(s,e,t,n){const r=so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),yt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=yt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=yt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=yt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(yt,"visit_");async function xn(s,e){const t=no(e);ze(s)?await wt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await wt(null,s,t,Object.freeze([]))}c(xn,"visitAsync"),xn.BREAK=ce,xn.SKIP=to,xn.REMOVE=_e;async function wt(s,e,t,n){const r=await so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),wt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await wt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await wt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=await wt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(wt,"visitAsync_");function no(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(no,"initVisitor");function so(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(mt(e))return t.Map?.(s,e,n);if(gt(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(J(e))return t.Scalar?.(s,e,n);if(Fe(e))return t.Alias?.(s,e,n)}c(so,"callVisitor");function ro(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(ze(n))n.contents=t;else{const r=Fe(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(ro,"replaceNode");const Ml={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rl=c(s=>s.replace(/[!,[\]{}]/g,e=>Ml[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Rl(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&Y(e.contents)){const i={};Ye(e.contents,(o,a)=>{Y(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
|
|
4
4
|
`)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function io(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(io,"anchorIsValid");function oo(s){const e=new Set;return Ye(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(oo,"anchorNames");function ao(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(ao,"findNewAnchor");function Ll(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=oo(s));const o=ao(e,r);return r.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(J(o.node)||z(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}c(Ll,"createNodeAnchors");function bt(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=bt(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=bt(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=bt(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=bt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(bt,"applyReviver");function me(s,e,t){if(Array.isArray(s))return s.map((n,r)=>me(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!eo(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(me,"toJS");class er{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,pe,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!ze(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},a=me(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?bt(i,{"":a},"",a):a}}class Pn extends er{static{c(this,"Alias")}constructor(e){super(Qs),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Ye(e,{Node:c((i,o)=>{(Fe(o)||eo(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(me(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Mn(r,o,n)),a.count*a.aliasCount>i)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(io(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Mn(s,e,t){if(Fe(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(z(e)){let n=0;for(const r of e.items){const i=Mn(s,r,t);i>n&&(n=i)}return n}else if(V(e)){const n=Mn(s,e.key,t),r=Mn(s,e.value,t);return Math.max(n,r)}return 1}c(Mn,"getAliasCount");const co=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class P extends er{static{c(this,"Scalar")}constructor(e){super(Te),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}P.BLOCK_FOLDED="BLOCK_FOLDED",P.BLOCK_LITERAL="BLOCK_LITERAL",P.PLAIN="PLAIN",P.QUOTE_DOUBLE="QUOTE_DOUBLE",P.QUOTE_SINGLE="QUOTE_SINGLE";const Dl="tag:yaml.org,2002:";function jl(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}c(jl,"findTagObject");function qt(s,e,t){if(ze(s)&&(s=s.contents),Y(s))return s;if(V(s)){const d=t.schema[je].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=r(s)),new Pn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Dl+e.slice(2));let u=jl(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new P(s);return l&&(l.node=d),d}u=s instanceof Map?o[je]:Symbol.iterator in Object(s)?o[pt]:o[je]}i&&(i(u),delete t.onTagObj);const f=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new P(s);return e?f.tag=e:u.default||(f.tag=u.tag),l&&(l.node=f),f}c(qt,"createNode");function Rn(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return qt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(Rn,"collectionFromPath");const Kt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class lo extends er{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>Y(n)||V(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Kt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(z(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Rn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(z(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&J(i)?i.value:i:z(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!V(t))return!1;const n=t.value;return n==null||e&&J(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return z(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(z(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Rn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Fl=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ie(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ie,"indentComment");const Xe=c((s,e,t)=>s.endsWith(`
|
|
5
5
|
`)?Ie(t,e):t.includes(`
|
|
6
6
|
`)?`
|
|
@@ -138,17 +138,17 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
138
138
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
139
139
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const 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(Ke(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(ea(t.key)&&!Ke(t.sep,"newline")){const o=Et(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(Ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Et(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]}):Ke(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);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&&!Ke(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start: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||Ke(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const 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=ss(n),i=Et(r);ta(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(`
|
|
140
140
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
141
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=ss(e),n=Et(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=ss(e),n=Et(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 na(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Qo||null,prettyErrors:e}}c(na,"parseOptions");function Fu(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Yn(s,t)),a.warnings.forEach(Yn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Fu,"parseAllDocuments");function sa(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(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 Ze(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Yn(s,t)),o.warnings.forEach(Yn(s,t))),o}c(sa,"parseDocument");function qu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=sa(s,t);if(!r)return null;if(r.warnings.forEach(i=>po(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(qu,"parse");function Ku(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 ze(s)&&!n?s.toString(t):new Lt(s,n,t).toString(t)}c(Ku,"stringify");var Bu=Object.freeze({__proto__:null,Alias:Pn,CST:Lu,Composer:vr,Document:Lt,Lexer:Xo,LineCounter:Qo,Pair:se,Parser:_r,Scalar:P,Schema:$s,YAMLError:mr,YAMLMap:ue,YAMLParseError:Ze,YAMLSeq:qe,YAMLWarning:Do,isAlias:Fe,isCollection:z,isDocument:ze,isMap:mt,isNode:Y,isPair:V,isScalar:J,isSeq:gt,parse:qu,parseAllDocuments:Fu,parseDocument:sa,stringify:Ku,visit:Ye,visitAsync:xn});const fe={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Uu={ignored:fl,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 Wu extends Gs{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ot(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(R.existsSync(this.membraneDir)||R.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=qc.watch(this.membraneDir,Uu),this.watcher.on("add",e=>this.handleFileSystemEvent(fe.Updated,e)).on("change",e=>this.handleFileSystemEvent(fe.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(fe.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(fe.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===fe.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 R.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?Bu.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 jc.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(){R.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=R.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=R.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Er=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Er||{});const Ju={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class Hu extends Gs{static{c(this,"RemoteElementWatcher")}constructor(e=Ju){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 U.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 Kc(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!==$c.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===L.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 ra{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())}}async function Vu(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await U.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>Or("integration",n));for(const n of Object.keys(le)){const r=le[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await U.withClient(a=>a[r.elements].findAll());if(i.push(...o.map(a=>Or(n,a))),r.integrationSpecific)for(const a of t){const l=await U.withClient(u=>u[r.elements].findAll({integrationId:a.id}));i.push(...l.map(u=>(u.integrationKey=a.key,Or(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(Vu,"getWorkspaceData");function Or(s,e){return e=Il(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(Or,"cleanUpForExport");const Ot="connectors",Ne="development",Ar={};async function Gu(){const s=await Vu("minified"),t=(await U.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await U.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=Be(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=B.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(B.join(i,l)),f=await Ir(l);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const m=await $r({connectorId:f.id});m&&m.isPublic&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const m=await U.withClient(y=>y.post("connectors",{...f,workspaceId:t}));n[f.id]=m.id}}const d=u.filter(p=>F.statSync(B.join(i,l,p)).isDirectory());for(const p of d)await Xu({connector:f,version:p,connectorId:n[f.id]})}return n}c(Gu,"pushConnectors");async function ia({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=ki(),o=await $r({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Qu({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Zu({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ia,"pullRemoteConnector");function Be(){const s=Vs();return B.join(s.membraneDirPath,Ot)}c(Be,"getConnectorsPath");async function Ir(s){const e=B.join(Be(),s,`${s}.yml`);return Xs(e,!1)}c(Ir,"readConnector");async function zu(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=Bc("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=F.readdirSync(s);for(const a of o){const l=B.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(zu,"createZipArchive");async function Yu(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Wc.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=B.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(l);i.pipe(f),f.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(Yu,"extractZipArchive");async function Xu({connector:s,version:e,connectorId:t}){const n=B.join(Be(),xe(s),oa(e)),r=B.join(n,"src"),i=B.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await zu(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Uc;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Ne)b.info(`[connectors] Uploading connector ${t}`),await U.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await U.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 U.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(Xu,"pushConnectorVersion");async function $r({connectorId:s}){if(s){if(Ar[s])return Ar[s];try{const e=await U.withClient(t=>t.get(`connectors/${s}`));return Ar[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c($r,"getConnector");async function Qu({basePath:s,connector:e}){const t=xe(e),n=B.join(s,Ot,t);F.mkdirSync(n,{recursive:!0});const r=B.join(n,`${xe(e)}.yml`);F.writeFileSync(r,Dt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Qu,"pullConnector");async function Zu({connector:s,connectorVersion:e,basePath:t}){const n=xe(s),r=oa(e),i=B.join(t,"connectors",n,r),o=await U.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=B.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=B.join(i,"src");F.mkdirSync(l,{recursive:!0}),await Yu(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Zu,"pullConnectorVersion");function xe(s){return s.key}c(xe,"getConnectorDirName");function oa(s){return s??Ne}c(oa,"getConnectorVersionDirName");function ef(s){const e=ki(),t=xe(s);return B.join(e,Ot,t)}c(ef,"getConnectorDirPath");function tf(s){return s.match(`${Ot}/[^/]+/${Ne}/src/.*`)!==null}c(tf,"isConnectorSourceFile");async function nf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await U.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(nf,"putConnectorFile");async function sf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await U.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(sf,"deleteConnectorFile");async function rf(s,e){try{const t=await U.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await U.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=xe(t),i=B.join(Be(),r,Ne,"src",e);F.mkdirSync(B.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.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}`)}}c(rf,"pullConnectorFile");async function of(s,e){const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(of,"deleteLocalConnectorFile");async function af(s,e,t){if(t&&e!==t)try{const n=await U.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=xe(n),i=B.join(Be(),r,Ne,"src"),o=B.join(i,e),a=B.join(i,t);F.existsSync(o)&&(F.mkdirSync(B.dirname(a),{recursive:!0}),F.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(af,"renameLocalConnectorDirectory");async function cf(s,e){try{const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);if(F.existsSync(r)){const i=B.resolve(Be());if(!B.resolve(r).startsWith(i))return;F.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(cf,"deleteLocalConnectorDirectory");const aa=[L.DataSource,L.FieldMapping,L.Action,L.Flow,L.Package,L.AppDataSchema,L.AppEventType];class wn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ra,this.remoteCache=new ra,this.localRepo=new xl(this.localCache),this.remoteRepo=new Pl(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(L.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ia({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await Gu();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Wu({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(fe.Updated,e=>this.handleLocalEvent(e,fe.Updated)),this.localWatcher.on(fe.Deleted,e=>this.handleLocalEvent(e,fe.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Hu,this.remoteWatcher.on(Er.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Er.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(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===L.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await $r({connectorId:o});if(!l?.key)return;const u=ef(l);await this.localWatcher?.executeWithPathLock(u,async()=>ia({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 Ds.ConnectorFileDeleted:await of(e,t);break;case Ds.ConnectorDirectoryRenamed:await af(e,t,r);break;case Ds.ConnectorDirectoryDeleted:await cf(e,t);break;default:await rf(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(tf(e.filePath))switch(t){case fe.Updated:await nf(e.filePath);break;case fe.Deleted:await sf(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(ae.OUTGOING)}] ${Al.toSentenceCase(t)}: ${n.id}`),t){case fe.Updated:await this.updateElement(n,ae.OUTGOING);break;case fe.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=wn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=wn.getChanges(ae.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===L.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==L.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of aa){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 aa){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 Ae.DELETE:return this.deleteElement(e.element,e.direction);case Ae.CREATE:return this.updateElement(e.element,e.direction);case Ae.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),f=n.get(l),d=wn.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Ae.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ae.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ae.UPDATE,element:e,direction:n,isConflict:!1}:null}}const Ue=K.join(Jc.tmpdir(),"membrane-mcp-status"),ca=3e4;class lf{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=rs(void 0,e),n=la(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function rs(s,e){try{const t=e||process.cwd();if(!s){const r=la(t);return r.length===0?null:r[0]}const n=Pr(s,t);if(R.existsSync(n)){const r=R.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ca)return zt(s,t),null;const a=R.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ca)return zt(s,t),null}return l}}catch{s&&e&&zt(s,e)}return null}c(rs,"getMcpStatus");function la(s){try{const e=s||process.cwd(),t=xr(e);if(!R.existsSync(Ue))return[];const n=R.readdirSync(Ue),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=rs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(la,"getAllMcpStatusFiles");function Nr(s){try{const t={...rs(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};R.existsSync(Ue)||R.mkdirSync(Ue,{recursive:!0});const n=Pr(s.processId,s.cwd);R.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Nr,"updateMcpStatus");function zt(s,e){try{const t=e||process.cwd();if(s){const n=Pr(s,t);R.existsSync(n)&&R.unlinkSync(n)}else{const n=xr(t);if(R.existsSync(Ue)){const r=R.readdirSync(Ue);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&R.unlinkSync(K.join(Ue,i))}}}catch{}}c(zt,"clearMcpStatus");function uf(s,e){const t=rs(s,e);t&&Nr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(uf,"trackToolExecution");function xr(s){return Fc("md5").update(s).digest("hex").slice(0,8)}c(xr,"getCwdHash");function Pr(s,e){const t=xr(e);return K.join(Ue,`mcp-${t}-${s}.json`)}c(Pr,"getStatusFilePath");const Yt={Agent:"agent",Cli:"cli"},x={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 ua{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new lf,this.syncService=new wn,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={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(x.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(x.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(x.NOT_INITIALIZED);try{await this.loadConfig(),Ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(x.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(x.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ft.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=Ft.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Yt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Yt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Yt.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 fa=mi(null);function ff({children:s,membraneCLIService:e}){const{data:t}=yi("/account"),[n,r]=H(x.NOT_INITIALIZED),[i,o]=H([]),[a,l]=H({}),[u,f]=H([]),[d,p]=H(null),y=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ge(()=>{const h=c(({state:E})=>r(E),"handleStateChanged"),w=c(({stats:E})=>l(E),"handleStatsChanged"),k=c(({log:E})=>f($=>[...$,E]),"handleLogAdded"),_=c(({conflicts:E})=>o(E),"handleConflictsUpdated"),I=c(({config:E})=>p(E),"handleConfigChanged");return e.notifier.on(X.StateChanged,h),e.notifier.on(X.StatsChanged,w),e.notifier.on(X.LogAdded,k),e.notifier.on(X.ConflictsChanged,_),e.notifier.on(X.ConfigChanged,I),e.init(),()=>{e.notifier.off(X.StateChanged,h),e.notifier.off(X.StatsChanged,w),e.notifier.off(X.LogAdded,k),e.notifier.off(X.ConflictsChanged,_),e.notifier.off(X.ConfigChanged,I)}},[]),g(fa.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:c(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:c(h=>e.pullWorkspace(h),"pull"),push:c(h=>e.pushWorkspace(h),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(ff,"MembraneCLIServiceProvider");function Se(){const s=gi(fa);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(Se,"useMembraneCLIService");const da=mi(process.cwd());function df({cwd:s,children:e}){return g(da.Provider,{value:s,children:e})}c(df,"CwdProvider");function hf(){return gi(da)}c(hf,"useCwd");function is({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(df,{cwd:n,children:g(Tc,{value:{fetcher:cl()},children:g(ff,{membraneCLIService:t,children:e})})})}c(is,"Layout");const Mr=[{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=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(R.existsSync(s))try{t=JSON.parse(R.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return R.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=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");R.existsSync(s)||R.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(R.existsSync(e))try{n=JSON.parse(R.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return R.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function pf({onExit:s,onComplete:e}){const[t,n]=H(0),[r,i]=H(!1),[o,a]=H(null),[l,u]=H(""),[f,d]=H("");rt((y,h)=>{if(l||f){(h.escape||y==="q"||h.return)&&e();return}if(r)h.return||y===" "?p(o):h.escape&&(i(!1),a(null));else if(h.escape)s();else if(h.upArrow||y==="k")n(Math.max(0,t-1));else if(h.downArrow||y==="j")n(Math.min(Mr.length-1,t+1));else if(h.return||y===" "){const w=Mr[t];a(w),i(!0)}});const p=c(y=>{try{const h=y.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"green",children:"Success"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"green",children:l}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(v,{marginTop:1,paddingLeft:2,children:g(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"red",children:"Error"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:g(C,{color:"red",children:f})}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Confirmation"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[O(C,{children:["Connect ",g(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,children:g(C,{color:"yellow",bold:!0,children:o.actionDescription})}),g(v,{marginTop:2,marginBottom:1,children:O(C,{children:[g(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Select Agent"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,flexDirection:"column",children:Mr.map((y,h)=>O(v,{children:[O(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",y.name]}),O(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(pf,"AddMcpServerScreen");function mf(){const[s,e]=H(null),[t,n]=H([]),[r,i]=H(null);return Ge(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(X.McpStatusChanged,o),Oe.on(X.McpServersChanged,a),()=>{Oe.off(X.McpStatusChanged,o),Oe.off(X.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(mf,"useMcpStatus");function gf(){const{error:s,serverCount:e,allMcpServers:t}=mf(),n=Math.min(100,process.stdout.columns||100);return O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(v,{marginTop:-1,marginBottom:0,flexDirection:"column",children:O(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(C,{color:"red",children:"error reading status"}):e===0?g(C,{color:"yellow",children:"none"}):g(C,{color:"green",children:e})]})}),!s&&e===0&&g(v,{marginTop:1,children:O(C,{color:"grey",children:["Connect your AI agents to Membrane.",g(Cc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(v,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(v,{children:O(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(gf,"Agent");const os=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ha(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ha,"truncateText");function Rr({children:s}){const{state:e,logs:t}=Se();return!e||e===x.NOT_INITIALIZED?O(v,{gap:1,flexDirection:"row",children:[g(Vc,{type:"dots"}),g(C,{children:"Initializing..."})]}):e===x.SETTING_UP?g(v,{gap:1,flexDirection:"row",children:g(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===x.ERROR?g(v,{flexDirection:"column",children:t.slice().map((n,r)=>g(C,{color:os(n.type),children:n.message},n.timestamp+r))}):s}c(Rr,"EnsureInitialized");function pa({onExit:s,showEscOption:e=!0}){const[t,n]=H(""),{data:r,error:i,isLoading:o}=yi("/account"),{updateConfig:a}=Se(),l=r?.workspaces,u=o;if(rt((h,w)=>{w.escape&&s?.()}),u)return O(v,{children:[g(vn,{}),g(C,{children:" Fetching workspaces..."})]});if(i)return O(v,{flexDirection:"column",children:[O(C,{color:"red",children:["Error: ",i.message]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,m=l?.length??0;async function y(h){const w=f.find(I=>I.id===h);if(!w)return;const{key:k,secret:_}=w;!k||!_||(await a({workspaceKey:k,workspaceSecret:_}),s?.())}return c(y,"handleSelect"),O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,children:g(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),O(v,{marginTop:1,children:[g(C,{children:"Search: "}),g(Gc,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&O(C,{children:["Showing ",p," of ",m," workspaces."]}),g(v,{marginTop:1,children:g(zc,{options:d,onChange:c(h=>{h&&y(h)},"onChange")})}),e&&g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]})}c(pa,"SelectWorkspace");function yf({currentPat:s,onSubmit:e}){const[t,n]=H(""),[r,i]=H(!1),[o,a]=H(null);return O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,marginBottom:1,children:g(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(C,{children:"Please provide your Personal Access Token. You can find it here:"}),g(v,{marginTop:1,marginBottom:1,children:g(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Yc,{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(v,{marginTop:1,children:O(C,{children:[g(vn,{type:"dots"})," Validating token..."]})}),o&&g(C,{color:"red",children:o})]})}c(yf,"PersonalAccessTokenInput");var Xt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Xt||{});const wf={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Lr=[Xt.Authenticate,Xt.ConnectWorkspace];function ma({onComplete:s}){const{config:e}=Se(),[t,n]=H(!1),[r,i]=H(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=_i(),l=Lr[r],u=r+1,f=Lr.length,d=Lr.map((y,h)=>{let w="pending";return h<r?w="done":h===r&&(w="current"),{id:y,label:wf[y],status:w}});async function p(y){const h=a&&y===""?a:y,w=new Ei;try{await w.request("/account",{headers:{Authorization:`Bearer ${h}`}}),al(h),i(k=>k+1)}catch(k){console.error(k)}}c(p,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),rt((y,h)=>{o&&h.escape&&s&&s()}),t?g(v,{children:g(C,{children:"\u2705 Setup complete. You are ready to go!"})}):O(v,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",O(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&g(C,{color:"grey",children:" [esc: go back]"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:d.map(y=>g(bf,{status:y.status,label:y.label},y.id))})]}),l===Xt.Authenticate&&g(yf,{currentPat:a,onSubmit:p}),l===Xt.ConnectWorkspace&&g(pa,{onExit:m,showEscOption:!1})]})}c(ma,"Setup");function bf({status:s,label:e}){return O(v,{children:[O(v,{width:2,children:[s==="current"&&g(vn,{type:"dots"}),s==="done"&&g(C,{children:"\u2705"})]}),g(C,{dimColor:s!=="current",children:e})]})}c(bf,"StepDisplay");function Dr(){const{stats:s}=Se(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:O(v,{flexDirection:"column",children:[g(v,{children:g(v,{width:12,children:g(C,{color:"grey",children:"Elements:"})})}),g(v,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>O(v,{children:[g(v,{width:20,children:O(C,{children:[t,":"]})}),g(C,{color:"green",children:n})]},t))})]})}c(Dr,"ElementStats");const jr=5,Sf=6;function vf(){const{logs:s}=Se(),[e,t]=H(0),n=Math.min(100,process.stdout.columns||100),r=jr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Sf,u=e<s.length-r,f=e>0;return rt((d,p)=>{if(s.length!==0)if(p.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else p.downArrow?t(m=>Math.max(0,m-1)):(d==="G"||d==="g")&&t(0)}),O(v,{flexDirection:"column",paddingTop:1,children:[O(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>jr&&g(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>g(v,{marginLeft:1,children:g(C,{color:os(d.type),children:ha(d.message,l)})},d.timestamp+p)),s.length>jr&&O(v,{marginLeft:1,flexDirection:"row",children:[u&&g(C,{color:"grey",children:"\u2191 "}),f&&g(C,{color:"grey",children:"\u2193 "})]})]})}c(vf,"Logs");const as=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Cf(){const{state:s,resolveConflicts:e,exit:t}=Se(),[n,r]=H(0),[i,o]=H(!1),[a,l]=H(!1);return rt((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:as.length-1):f.downArrow?r(d=>d<as.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),as[n].value==="sync"?e({watch:!0}):t())}}),Ge(()=>{s!==x.CONFLICTS&&i&&o(!1)},[s,i]),O(v,{flexDirection:"column",paddingTop:1,children:[g(v,{children:g(v,{flexDirection:"row",gap:2,children:g(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(v,{children:g(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(v,{marginTop:1,marginLeft:2,children:g(Fr,{isExpanded:a})}),O(v,{marginTop:2,flexDirection:"row",gap:1,children:[g(C,{color:"white",bold:!0,children:"What would you like to do?"}),g(C,{color:"grey",children:"[up/down, enter]"})]}),g(v,{children:i?O(v,{flexDirection:"row",gap:1,children:[g(vn,{type:"dots"}),g(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(v,{flexDirection:"column",children:as.map((u,f)=>g(v,{flexDirection:"column",children:O(v,{flexDirection:"row",gap:1,children:[g(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),g(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c(Cf,"ResolveChangesUI");const kf={[Ae.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ae.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ae.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Fr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=Se(),n=5,r=_c(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return g(v,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=kf[a][l];return O(v,{flexDirection:"column",children:[O(v,{flexDirection:"row",gap:1,children:[O(C,{color:"yellow",children:[u.label," (",o.length,")"]}),g(C,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>g(v,{marginLeft:2,children:O(C,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&g(v,{marginLeft:2,children:O(C,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&g(v,{marginLeft:2,children:g(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Fr,"Conflicts");function Tf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=Se(),i=n?.name,o=i?ha(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ge(()=>{r({watch:!0})},[]),O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(v,{marginTop:-1,marginBottom:1,children:O(v,{flexDirection:"row",gap:1,children:[g(C,{bold:!0,children:"\u{1F504} Workspace"}),O(C,{color:Ef(e),children:[" [",_f(e),"] "]})]})}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Local:"})}),g(C,{color:"grey",children:process.cwd()})]}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?O(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):O(C,{children:[g(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?g(Cf,{}):O(Rs,{children:[g(v,{paddingTop:1,children:g(Dr,{})}),t.length>0&&g(vf,{})]})]})}c(Tf,"Workspace");function _f(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INITIALIZED:return"initialized";case x.SETTING_UP:return"setup required";default:return"unknown"}}c(_f,"getStatusDisplay");function Ef(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";case x.SETTING_UP:return"yellow";default:return"grey"}}c(Ef,"getStatusColor");const Of="https://console.integration.app/w";function Af(){const s=hf(),e=Ec(!0),{exit:t,state:n}=Se(),[r,i]=H(null),o=r??(n===x.SETTING_UP?"setup":"main");rt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===x.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Ai(s),u=`${Of}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Hc(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ge(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(pa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(pf,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(ma,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Rr,{children:O(v,{flexDirection:"column",children:[g(v,{flexGrow:1,children:g(gf,{})}),g(Tf,{}),g(v,{paddingLeft:2,children:g(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Af,"Main");const Qt=kc(process.argv.slice(2)),ga=Qt.cwd?Sc(Qt.cwd):process.cwd(),If=new ua(Yt.Agent,ga);if(Qt.verbose&&b.setVerboseMode(!0),Qt.rps!==void 0){const s=parseInt(Qt.rps,10);!isNaN(s)&&s>0&&s<=1e3?U.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const $f=c(()=>g(is,{cwd:ga,membraneCLIService:If,children:g(Af,{})}),"App");function Nf(){bn(g($f,{}))}c(Nf,"runAgent");function tt(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>tt({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?tt(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=tt(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(tt)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=tt(s.additionalProperties)),s.required&&(e.required=s.required),e}c(tt,"convertDataSchemaToOpenAPI");function xf(s){const{membraneInterfaces:{actions:e}}=s,t=Pf(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(xf,"generateOpenAPIContent");function Pf(s){const e={};return s.forEach(t=>{const n=Us(Bs(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=tt(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=tt(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Pf,"generateOpenAPISchemas");function Mf(s){const{membraneInterfaces:{actions:e}}=s,t=el(e,"key"),n=new Zc({indentNumberOfSpaces:2,newLine:`
|
|
142
|
-
`});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Rf(n,t),n.toString()}c(Mf,"generateTypeScriptContent");function Rf(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Kr(t),r=t?.inputSchema;cs(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Br(t),o=t?.customOutputSchema||t?.outputSchema;cs(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),cs(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),cs(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Rf,"generateModuleAugmentation");function cs(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&Lf(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(cs,"generateTypeScriptInterface");function Lf(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=qr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Lf,"generateTypeScriptProperties");function qr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?qr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=qr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(qr,"convertJsonSchemaToTypeScript");function Kr(s){return`${Us(Bs(s.key))}Input`}c(Kr,"getInputTypeName");function Br(s){return`${Us(Bs(s.key))}Output`}c(Br,"getOutputTypeName");async function Df(s){const{out:e}=s;await
|
|
141
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=ss(e),n=Et(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=ss(e),n=Et(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 na(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Qo||null,prettyErrors:e}}c(na,"parseOptions");function Fu(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Yn(s,t)),a.warnings.forEach(Yn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Fu,"parseAllDocuments");function sa(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(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 Ze(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Yn(s,t)),o.warnings.forEach(Yn(s,t))),o}c(sa,"parseDocument");function qu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=sa(s,t);if(!r)return null;if(r.warnings.forEach(i=>po(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(qu,"parse");function Ku(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 ze(s)&&!n?s.toString(t):new Lt(s,n,t).toString(t)}c(Ku,"stringify");var Bu=Object.freeze({__proto__:null,Alias:Pn,CST:Lu,Composer:vr,Document:Lt,Lexer:Xo,LineCounter:Qo,Pair:se,Parser:_r,Scalar:P,Schema:$s,YAMLError:mr,YAMLMap:ue,YAMLParseError:Ze,YAMLSeq:qe,YAMLWarning:Do,isAlias:Fe,isCollection:z,isDocument:ze,isMap:mt,isNode:Y,isPair:V,isScalar:J,isSeq:gt,parse:qu,parseAllDocuments:Fu,parseDocument:sa,stringify:Ku,visit:Ye,visitAsync:xn});const fe={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Uu={ignored:fl,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 Wu extends Gs{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ot(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=qc.watch(this.membraneDir,Uu),this.watcher.on("add",e=>this.handleFileSystemEvent(fe.Updated,e)).on("change",e=>this.handleFileSystemEvent(fe.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(fe.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(fe.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===fe.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 L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?Bu.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 jc.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(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Er=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Er||{});const Ju={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class Hu extends Gs{static{c(this,"RemoteElementWatcher")}constructor(e=Ju){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 U.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 Kc(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!==$c.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===R.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 ra{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())}}async function Vu(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await U.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>Or("integration",n));for(const n of Object.keys(le)){const r=le[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await U.withClient(a=>a[r.elements].findAll());if(i.push(...o.map(a=>Or(n,a))),r.integrationSpecific)for(const a of t){const l=await U.withClient(u=>u[r.elements].findAll({integrationId:a.id}));i.push(...l.map(u=>(u.integrationKey=a.key,Or(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(Vu,"getWorkspaceData");function Or(s,e){return e=Il(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(Or,"cleanUpForExport");const Ot="connectors",Ne="development",Ar={};async function Gu(){const s=await Vu("minified"),t=(await U.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await U.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=Be(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=B.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(B.join(i,l)),f=await Ir(l);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const m=await $r({connectorId:f.id});m&&m.isPublic&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const m=await U.withClient(y=>y.post("connectors",{...f,workspaceId:t}));n[f.id]=m.id}}const d=u.filter(p=>F.statSync(B.join(i,l,p)).isDirectory());for(const p of d)await Xu({connector:f,version:p,connectorId:n[f.id]})}return n}c(Gu,"pushConnectors");async function ia({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=ki(),o=await $r({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Qu({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Zu({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ia,"pullRemoteConnector");function Be(){const s=Vs();return B.join(s.membraneDirPath,Ot)}c(Be,"getConnectorsPath");async function Ir(s){const e=B.join(Be(),s,`${s}.yml`);return Xs(e,!1)}c(Ir,"readConnector");async function zu(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=Bc("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=F.readdirSync(s);for(const a of o){const l=B.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(zu,"createZipArchive");async function Yu(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Wc.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=B.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(l);i.pipe(f),f.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(Yu,"extractZipArchive");async function Xu({connector:s,version:e,connectorId:t}){const n=B.join(Be(),xe(s),oa(e)),r=B.join(n,"src"),i=B.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await zu(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Uc;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Ne)b.info(`[connectors] Uploading connector ${t}`),await U.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await U.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 U.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(Xu,"pushConnectorVersion");async function $r({connectorId:s}){if(s){if(Ar[s])return Ar[s];try{const e=await U.withClient(t=>t.get(`connectors/${s}`));return Ar[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c($r,"getConnector");async function Qu({basePath:s,connector:e}){const t=xe(e),n=B.join(s,Ot,t);F.mkdirSync(n,{recursive:!0});const r=B.join(n,`${xe(e)}.yml`);F.writeFileSync(r,Dt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Qu,"pullConnector");async function Zu({connector:s,connectorVersion:e,basePath:t}){const n=xe(s),r=oa(e),i=B.join(t,"connectors",n,r),o=await U.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=B.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=B.join(i,"src");F.mkdirSync(l,{recursive:!0}),await Yu(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Zu,"pullConnectorVersion");function xe(s){return s.key}c(xe,"getConnectorDirName");function oa(s){return s??Ne}c(oa,"getConnectorVersionDirName");function ef(s){const e=ki(),t=xe(s);return B.join(e,Ot,t)}c(ef,"getConnectorDirPath");function tf(s){return s.match(`${Ot}/[^/]+/${Ne}/src/.*`)!==null}c(tf,"isConnectorSourceFile");async function nf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await U.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(nf,"putConnectorFile");async function sf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await U.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(sf,"deleteConnectorFile");async function rf(s,e){try{const t=await U.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await U.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=xe(t),i=B.join(Be(),r,Ne,"src",e);F.mkdirSync(B.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.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}`)}}c(rf,"pullConnectorFile");async function of(s,e){const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(of,"deleteLocalConnectorFile");async function af(s,e,t){if(t&&e!==t)try{const n=await U.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=xe(n),i=B.join(Be(),r,Ne,"src"),o=B.join(i,e),a=B.join(i,t);F.existsSync(o)&&(F.mkdirSync(B.dirname(a),{recursive:!0}),F.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(af,"renameLocalConnectorDirectory");async function cf(s,e){try{const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);if(F.existsSync(r)){const i=B.resolve(Be());if(!B.resolve(r).startsWith(i))return;F.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(cf,"deleteLocalConnectorDirectory");const aa=[R.DataSource,R.FieldMapping,R.Action,R.Flow,R.Package,R.AppDataSchema,R.AppEventType];class wn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ra,this.remoteCache=new ra,this.localRepo=new xl(this.localCache),this.remoteRepo=new Pl(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(R.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ia({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await Gu();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Wu({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(fe.Updated,e=>this.handleLocalEvent(e,fe.Updated)),this.localWatcher.on(fe.Deleted,e=>this.handleLocalEvent(e,fe.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Hu,this.remoteWatcher.on(Er.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Er.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(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===R.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await $r({connectorId:o});if(!l?.key)return;const u=ef(l);await this.localWatcher?.executeWithPathLock(u,async()=>ia({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 Ds.ConnectorFileDeleted:await of(e,t);break;case Ds.ConnectorDirectoryRenamed:await af(e,t,r);break;case Ds.ConnectorDirectoryDeleted:await cf(e,t);break;default:await rf(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(tf(e.filePath))switch(t){case fe.Updated:await nf(e.filePath);break;case fe.Deleted:await sf(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${Al.toSentenceCase(t)}: ${n.id}`),t){case fe.Updated:await this.updateElement(n,ae.OUTGOING);break;case fe.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=wn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=wn.getChanges(ae.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===R.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==R.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of aa){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 aa){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 Ae.DELETE:return this.deleteElement(e.element,e.direction);case Ae.CREATE:return this.updateElement(e.element,e.direction);case Ae.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),f=n.get(l),d=wn.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Ae.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ae.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ae.UPDATE,element:e,direction:n,isConflict:!1}:null}}const Ue=K.join(Jc.tmpdir(),"membrane-mcp-status"),ca=3e4;class lf{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=rs(void 0,e),n=la(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function rs(s,e){try{const t=e||process.cwd();if(!s){const r=la(t);return r.length===0?null:r[0]}const n=Pr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ca)return zt(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ca)return zt(s,t),null}return l}}catch{s&&e&&zt(s,e)}return null}c(rs,"getMcpStatus");function la(s){try{const e=s||process.cwd(),t=xr(e);if(!L.existsSync(Ue))return[];const n=L.readdirSync(Ue),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=rs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(la,"getAllMcpStatusFiles");function Nr(s){try{const t={...rs(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};L.existsSync(Ue)||L.mkdirSync(Ue,{recursive:!0});const n=Pr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Nr,"updateMcpStatus");function zt(s,e){try{const t=e||process.cwd();if(s){const n=Pr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=xr(t);if(L.existsSync(Ue)){const r=L.readdirSync(Ue);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(Ue,i))}}}catch{}}c(zt,"clearMcpStatus");function uf(s,e){const t=rs(s,e);t&&Nr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(uf,"trackToolExecution");function xr(s){return Fc("md5").update(s).digest("hex").slice(0,8)}c(xr,"getCwdHash");function Pr(s,e){const t=xr(e);return K.join(Ue,`mcp-${t}-${s}.json`)}c(Pr,"getStatusFilePath");const Yt={Agent:"agent",Cli:"cli"},x={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 ua{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new lf,this.syncService=new wn,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={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(x.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(x.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(x.NOT_INITIALIZED);try{await this.loadConfig(),Ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(x.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(x.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ft.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=Ft.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Yt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Yt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Yt.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 fa=mi(null);function ff({children:s,membraneCLIService:e}){const{data:t}=yi("/account"),[n,r]=H(x.NOT_INITIALIZED),[i,o]=H([]),[a,l]=H({}),[u,f]=H([]),[d,p]=H(null),y=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ge(()=>{const h=c(({state:E})=>r(E),"handleStateChanged"),w=c(({stats:E})=>l(E),"handleStatsChanged"),k=c(({log:E})=>f($=>[...$,E]),"handleLogAdded"),_=c(({conflicts:E})=>o(E),"handleConflictsUpdated"),I=c(({config:E})=>p(E),"handleConfigChanged");return e.notifier.on(Q.StateChanged,h),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,k),e.notifier.on(Q.ConflictsChanged,_),e.notifier.on(Q.ConfigChanged,I),e.init(),()=>{e.notifier.off(Q.StateChanged,h),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,k),e.notifier.off(Q.ConflictsChanged,_),e.notifier.off(Q.ConfigChanged,I)}},[]),g(fa.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:c(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:c(h=>e.pullWorkspace(h),"pull"),push:c(h=>e.pushWorkspace(h),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(ff,"MembraneCLIServiceProvider");function Se(){const s=gi(fa);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(Se,"useMembraneCLIService");const da=mi(process.cwd());function df({cwd:s,children:e}){return g(da.Provider,{value:s,children:e})}c(df,"CwdProvider");function hf(){return gi(da)}c(hf,"useCwd");function is({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(df,{cwd:n,children:g(Tc,{value:{fetcher:cl()},children:g(ff,{membraneCLIService:t,children:e})})})}c(is,"Layout");const Mr=[{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=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.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=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function pf({onExit:s,onComplete:e}){const[t,n]=H(0),[r,i]=H(!1),[o,a]=H(null),[l,u]=H(""),[f,d]=H("");rt((y,h)=>{if(l||f){(h.escape||y==="q"||h.return)&&e();return}if(r)h.return||y===" "?p(o):h.escape&&(i(!1),a(null));else if(h.escape)s();else if(h.upArrow||y==="k")n(Math.max(0,t-1));else if(h.downArrow||y==="j")n(Math.min(Mr.length-1,t+1));else if(h.return||y===" "){const w=Mr[t];a(w),i(!0)}});const p=c(y=>{try{const h=y.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"green",children:"Success"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"green",children:l}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(v,{marginTop:1,paddingLeft:2,children:g(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"red",children:"Error"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:g(C,{color:"red",children:f})}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Confirmation"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[O(C,{children:["Connect ",g(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,children:g(C,{color:"yellow",bold:!0,children:o.actionDescription})}),g(v,{marginTop:2,marginBottom:1,children:O(C,{children:[g(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Select Agent"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,flexDirection:"column",children:Mr.map((y,h)=>O(v,{children:[O(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",y.name]}),O(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(pf,"AddMcpServerScreen");function mf(){const[s,e]=H(null),[t,n]=H([]),[r,i]=H(null);return Ge(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.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(mf,"useMcpStatus");function gf(){const{error:s,serverCount:e,allMcpServers:t}=mf(),n=Math.min(100,process.stdout.columns||100);return O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(v,{marginTop:-1,marginBottom:0,flexDirection:"column",children:O(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(C,{color:"red",children:"error reading status"}):e===0?g(C,{color:"yellow",children:"none"}):g(C,{color:"green",children:e})]})}),!s&&e===0&&g(v,{marginTop:1,children:O(C,{color:"grey",children:["Connect your AI agents to Membrane.",g(Cc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(v,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(v,{children:O(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(gf,"Agent");const os=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ha(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ha,"truncateText");function Rr({children:s}){const{state:e,logs:t}=Se();return!e||e===x.NOT_INITIALIZED?O(v,{gap:1,flexDirection:"row",children:[g(Vc,{type:"dots"}),g(C,{children:"Initializing..."})]}):e===x.SETTING_UP?g(v,{gap:1,flexDirection:"row",children:g(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===x.ERROR?g(v,{flexDirection:"column",children:t.slice().map((n,r)=>g(C,{color:os(n.type),children:n.message},n.timestamp+r))}):s}c(Rr,"EnsureInitialized");function pa({onExit:s,showEscOption:e=!0}){const[t,n]=H(""),{data:r,error:i,isLoading:o}=yi("/account"),{updateConfig:a}=Se(),l=r?.workspaces,u=o;if(rt((h,w)=>{w.escape&&s?.()}),u)return O(v,{children:[g(vn,{}),g(C,{children:" Fetching workspaces..."})]});if(i)return O(v,{flexDirection:"column",children:[O(C,{color:"red",children:["Error: ",i.message]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,m=l?.length??0;async function y(h){const w=f.find(I=>I.id===h);if(!w)return;const{key:k,secret:_}=w;!k||!_||(await a({workspaceKey:k,workspaceSecret:_}),s?.())}return c(y,"handleSelect"),O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,children:g(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),O(v,{marginTop:1,children:[g(C,{children:"Search: "}),g(Gc,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&O(C,{children:["Showing ",p," of ",m," workspaces."]}),g(v,{marginTop:1,children:g(zc,{options:d,onChange:c(h=>{h&&y(h)},"onChange")})}),e&&g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]})}c(pa,"SelectWorkspace");function yf({currentPat:s,onSubmit:e}){const[t,n]=H(""),[r,i]=H(!1),[o,a]=H(null);return O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,marginBottom:1,children:g(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(C,{children:"Please provide your Personal Access Token. You can find it here:"}),g(v,{marginTop:1,marginBottom:1,children:g(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Yc,{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(v,{marginTop:1,children:O(C,{children:[g(vn,{type:"dots"})," Validating token..."]})}),o&&g(C,{color:"red",children:o})]})}c(yf,"PersonalAccessTokenInput");var Xt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Xt||{});const wf={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Lr=[Xt.Authenticate,Xt.ConnectWorkspace];function ma({onComplete:s}){const{config:e}=Se(),[t,n]=H(!1),[r,i]=H(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=_i(),l=Lr[r],u=r+1,f=Lr.length,d=Lr.map((y,h)=>{let w="pending";return h<r?w="done":h===r&&(w="current"),{id:y,label:wf[y],status:w}});async function p(y){const h=a&&y===""?a:y,w=new Ei;try{await w.request("/account",{headers:{Authorization:`Bearer ${h}`}}),al(h),i(k=>k+1)}catch(k){console.error(k)}}c(p,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),rt((y,h)=>{o&&h.escape&&s&&s()}),t?g(v,{children:g(C,{children:"\u2705 Setup complete. You are ready to go!"})}):O(v,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",O(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&g(C,{color:"grey",children:" [esc: go back]"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:d.map(y=>g(bf,{status:y.status,label:y.label},y.id))})]}),l===Xt.Authenticate&&g(yf,{currentPat:a,onSubmit:p}),l===Xt.ConnectWorkspace&&g(pa,{onExit:m,showEscOption:!1})]})}c(ma,"Setup");function bf({status:s,label:e}){return O(v,{children:[O(v,{width:2,children:[s==="current"&&g(vn,{type:"dots"}),s==="done"&&g(C,{children:"\u2705"})]}),g(C,{dimColor:s!=="current",children:e})]})}c(bf,"StepDisplay");function Dr(){const{stats:s}=Se(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:O(v,{flexDirection:"column",children:[g(v,{children:g(v,{width:12,children:g(C,{color:"grey",children:"Elements:"})})}),g(v,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>O(v,{children:[g(v,{width:20,children:O(C,{children:[t,":"]})}),g(C,{color:"green",children:n})]},t))})]})}c(Dr,"ElementStats");const jr=5,Sf=6;function vf(){const{logs:s}=Se(),[e,t]=H(0),n=Math.min(100,process.stdout.columns||100),r=jr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Sf,u=e<s.length-r,f=e>0;return rt((d,p)=>{if(s.length!==0)if(p.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else p.downArrow?t(m=>Math.max(0,m-1)):(d==="G"||d==="g")&&t(0)}),O(v,{flexDirection:"column",paddingTop:1,children:[O(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>jr&&g(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>g(v,{marginLeft:1,children:g(C,{color:os(d.type),children:ha(d.message,l)})},d.timestamp+p)),s.length>jr&&O(v,{marginLeft:1,flexDirection:"row",children:[u&&g(C,{color:"grey",children:"\u2191 "}),f&&g(C,{color:"grey",children:"\u2193 "})]})]})}c(vf,"Logs");const as=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Cf(){const{state:s,resolveConflicts:e,exit:t}=Se(),[n,r]=H(0),[i,o]=H(!1),[a,l]=H(!1);return rt((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:as.length-1):f.downArrow?r(d=>d<as.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),as[n].value==="sync"?e({watch:!0}):t())}}),Ge(()=>{s!==x.CONFLICTS&&i&&o(!1)},[s,i]),O(v,{flexDirection:"column",paddingTop:1,children:[g(v,{children:g(v,{flexDirection:"row",gap:2,children:g(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(v,{children:g(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(v,{marginTop:1,marginLeft:2,children:g(Fr,{isExpanded:a})}),O(v,{marginTop:2,flexDirection:"row",gap:1,children:[g(C,{color:"white",bold:!0,children:"What would you like to do?"}),g(C,{color:"grey",children:"[up/down, enter]"})]}),g(v,{children:i?O(v,{flexDirection:"row",gap:1,children:[g(vn,{type:"dots"}),g(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(v,{flexDirection:"column",children:as.map((u,f)=>g(v,{flexDirection:"column",children:O(v,{flexDirection:"row",gap:1,children:[g(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),g(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c(Cf,"ResolveChangesUI");const kf={[Ae.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ae.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ae.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Fr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=Se(),n=5,r=_c(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return g(v,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=kf[a][l];return O(v,{flexDirection:"column",children:[O(v,{flexDirection:"row",gap:1,children:[O(C,{color:"yellow",children:[u.label," (",o.length,")"]}),g(C,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>g(v,{marginLeft:2,children:O(C,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&g(v,{marginLeft:2,children:O(C,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&g(v,{marginLeft:2,children:g(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Fr,"Conflicts");function Tf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=Se(),i=n?.name,o=i?ha(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ge(()=>{r({watch:!0})},[]),O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(v,{marginTop:-1,marginBottom:1,children:O(v,{flexDirection:"row",gap:1,children:[g(C,{bold:!0,children:"\u{1F504} Workspace"}),O(C,{color:Ef(e),children:[" [",_f(e),"] "]})]})}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Local:"})}),g(C,{color:"grey",children:process.cwd()})]}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?O(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):O(C,{children:[g(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?g(Cf,{}):O(Rs,{children:[g(v,{paddingTop:1,children:g(Dr,{})}),t.length>0&&g(vf,{})]})]})}c(Tf,"Workspace");function _f(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INITIALIZED:return"initialized";case x.SETTING_UP:return"setup required";default:return"unknown"}}c(_f,"getStatusDisplay");function Ef(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";case x.SETTING_UP:return"yellow";default:return"grey"}}c(Ef,"getStatusColor");const Of="https://console.integration.app/w";function Af(){const s=hf(),e=Ec(!0),{exit:t,state:n}=Se(),[r,i]=H(null),o=r??(n===x.SETTING_UP?"setup":"main");rt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===x.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Ai(s),u=`${Of}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Hc(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ge(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(pa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(pf,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(ma,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Rr,{children:O(v,{flexDirection:"column",children:[g(v,{flexGrow:1,children:g(gf,{})}),g(Tf,{}),g(v,{paddingLeft:2,children:g(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Af,"Main");const Qt=kc(process.argv.slice(2)),ga=Qt.cwd?Sc(Qt.cwd):process.cwd(),If=new ua(Yt.Agent,ga);if(Qt.verbose&&b.setVerboseMode(!0),Qt.rps!==void 0){const s=parseInt(Qt.rps,10);!isNaN(s)&&s>0&&s<=1e3?U.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const $f=c(()=>g(is,{cwd:ga,membraneCLIService:If,children:g(Af,{})}),"App");function Nf(){bn(g($f,{}))}c(Nf,"runAgent");function tt(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>tt({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?tt(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=tt(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(tt)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=tt(s.additionalProperties)),s.required&&(e.required=s.required),e}c(tt,"convertDataSchemaToOpenAPI");function xf(s){const{membraneInterfaces:{actions:e}}=s,t=Pf(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(xf,"generateOpenAPIContent");function Pf(s){const e={};return s.forEach(t=>{const n=Us(Bs(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=tt(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=tt(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Pf,"generateOpenAPISchemas");function Mf(s){const{membraneInterfaces:{actions:e}}=s,t=el(e,"key"),n=new Zc({indentNumberOfSpaces:2,newLine:`
|
|
142
|
+
`});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),Rf(n,t),n.toString()}c(Mf,"generateTypeScriptContent");function Rf(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Kr(t),r=t?.inputSchema;cs(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Br(t),o=t?.customOutputSchema||t?.outputSchema;cs(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),cs(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),cs(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Rf,"generateModuleAugmentation");function cs(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&Lf(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(cs,"generateTypeScriptInterface");function Lf(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=qr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Lf,"generateTypeScriptProperties");function qr(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?qr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=qr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(qr,"convertJsonSchemaToTypeScript");function Kr(s){return`${Us(Bs(s.key))}Input`}c(Kr,"getInputTypeName");function Br(s){return`${Us(Bs(s.key))}Output`}c(Br,"getOutputTypeName");async function Df(s){const{out:e}=s;await L.promises.mkdir(e,{recursive:!0});const t=jf(s);for(const[n,r]of Object.entries(t)){const i=K.join(e,n);await L.promises.writeFile(i,r,"utf-8")}}c(Df,"generateCode");function jf(s){switch(s.target){case"openapi":return{"openapi.json":xf(s)};case"typescript":return{"generated.d.ts":Mf(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(jf,"generateContent");const Ur=c(()=>[T.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"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.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"),T.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.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(`
|
|
143
143
|
`),"createExperimentalWarning$1");function Ff(s,e){s.command("codegen").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk. (Alias: install)").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Ur()).addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${T.gray("\u25B8")} ${T.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Ur()].join(`
|
|
144
|
-
`)).action(async t=>{try{console.warn(Ur()),console.error(T.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await qf(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await Df(r),console.error(T.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(T.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Ff,"setupCodegenCommand");async function qf(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(
|
|
144
|
+
`)).action(async t=>{try{console.warn(Ur()),console.error(T.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await qf(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await Df(r),console.error(T.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(T.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Ff,"setupCodegenCommand");async function qf(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(R.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(qf,"loadMembraneInterfaces");function Kf(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(`
|
|
145
145
|
`)).action(t=>{t.key&&t.secret?Ft.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(ma,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Kf,"setupInitCommand");async function ya(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Ks.sign(n,e)}c(ya,"generateMcpAccessToken");async function Bf(s,e){return(await Ws.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Bf,"fetchOpenApiSchema");function We(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return We(o,e,t,n)}return W.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]=We(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=We(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=We(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?We(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.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(We,"convertOpenApiSchemaToZod");function wa(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(wa,"extractPathParameters");function Uf(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}`,f={},d={},p={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")d[y.name]=We(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const h=y.required===!0;p[y.name]=We(y.schema,h,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(d).length>0&&(f.params=W.object(d).describe("Path parameters")),Object.keys(p).length>0&&(f.query=W.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const h=s.requestBody.content["application/json"].schema;h?f.body=We(h,y,o).describe("Request body (JSON)"):f.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?f.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):f.body=W.any().describe("Request body")}const m=Object.keys(f).length>0?W.object(f):W.object({});return{name:l,description:u,parameters:m,async execute(y){try{const h=wa(e);if(h.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const N=h.filter(D=>!(D in y.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[N,D]of Object.entries(y.params)){const A=`{${N}}`;w.includes(A)&&(w=w.replace(A,String(D)))}const k=wa(w);if(k.length>0)throw new Error(`Unresolved path parameters: ${k.join(", ")}`);const _=new URLSearchParams;if(y.query)for(const[N,D]of Object.entries(y.query))D!=null&&_.append(N,String(D));_.toString()&&(w+=`?${_.toString()}`);const I=await ya(r,i,a),E={method:t.toUpperCase(),headers:{Authorization:`Bearer ${I}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(E.headers["Content-Type"]="application/json",E.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(E.headers["Content-Type"]="application/octet-stream",E.data=y.body):s.requestBody?.content?.["text/plain"]?(E.headers["Content-Type"]="text/plain",E.data=y.body):(E.headers["Content-Type"]="application/json",E.data=y.body));const $=await Ws.request({url:w,...E});return{content:[{type:"text",text:$.data===""?"":JSON.stringify($.data,null,2)}]}}catch(h){return Ws.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Uf,"createApiTool");function Wf(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,f]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&f&&typeof f=="object"){const d=Uf(f,a,u,e,t,n,o,r);i.push(d)}}return i}c(Wf,"convertOpenApiToTools");function Jf(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(`
|
|
146
146
|
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Cn();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||Hs,n=await ya(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Bf(t,n),i=Wf(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new tl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
|
147
147
|
Use it for anything related to Membrane or integrations.
|
|
148
|
-
`,version:"1.0.0"});for(const u of i){const f=u.execute;u.execute=async d=>(uf(process.pid,process.cwd()),f(d)),o.addTool(u)}Nr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Nr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),zt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{zt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Jf,"setupMcpCommand");const Hf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Vf={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class
|
|
148
|
+
`,version:"1.0.0"});for(const u of i){const f=u.execute;u.execute=async d=>(uf(process.pid,process.cwd()),f(d)),o.addTool(u)}Nr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{Nr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),zt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{zt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Jf,"setupMcpCommand");const Hf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Vf={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class Z{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${T.gray(new Date().toISOString())} `:"",i=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=Hf[t],l=Vf[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${T.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(T.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
149
149
|
${T.red(t.error)}`:""):console.debug(T.gray(e),t?.error?`
|
|
150
150
|
${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function Gf(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
|
|
151
|
-
`)).action(async()=>{try{
|
|
151
|
+
`)).action(async()=>{try{Z.header("Opening Workspace in Browser"),Z.info("Loading configuration...");const e=Cn();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");Z.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Ai(process.cwd())}`;Z.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),Z.success("Browser opened successfully")}catch(e){e instanceof Error&&(Z.error(e.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(Gf,"setupOpenCommand");function zf(s){return g(Rr,{children:g(Yf,{options:s})})}c(zf,"Pull");function Yf({options:s}){const{logs:e,state:t,conflicts:n,pull:r}=Se();Ge(()=>{r(s)},[]);const i=t===x.CONFLICTS;return O(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:os(o.type),children:o.message},o.timestamp+a)),i&&O(Rs,{children:[O(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Fr,{isExpanded:!s.watch,showControls:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Dr,{})]})}c(Yf,"PullActivity");function ba(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(ba,"getWatchModeCallback");function Xf(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically"," membrane pull --rps 5 # Limit to 5 requests per second",""].join(`
|
|
152
152
|
`)).action(async t=>{const n=t.watch?ba():()=>process.exit(0);bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(zf,{...t,onComplete:n})}))})}c(Xf,"setupPullCommand");function Qf(s){return g(Rr,{children:g(Zf,{options:s})})}c(Qf,"Push");function Zf({options:s}){const{logs:e,state:t,conflicts:n,push:r}=Se();Ge(()=>{r(s)},[]);const i=t===x.CONFLICTS;return O(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:os(o.type),children:o.message},o.timestamp+a)),i&&O(Rs,{children:[O(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Fr,{isExpanded:!s.watch,showControls:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Dr,{})]})}c(Zf,"PushActivity");function ed(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data"," membrane push --rps 5 # Limit to 5 requests per second",""].join(`
|
|
153
153
|
`)).action(async t=>{const n=t.watch?ba():()=>process.exit(0);bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(Qf,{...t,onComplete:n})}))})}c(ed,"setupPushCommand");class td{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=Vs(),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 M(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(M,"__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 Sa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Sa=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 Zt(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(Zt,"isAbortError");const Wr=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 j extends Error{static{c(this,"AnthropicError")}}class re extends j{static{c(this,"APIError")}constructor(e,t,n,r){super(`${re.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 ls({message:n,cause:Wr(t)});const i=t;return e===400?new Ca(e,i,n,r):e===401?new ka(e,i,n,r):e===403?new Ta(e,i,n,r):e===404?new _a(e,i,n,r):e===409?new Ea(e,i,n,r):e===422?new Oa(e,i,n,r):e===429?new Aa(e,i,n,r):e>=500?new Ia(e,i,n,r):new re(e,i,n,r)}}class ve extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ls extends re{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class va extends ls{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ca extends re{static{c(this,"BadRequestError")}}class ka extends re{static{c(this,"AuthenticationError")}}class Ta extends re{static{c(this,"PermissionDeniedError")}}class _a extends re{static{c(this,"NotFoundError")}}class Ea extends re{static{c(this,"ConflictError")}}class Oa extends re{static{c(this,"UnprocessableEntityError")}}class Aa extends re{static{c(this,"RateLimitError")}}class Ia extends re{static{c(this,"InternalServerError")}}const nd=/^[a-z][a-z0-9+.-]*:/i,sd=c(s=>nd.test(s),"isAbsoluteURL");let Jr=c(s=>(Jr=Array.isArray,Jr(s)),"isArray"),$a=Jr;function Na(s){return typeof s!="object"?{}:s??{}}c(Na,"maybeObj");function rd(s){if(!s)return!0;for(const e in s)return!1;return!0}c(rd,"isEmptyObj");function id(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(id,"hasOwn");const od=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new j(`${s} must be an integer`);if(e<0)throw new j(`${s} must be a positive integer`);return e},"validatePositiveInteger"),xa=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),ad=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),At="0.62.0",cd=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function ld(){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(ld,"getDetectedPlatform");const ud=c(()=>{const s=ld();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":Ma(Deno.build.os),"X-Stainless-Arch":Pa(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":At,"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":At,"X-Stainless-OS":Ma(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Pa(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=fd();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"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":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function fd(){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(fd,"getBrowserInfo");const Pa=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),Ma=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 Ra;const dd=c(()=>Ra??(Ra=ud()),"getPlatformHeaders");function hd(){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(hd,"getDefaultFetch");function La(...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(La,"makeReadableStream");function Da(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return La({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(Da,"ReadableStreamFrom");function Hr(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(Hr,"ReadableStreamToAsyncIterable");async function pd(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(pd,"CancelReadableStream");const md=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function gd(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(gd,"concatBytes");let ja;function Vr(s){let e;return(ja??(e=new globalThis.TextEncoder,ja=e.encode.bind(e)))(s)}c(Vr,"encodeUTF8");let Fa;function qa(s){let e;return(Fa??(e=new globalThis.TextDecoder,Fa=e.decode.bind(e)))(s)}c(qa,"decodeUTF8");var de,he;class en{static{c(this,"LineDecoder")}constructor(){de.set(this,void 0),he.set(this,void 0),M(this,de,new Uint8Array),M(this,he,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Vr(e):e;M(this,de,gd([S(this,de,"f"),t]));const n=[];let r;for(;(r=yd(S(this,de,"f"),S(this,he,"f")))!=null;){if(r.carriage&&S(this,he,"f")==null){M(this,he,r.index);continue}if(S(this,he,"f")!=null&&(r.index!==S(this,he,"f")+1||r.carriage)){n.push(qa(S(this,de,"f").subarray(0,S(this,he,"f")-1))),M(this,de,S(this,de,"f").subarray(S(this,he,"f"))),M(this,he,null);continue}const i=S(this,he,"f")!==null?r.preceding-1:r.preceding,o=qa(S(this,de,"f").subarray(0,i));n.push(o),M(this,de,S(this,de,"f").subarray(r.index)),M(this,he,null)}return n}flush(){return S(this,de,"f").length?this.decode(`
|
|
154
154
|
`):[]}}de=new WeakMap,he=new WeakMap,en.NEWLINE_CHARS=new Set([`
|
|
@@ -352,9 +352,9 @@ ${JSON.stringify(r,null,2)}`).join(`
|
|
|
352
352
|
|
|
353
353
|
`)}.
|
|
354
354
|
|
|
355
|
-
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return vi(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ci(r);n[i]=await this.fetchExampleRecords(r)}return n}}const di={spec:{testerClass:Yd},create:{testerClass:Wd,operationKey:"create"},"find-by-id":{testerClass:Hd,operationKey:"findById"},list:{testerClass:Vd,operationKey:"list"},match:{testerClass:Gd,operationKey:"match"},search:{testerClass:zd,operationKey:"search"},update:{testerClass:Xd,operationKey:"update"},delete:{testerClass:Jd,operationKey:"delete"}};class Qd extends Ud{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);
|
|
356
|
-
`),"createExperimentalWarning");function eh(s){s.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",Is()).action(async()=>{console.warn(Is()),
|
|
357
|
-
`)).action(async(t,n)=>{try{console.warn(Is()),t||(
|
|
355
|
+
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return vi(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=Ci(r);n[i]=await this.fetchExampleRecords(r)}return n}}const di={spec:{testerClass:Yd},create:{testerClass:Wd,operationKey:"create"},"find-by-id":{testerClass:Hd,operationKey:"findById"},list:{testerClass:Vd,operationKey:"list"},match:{testerClass:Gd,operationKey:"match"},search:{testerClass:zd,operationKey:"search"},update:{testerClass:Xd,operationKey:"update"},delete:{testerClass:Jd,operationKey:"delete"}};class Qd extends Ud{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);Z.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=di[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(di).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const n={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(n)}getAvailableTestMethods(e){return Object.entries(di).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){Z.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Zd extends td{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){Z.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(Z.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(Z.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),Z.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,f=[...a,...t?t.split("/"):[]].join("/"),d=await hi.create({connectionId:l,testBasePath:u,options:{fix:n}}),m=await d.client.get(`connections/${l}/data`),y=[],h=f?f.split("/"):[];if(h.length===0||h[0]==="data"){h[0]==="data"&&h.shift();let k,_;h.length>=1&&(_=h[0],h.length>=2&&h[1].trim()!==""&&(k=h[1]));for(const I of m){if(_&&_!==I.key)continue;const E=new Qd({environment:d,dataCollectionKey:I.key,testMethod:k});y.push(E)}}y.length===0&&(Z.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const w={};for(const k of y){await k.run();const _=k.getResult();Z.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Js(w,_)}console.debug("[TestRunner] All results collected:",Object.keys(w)),d.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Is=c(()=>[T.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"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.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"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.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(`
|
|
356
|
+
`),"createExperimentalWarning");function eh(s){s.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",Is()).action(async()=>{console.warn(Is()),Z.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",Is()].join(`
|
|
357
|
+
`)).action(async(t,n)=>{try{console.warn(Is()),t||(Z.error("Test path is required"),process.exit(1)),Z.header(`Testing: ${t}`);const r=new Zd({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),Z.success("Tests completed")}catch(r){r instanceof Error&&(Z.error(r.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(eh,"setupTestCommand");const th=c(()=>{try{const s=Xc(import.meta.url),e=vc(s),t=Ls(e,"..","package.json");return JSON.parse(Rc(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),yc=th();function nh(){const s=new Qc().name("membrane").description("Command-line interface for Membrane Agent").version(yc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>T.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${T.cyan(n.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${T.gray("\u25B8")} ${T.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>T.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>T.gray(n.description),"optionDescription"),commandDescription:c(n=>T.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
|
|
358
358
|
${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${yc}`)}
|
|
359
359
|
|
|
360
360
|
`);const e=new ua(Yt.Cli,process.cwd());Xf(s,e),ed(s,e),Kf(s,e),Ff(s,e),Gf(s),eh(s),Jf(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(nh,"runCLI");const wc=["--cwd","--verbose"];function sh(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&wc.includes(s[t-1])?!1:!wc.includes(e))}c(sh,"hasCLIArguments"),sh()?nh():Nf();
|