@membranehq/cli 0.10.18 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +33 -33
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- var Nr=Object.defineProperty;var l=(s,e)=>Nr(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as yn}from"react/jsx-runtime";import*as _ from"node:path";import{resolve as $r,dirname as Pr,join as Lr}from"node:path";import{useInput as De,Box as b,Text as S,Newline as xr,render as Tt}from"ink";import Dr from"minimist";import{SWRConfig as _r}from"swr";import _e,{createContext as vs,useState as B,useEffect as Ee,useContext as ks,useMemo as Rr,useRef as Mr}from"react";import Ts from"swr/immutable";import{MembraneConfigLoader as jr,WorkspaceElementType as R,WorkspaceElementSpecs as we,MembraneClient as Es,WorkspaceSyncEventType as Kr,setValueAtLocator as wn,extractMembraneErrorData as ue,getDataCollectionCreateFields as bn,excludeWriteOnlyFieldsFromSchema as Is,valueToSchema as Et,getRequiredFieldsFromSchema as Fr,getValueAtLocator as Br,walkSchema as Os,makeDataLocationPath as As,getDataCollectionUpdateFields as Sn}from"@membranehq/sdk";import qr from"lodash/isEqual.js";import*as x from"node:fs";import{readFileSync as Ur}from"node:fs";import Ie from"js-yaml";import Ns from"os";import{EventEmitter as Jr}from"events";import U from"path";import Wr from"conf";import Cn from"jsonwebtoken";import*as Vr from"node:crypto";import{createHash as Gr}from"node:crypto";import zr from"chokidar";import{EventSource as Hr}from"eventsource";import M from"fs";import Yr from"archiver";import Zr from"form-data";import Qr from"unzipper";import*as Xr from"node:os";import{exec as eo}from"node:child_process";import{Spinner as to,TextInput as no,Select as so}from"@inkjs/ui";import It from"ink-spinner";import io from"ink-text-input";import{fileURLToPath as ro}from"node:url";import k from"chalk";import{Command as oo}from"commander";import vn from"axios";import{FastMCP as ao}from"fastmcp";import{z as Z}from"zod";import kn from"lodash/merge.js";import co from"@anthropic-ai/sdk";import{faker as ot}from"@faker-js/faker";import lo from"lodash/template.js";import uo from"lodash/templateSettings.js";class nt{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new jr}static getInstance(){return nt.instance||(nt.instance=new nt),nt.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 at=nt.getInstance();var D={},Ot={},$s;function Ps(){if($s)return Ot;$s=1,Object.defineProperty(Ot,"__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,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toCamelCase"),Ot.default=s,Ot}l(Ps,"requireJsCamelcase");var At={},Ls;function xs(){if(Ls)return At;Ls=1,Object.defineProperty(At,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(s,"toSnakeCase"),At.default=s,At}l(xs,"requireJsSnakecase");var Nt={},Ds;function _s(){if(Ds)return Nt;Ds=1,Object.defineProperty(Nt,"__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,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toPascalCase"),Nt.default=s,Nt}l(_s,"requireJsPascalcase");var $t={},Rs;function fo(){if(Rs)return $t;Rs=1,Object.defineProperty($t,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(s,"toDotCase"),$t.default=s,$t}l(fo,"requireJsDotcase");var Pt={},Ms;function ho(){if(Ms)return Pt;Ms=1,Object.defineProperty(Pt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(s,"toPathCase"),Pt.default=s,Pt}l(ho,"requireJsPathcase");var Lt={},js;function po(){if(js)return Lt;js=1,Object.defineProperty(Lt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(s,"toTextCase"),Lt.default=s,Lt}l(po,"requireJsTextcase");var xt={},Ks;function mo(){if(Ks)return xt;Ks=1,Object.defineProperty(xt,"__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,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(s,"toSentenceCase"),xt.default=s,xt}l(mo,"requireJsSentencecase");var Dt={},Fs;function go(){if(Fs)return Dt;Fs=1,Object.defineProperty(Dt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,i,r){return n+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(s,"toHeaderCase"),Dt.default=s,Dt}l(go,"requireJsHeadercase");var _t={},Bs;function qs(){if(Bs)return _t;Bs=1,Object.defineProperty(_t,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(s,"toKebabCase"),_t.default=s,_t}l(qs,"requireJsKebabcase");var Re={},Tn={},Us;function Me(){return Us||(Us=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})}}(Tn)),Tn}l(Me,"requireUtils");var Js;function yo(){if(Js)return Re;Js=1;var s=Re&&Re.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(Re,"__esModule",{value:!0});var e=Me();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var h=t({key:u},i);f=h.key}return f}))),r[c]=a}),r}return l(t,"lowerKeys"),Re.default=t,Re}l(yo,"requireLowercaseKeysObject");var je={},Ws;function wo(){if(Ws)return je;Ws=1;var s=je&&je.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(je,"__esModule",{value:!0});var e=Me();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var h=t({key:u},i);f=h.key}return f}))),r[c]=a}),r}return l(t,"upperKeys"),je.default=t,je}l(wo,"requireUppercaseKeysObject");var Ke={},Vs;function bo(){if(Vs)return Ke;Vs=1;var s=Ke&&Ke.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Ke,"__esModule",{value:!0});var e=Me(),t=Ps();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"camelKeys"),Ke.default=n,Ke}l(bo,"requireCamelcaseKeysObject");var Fe={},Gs;function So(){if(Gs)return Fe;Gs=1;var s=Fe&&Fe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Fe,"__esModule",{value:!0});var e=Me(),t=xs();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"snakeKeys"),Fe.default=n,Fe}l(So,"requireSnakecaseKeysObject");var Be={},zs;function Co(){if(zs)return Be;zs=1;var s=Be&&Be.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Be,"__esModule",{value:!0});var e=Me(),t=_s();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"pascalKeys"),Be.default=n,Be}l(Co,"requirePascalcaseKeysObject");var qe={},Hs;function vo(){if(Hs)return qe;Hs=1;var s=qe&&qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Me(),t=qs();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"kebabKeys"),qe.default=n,qe}l(vo,"requireKebabcaseKeysObject");var Ys;function ko(){if(Ys)return D;Ys=1,Object.defineProperty(D,"__esModule",{value:!0}),D.kebabKeys=D.pascalKeys=D.snakeKeys=D.camelKeys=D.upperKeys=D.lowerKeys=D.toLowerCase=D.toUpperCase=D.toKebabCase=D.toHeaderCase=D.toSentenceCase=D.toTextCase=D.toPathCase=D.toDotCase=D.toPascalCase=D.toSnakeCase=D.toCamelCase=void 0;var s=Ps();D.toCamelCase=s.default;var e=xs();D.toSnakeCase=e.default;var t=_s();D.toPascalCase=t.default;var n=fo();D.toDotCase=n.default;var i=ho();D.toPathCase=i.default;var r=po();D.toTextCase=r.default;var o=mo();D.toSentenceCase=o.default;var a=go();D.toHeaderCase=a.default;var c=qs();D.toKebabCase=c.default;var u=yo();D.lowerKeys=u.default;var f=wo();D.upperKeys=f.default;var h=bo();D.camelKeys=h.default;var p=So();D.snakeKeys=p.default;var g=Co();D.pascalKeys=g.default;var w=vo();D.kebabKeys=w.default;var d=l(function(v){return String(v||"").toLowerCase()},"toLowerCase");D.toLowerCase=d;var y=l(function(v){return String(v||"").toUpperCase()},"toUpperCase");D.toUpperCase=y;var C={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:d,lowerKeys:u.default,upperKeys:f.default,camelKeys:h.default,snakeKeys:p.default,pascalKeys:g.default,kebabKeys:w.default};return D.default=C,D}l(ko,"requireLib");var En,Zs;function To(){return Zs||(Zs=1,En=ko()),En}l(To,"requireJsConvertCase");var Eo=To();const de={UPDATE:"update",DELETE:"delete",CREATE:"create"},ee={INCOMING:"incoming",OUTGOING:"outgoing"},ne={[R.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(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:l(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:l(s=>(delete s.dataSourceId,s),"exportCleanup")},[R.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Io(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}l(Io,"baseExportCleanup");const Oo="membrane",Ao=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function ct(s){return _.join(s,Oo)}l(ct,"getMembraneDir");const No=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Qs=[R.Action,R.FieldMapping,R.Flow,R.DataSource];class z{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||z.extractIntegrationKey(i)}get id(){return z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[R.Integration].apiPath;return _.join(t,this.integrationKey,e,this.key)}return _.join(e,this.key)}get path(){return _.join(this.dirPath,"spec.yaml")}get relativePath(){return _.relative(ct(process.cwd()),this.path)}get absolutePath(){return _.resolve(_.join(ct(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return qr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return No.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ne?.[this.type]?.parentKey&&(e=ne?.[this.type]?.parentKey),e}static new(e,t,n,i){return new z(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new z(e,t.key,n,t)}static fromPathAndData(e,t){const n=z.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?z.new(n.type,i,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===R.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(we).map(c=>c.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:c,elementKey:u}=r.groups,f=this.getElementTypeFromPath(c);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:c,elementType:u,elementKey:f}=a.groups,h=this.getElementTypeFromPath(u);if(h)return{type:h,key:f,integrationKey:c}}}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=>we[t].apiPath===e)}static getRelativePath(e){return _.relative(ct(process.cwd()),e)}static isIntegrationSpecific(e){return Qs.includes(e)}static canBeIntegrationSpecific(e){return Qs.includes(e)}}const V={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class In extends Jr{static{l(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const $o="membrane",Po="membrane.config.yml",On="https://api.integration.app";function An(){const s=process.cwd(),e=_.join(s,$o),t=_.join(s,Po),n=e,i=_.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}l(An,"getPaths");function Lo(){return An().membraneDirPath}l(Lo,"getBasePath");const xo={pat:{type:"string"},workspace:{type:"object"}},Xs=new Wr({schema:xo,configName:"config",cwd:U.join(Ns.homedir(),".membrane")}),Do=l(s=>{Xs.set("pat",s)},"setPat"),ei=l(()=>Xs.get("pat"),"getPat");class ti{static{l(this,"AccountApiClient")}constructor(e=On){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=ei();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const _o=l(s=>{const e=new ti(On);return t=>e.get(t)},"createAccountApiFetcher");function Rt(s){return at.loadConfig(s)}l(Rt,"readProjectConfig");class Ro{static{l(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();constructor(e={}){this.windowSizeMs=e.windowSizeMs||1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond||80,this.maxConcurrentRequests=e.maxConcurrentRequests||Math.min(this.maxRequestsPerSecond/4,20),this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.requestTimeout=e.requestTimeout||12e4,this.enableJitter=e.enableJitter!==!1}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()}})}async generateAccessToken(e,t){return Cn.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=Rt(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 Es({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,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){let t;for(let n=0;n<=this.maxRetries;n++)try{return await e()}catch(i){if(t=i,!this.isRetryableError(i)||n===this.maxRetries)throw i;let r=this.retryDelay*Math.pow(2,n);if(this.enableJitter){const o=r*.25*(Math.random()*2-1);r=Math.max(0,r+o)}await new Promise(o=>setTimeout(o,r))}throw t||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 i=new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const r=await Promise.race([e,i]);return n&&clearTimeout(n),r}catch(r){throw n&&clearTimeout(n),r}}}const F=new Ro;async function ni(s){const{id:e}=await F.withClient(t=>t.get("org-workspace-id"),s);return e}l(ni,"getWorkspaceId");class Mo extends In{static{l(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(V.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(V.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(V.ConfigChanged,{config:e})}setStats(e){this.emit(V.StatsChanged,{stats:e})}addLog(e){this.emit(V.LogAdded,{log:e})}setMcpStatus(e){this.emit(V.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(V.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await F.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await F.withClient(t=>t.post("/local-clients",{hostname:Ns.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const pe=new Mo({heartbeatIntervalMs:15e3});class jo{static{l(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=pe}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new jo;class si{static{l(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=[R.Integration,R.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of r)e.push(...o)}catch(t){throw T.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return 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){}}class Ko extends si{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ct(process.cwd())}async getElementsByType(e,t){const n=[],i=_.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=_.join(this.basePath,we[R.Integration].apiPath,o.key,we[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=_.join(this.basePath,t.dirPath),i=_.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=_.join(this.basePath,e.path),n=_.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=_.join(this.basePath,we[R.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return z.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=_.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(_.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Fo extends si{static{l(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!z.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:r});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await F.withClient(n=>n[ne[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 i=await F.withClient(o=>o[ne[e.type].elements].create(n),process.cwd()),r=z.fromData(e.type,i);return T.info(`[remote] Created ${r.id}`),r}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean();this.transformElementForUpdate(e,i,n);const r=await F.withClient(a=>a[ne[e.type].element](t.data.id).put(i),process.cwd()),o=z.fromData(t.type,r);return T.info(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await F.withClient(t=>t[ne[e.type].element](e.data.id).archive(),process.cwd()),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await F.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>z.fromData(R.Integration,n));return t.length>0&&T.success(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await F.withClient(i=>i[ne[t].element](e).get())}catch{return}return z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===R.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===R.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===R.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===R.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.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 i=e.getParentKey();if(!i)return;const r=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(r)t[i]=r.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){return(await F.withClient(i=>i[ne[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>z.fromData(e,i))}}const Nn=Symbol.for("yaml.alias"),$n=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),ii=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Ue=Symbol.for("yaml.seq"),re=Symbol.for("yaml.node.type"),Se=l(s=>!!s&&typeof s=="object"&&s[re]===Nn,"isAlias"),Oe=l(s=>!!s&&typeof s=="object"&&s[re]===$n,"isDocument"),Je=l(s=>!!s&&typeof s=="object"&&s[re]===be,"isMap"),q=l(s=>!!s&&typeof s=="object"&&s[re]===ii,"isPair"),j=l(s=>!!s&&typeof s=="object"&&s[re]===fe,"isScalar$1"),We=l(s=>!!s&&typeof s=="object"&&s[re]===Ue,"isSeq");function J(s){if(s&&typeof s=="object")switch(s[re]){case be:case Ue:return!0}return!1}l(J,"isCollection$1");function W(s){if(s&&typeof s=="object")switch(s[re]){case Nn:case be:case fe:case Ue:return!0}return!1}l(W,"isNode");const ri=l(s=>(j(s)||J(s))&&!!s.anchor,"hasAnchor"),te=Symbol("break visit"),oi=Symbol("skip children"),he=Symbol("remove node");function Ae(s,e){const t=ai(e);Oe(s)?Ve(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):Ve(null,s,t,Object.freeze([]))}l(Ae,"visit$1"),Ae.BREAK=te,Ae.SKIP=oi,Ae.REMOVE=he;function Ve(s,e,t,n){const i=ci(s,e,t,n);if(W(i)||q(i))return li(s,n,i),Ve(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=Ve(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=Ve("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=Ve("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}l(Ve,"visit_");async function Mt(s,e){const t=ai(e);Oe(s)?await Ge(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):await Ge(null,s,t,Object.freeze([]))}l(Mt,"visitAsync"),Mt.BREAK=te,Mt.SKIP=oi,Mt.REMOVE=he;async function Ge(s,e,t,n){const i=await ci(s,e,t,n);if(W(i)||q(i))return li(s,n,i),Ge(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Ge(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=await Ge("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=await Ge("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}l(Ge,"visitAsync_");function ai(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}l(ai,"initVisitor");function ci(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Je(e))return t.Map?.(s,e,n);if(We(e))return t.Seq?.(s,e,n);if(q(e))return t.Pair?.(s,e,n);if(j(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}l(ci,"callVisitor");function li(s,e,t){const n=e[e.length-1];if(J(n))n.items[s]=t;else if(q(n))s==="key"?n.key=t:n.value=t;else if(Oe(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(li,"replaceNode");const Bo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qo=l(s=>s.replace(/[!,[\]{}]/g,e=>Bo[e]),"escapeTagName");class X{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},X.defaultYaml,e),this.tags=Object.assign({},X.defaultTags,t)}clone(){const e=new X(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new X(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:X.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},X.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:X.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},X.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+qo(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&W(e.contents)){const r={};Ae(e.contents,(o,a)=>{W(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
- `)}}X.defaultYaml={explicit:!1,version:"1.2"},X.defaultTags={"!!":"tag:yaml.org,2002:"};function ui(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}l(ui,"anchorIsValid");function fi(s){const e=new Set;return Ae(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(fi,"anchorNames");function hi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(hi,"findNewAnchor");function Uo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=fi(s));const o=hi(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(j(o.node)||J(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}l(Uo,"createNodeAnchors");function ze(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=ze(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=ze(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=ze(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=ze(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}l(ze,"applyReviver");function oe(s,e,t){if(Array.isArray(s))return s.map((n,i)=>oe(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!ri(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}l(oe,"toJS");class Pn{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,re,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Oe(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=oe(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?ze(r,{"":a},"",a):a}}class jt extends Pn{static{l(this,"Alias")}constructor(e){super(Nn),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=[],Ae(e,{Node:l((r,o)=>{(Se(o)||ri(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(oe(o,null,t),a=n.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Kt(i,o,n)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(ui(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function Kt(s,e,t){if(Se(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(J(e)){let n=0;for(const i of e.items){const r=Kt(s,i,t);r>n&&(n=r)}return n}else if(q(e)){const n=Kt(s,e.key,t),i=Kt(s,e.value,t);return Math.max(n,i)}return 1}l(Kt,"getAliasCount");const di=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends Pn{static{l(this,"Scalar")}constructor(e){super(fe),this.value=e}toJSON(e,t){return t?.keep?this.value:oe(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const Jo="tag:yaml.org,2002:";function Wo(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}l(Wo,"findTagObject");function lt(s,e,t){if(Oe(s)&&(s=s.contents),W(s))return s;if(q(s)){const h=t.schema[be].createNode?.(t.schema,null,t);return h.items.push(s),h}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=i(s)),new jt(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Jo+e.slice(2));let u=Wo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const h=new L(s);return c&&(c.node=h),h}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[Ue]:o[be]}r&&(r(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 L(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(lt,"createNode");function Ft(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return lt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}l(Ft,"collectionFromPath");const ut=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class pi extends Pn{static{l(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=>W(n)||q(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ut(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(J(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ft(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(J(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&j(r)?r.value:r:J(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!q(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 i=this.get(t,!0);return J(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(J(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ft(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Vo=l(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function me(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}l(me,"indentComment");const Ne=l((s,e,t)=>s.endsWith(`
2
+ var Nr=Object.defineProperty;var l=(s,e)=>Nr(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as yn}from"react/jsx-runtime";import*as _ from"node:path";import{resolve as $r,dirname as Pr,join as Lr}from"node:path";import{useInput as De,Box as b,Text as S,Newline as xr,render as Tt}from"ink";import Dr from"minimist";import{SWRConfig as _r}from"swr";import _e,{createContext as vs,useState as B,useEffect as Ee,useContext as ks,useMemo as Rr,useRef as Mr}from"react";import Ts from"swr/immutable";import{MembraneConfigLoader as jr,WorkspaceElementType as R,WorkspaceElementSpecs as we,MembraneClient as Es,WorkspaceSyncEventType as Kr,setValueAtLocator as wn,extractMembraneErrorData as ue,getDataCollectionCreateFields as bn,excludeWriteOnlyFieldsFromSchema as Is,valueToSchema as Et,getRequiredFieldsFromSchema as Fr,getValueAtLocator as Br,walkSchema as Os,makeDataLocationPath as As,getDataCollectionUpdateFields as Sn}from"@membranehq/sdk";import qr from"lodash/isEqual.js";import*as x from"node:fs";import{readFileSync as Ur}from"node:fs";import Ie from"js-yaml";import Ns from"os";import{EventEmitter as Jr}from"events";import U from"path";import Wr from"conf";import Cn from"jsonwebtoken";import*as Vr from"node:crypto";import{createHash as Gr}from"node:crypto";import zr from"chokidar";import{EventSource as Hr}from"eventsource";import M from"fs";import Yr from"archiver";import Zr from"form-data";import Qr from"unzipper";import*as Xr from"node:os";import{exec as eo}from"node:child_process";import{Spinner as to,TextInput as no,Select as so}from"@inkjs/ui";import It from"ink-spinner";import io from"ink-text-input";import{fileURLToPath as ro}from"node:url";import k from"chalk";import{Command as oo}from"commander";import vn from"axios";import{FastMCP as ao}from"fastmcp";import{z as Z}from"zod";import kn from"lodash/merge.js";import co from"@anthropic-ai/sdk";import{faker as ot}from"@faker-js/faker";import lo from"lodash/template.js";import uo from"lodash/templateSettings.js";class nt{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new jr}static getInstance(){return nt.instance||(nt.instance=new nt),nt.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 at=nt.getInstance();var D={},Ot={},$s;function Ps(){if($s)return Ot;$s=1,Object.defineProperty(Ot,"__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,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toCamelCase"),Ot.default=s,Ot}l(Ps,"requireJsCamelcase");var At={},Ls;function xs(){if(Ls)return At;Ls=1,Object.defineProperty(At,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(s,"toSnakeCase"),At.default=s,At}l(xs,"requireJsSnakecase");var Nt={},Ds;function _s(){if(Ds)return Nt;Ds=1,Object.defineProperty(Nt,"__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,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toPascalCase"),Nt.default=s,Nt}l(_s,"requireJsPascalcase");var $t={},Rs;function fo(){if(Rs)return $t;Rs=1,Object.defineProperty($t,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(s,"toDotCase"),$t.default=s,$t}l(fo,"requireJsDotcase");var Pt={},Ms;function ho(){if(Ms)return Pt;Ms=1,Object.defineProperty(Pt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(s,"toPathCase"),Pt.default=s,Pt}l(ho,"requireJsPathcase");var Lt={},js;function po(){if(js)return Lt;js=1,Object.defineProperty(Lt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(s,"toTextCase"),Lt.default=s,Lt}l(po,"requireJsTextcase");var xt={},Ks;function mo(){if(Ks)return xt;Ks=1,Object.defineProperty(xt,"__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,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(s,"toSentenceCase"),xt.default=s,xt}l(mo,"requireJsSentencecase");var Dt={},Fs;function go(){if(Fs)return Dt;Fs=1,Object.defineProperty(Dt,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,i,r){return n+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(s,"toHeaderCase"),Dt.default=s,Dt}l(go,"requireJsHeadercase");var _t={},Bs;function qs(){if(Bs)return _t;Bs=1,Object.defineProperty(_t,"__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,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(s,"toKebabCase"),_t.default=s,_t}l(qs,"requireJsKebabcase");var Re={},Tn={},Us;function Me(){return Us||(Us=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})}}(Tn)),Tn}l(Me,"requireUtils");var Js;function yo(){if(Js)return Re;Js=1;var s=Re&&Re.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(Re,"__esModule",{value:!0});var e=Me();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var h=t({key:u},i);f=h.key}return f}))),r[c]=a}),r}return l(t,"lowerKeys"),Re.default=t,Re}l(yo,"requireLowercaseKeysObject");var je={},Ws;function wo(){if(Ws)return je;Ws=1;var s=je&&je.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(je,"__esModule",{value:!0});var e=Me();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var h=t({key:u},i);f=h.key}return f}))),r[c]=a}),r}return l(t,"upperKeys"),je.default=t,je}l(wo,"requireUppercaseKeysObject");var Ke={},Vs;function bo(){if(Vs)return Ke;Vs=1;var s=Ke&&Ke.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Ke,"__esModule",{value:!0});var e=Me(),t=Ps();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"camelKeys"),Ke.default=n,Ke}l(bo,"requireCamelcaseKeysObject");var Fe={},Gs;function So(){if(Gs)return Fe;Gs=1;var s=Fe&&Fe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Fe,"__esModule",{value:!0});var e=Me(),t=xs();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"snakeKeys"),Fe.default=n,Fe}l(So,"requireSnakecaseKeysObject");var Be={},zs;function Co(){if(zs)return Be;zs=1;var s=Be&&Be.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(Be,"__esModule",{value:!0});var e=Me(),t=_s();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"pascalKeys"),Be.default=n,Be}l(Co,"requirePascalcaseKeysObject");var qe={},Hs;function vo(){if(Hs)return qe;Hs=1;var s=qe&&qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,h=u.length;f<h;f++,c++)a[c]=u[f];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Me(),t=qs();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var h=f;if(e.isValidObject(f))e.belongToTypes(h,r.keepTypesOnRecursion)||(h=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);h=p.key}return h}))),o[u]=c}),o}return l(n,"kebabKeys"),qe.default=n,qe}l(vo,"requireKebabcaseKeysObject");var Ys;function ko(){if(Ys)return D;Ys=1,Object.defineProperty(D,"__esModule",{value:!0}),D.kebabKeys=D.pascalKeys=D.snakeKeys=D.camelKeys=D.upperKeys=D.lowerKeys=D.toLowerCase=D.toUpperCase=D.toKebabCase=D.toHeaderCase=D.toSentenceCase=D.toTextCase=D.toPathCase=D.toDotCase=D.toPascalCase=D.toSnakeCase=D.toCamelCase=void 0;var s=Ps();D.toCamelCase=s.default;var e=xs();D.toSnakeCase=e.default;var t=_s();D.toPascalCase=t.default;var n=fo();D.toDotCase=n.default;var i=ho();D.toPathCase=i.default;var r=po();D.toTextCase=r.default;var o=mo();D.toSentenceCase=o.default;var a=go();D.toHeaderCase=a.default;var c=qs();D.toKebabCase=c.default;var u=yo();D.lowerKeys=u.default;var f=wo();D.upperKeys=f.default;var h=bo();D.camelKeys=h.default;var p=So();D.snakeKeys=p.default;var g=Co();D.pascalKeys=g.default;var w=vo();D.kebabKeys=w.default;var d=l(function(v){return String(v||"").toLowerCase()},"toLowerCase");D.toLowerCase=d;var y=l(function(v){return String(v||"").toUpperCase()},"toUpperCase");D.toUpperCase=y;var C={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:d,lowerKeys:u.default,upperKeys:f.default,camelKeys:h.default,snakeKeys:p.default,pascalKeys:g.default,kebabKeys:w.default};return D.default=C,D}l(ko,"requireLib");var En,Zs;function To(){return Zs||(Zs=1,En=ko()),En}l(To,"requireJsConvertCase");var Eo=To();const de={UPDATE:"update",DELETE:"delete",CREATE:"create"},ee={INCOMING:"incoming",OUTGOING:"outgoing"},ne={[R.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(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:l(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:l(s=>(delete s.dataSourceId,s),"exportCleanup")},[R.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Io(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}l(Io,"baseExportCleanup");const Oo="membrane",Ao=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function ct(s){return _.join(s,Oo)}l(ct,"getMembraneDir");const No=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Qs=[R.Action,R.FieldMapping,R.Flow,R.DataSource];class z{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||z.extractIntegrationKey(i)}get id(){return z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[R.Integration].apiPath;return _.join(t,this.integrationKey,e,this.key)}return _.join(e,this.key)}get path(){return _.join(this.dirPath,"spec.yaml")}get relativePath(){return _.relative(ct(process.cwd()),this.path)}get absolutePath(){return _.resolve(_.join(ct(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return qr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return No.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ne?.[this.type]?.parentKey&&(e=ne?.[this.type]?.parentKey),e}static new(e,t,n,i){return new z(e,t,n,i)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new z(e,t.key,n,t)}static fromPathAndData(e,t){const n=z.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?z.new(n.type,i,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===R.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(we).map(c=>c.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:c,elementKey:u}=r.groups,f=this.getElementTypeFromPath(c);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:c,elementType:u,elementKey:f}=a.groups,h=this.getElementTypeFromPath(u);if(h)return{type:h,key:f,integrationKey:c}}}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=>we[t].apiPath===e)}static getRelativePath(e){return _.relative(ct(process.cwd()),e)}static isIntegrationSpecific(e){return Qs.includes(e)}static canBeIntegrationSpecific(e){return Qs.includes(e)}}const V={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class In extends Jr{static{l(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const $o="membrane",Po="membrane.config.yml",On="https://api.integration.app";function An(){const s=process.cwd(),e=_.join(s,$o),t=_.join(s,Po),n=e,i=_.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}l(An,"getPaths");function Lo(){return An().membraneDirPath}l(Lo,"getBasePath");const xo={pat:{type:"string"},workspace:{type:"object"}},Xs=new Wr({schema:xo,configName:"config",cwd:U.join(Ns.homedir(),".membrane")}),Do=l(s=>{Xs.set("pat",s)},"setPat"),ei=l(()=>Xs.get("pat"),"getPat");class ti{static{l(this,"AccountApiClient")}constructor(e=On){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=ei();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const _o=l(s=>{const e=new ti(On);return t=>e.get(t)},"createAccountApiFetcher");function Rt(s){return at.loadConfig(s)}l(Rt,"readProjectConfig");class Ro{static{l(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();constructor(e={}){this.windowSizeMs=e.windowSizeMs||1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond||80,this.maxConcurrentRequests=e.maxConcurrentRequests||Math.min(this.maxRequestsPerSecond/4,20),this.maxRetries=e.maxRetries||3,this.retryDelay=e.retryDelay||1e3,this.requestTimeout=e.requestTimeout||12e4,this.enableJitter=e.enableJitter!==!1}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()}})}async generateAccessToken(e,t){return Cn.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=Rt(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 Es({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,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){let t;for(let n=0;n<=this.maxRetries;n++)try{return await e()}catch(i){if(t=i,!this.isRetryableError(i)||n===this.maxRetries)throw i;let r=this.retryDelay*Math.pow(2,n);if(this.enableJitter){const o=r*.25*(Math.random()*2-1);r=Math.max(0,r+o)}await new Promise(o=>setTimeout(o,r))}throw t||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 i=new Promise((r,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const r=await Promise.race([e,i]);return n&&clearTimeout(n),r}catch(r){throw n&&clearTimeout(n),r}}}const F=new Ro;async function ni(s){const{id:e}=await F.withClient(t=>t.get("org-workspace-id"),s);return e}l(ni,"getWorkspaceId");class Mo extends In{static{l(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(V.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(V.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(V.ConfigChanged,{config:e})}setStats(e){this.emit(V.StatsChanged,{stats:e})}addLog(e){this.emit(V.LogAdded,{log:e})}setMcpStatus(e){this.emit(V.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(V.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await F.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await F.withClient(t=>t.post("/local-clients",{hostname:Ns.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await F.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const pe=new Mo({heartbeatIntervalMs:15e3});class jo{static{l(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=pe}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new jo;class si{static{l(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=[R.Integration,R.Connector],i=Object.keys(ne),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of r)e.push(...o)}catch(t){throw T.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return 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){}}class Ko extends si{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ct(process.cwd())}async getElementsByType(e,t){const n=[],i=_.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=_.join(this.basePath,we[R.Integration].apiPath,o.key,we[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=_.join(this.basePath,t.dirPath),i=_.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ie.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=_.join(this.basePath,e.path),n=_.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=_.join(this.basePath,we[R.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ie.load(t);if(n)return z.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!x.existsSync(e))return t;const n=x.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=_.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(i)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!x.existsSync(e)||x.readdirSync(e).length>0)return;x.rmdirSync(e),this.pruneEmptyDir(_.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Fo extends si{static{l(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=await this.findAll(e);if(!z.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,o?{integrationId:o}:{integrationKey:r});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await F.withClient(n=>n[ne[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 i=await F.withClient(o=>o[ne[e.type].elements].create(n),process.cwd()),r=z.fromData(e.type,i);return T.info(`[remote] Created ${r.id}`),r}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean();this.transformElementForUpdate(e,i,n);const r=await F.withClient(a=>a[ne[e.type].element](t.data.id).put(i),process.cwd()),o=z.fromData(t.type,r);return T.info(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await F.withClient(t=>t[ne[e.type].element](e.data.id).archive(),process.cwd()),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await F.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>z.fromData(R.Integration,n));return t.length>0&&T.success(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await F.withClient(i=>i[ne[t].element](e).get())}catch{return}return z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===R.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===R.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===R.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}if(e.integrationKey){t.integrationKey=e.integrationKey;const i=n.elements.find(r=>r.type===R.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.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 i=e.getParentKey();if(!i)return;const r=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(r)t[i]=r.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={}){return(await F.withClient(i=>i[ne[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>z.fromData(e,i))}}const Nn=Symbol.for("yaml.alias"),$n=Symbol.for("yaml.document"),be=Symbol.for("yaml.map"),ii=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Ue=Symbol.for("yaml.seq"),re=Symbol.for("yaml.node.type"),Se=l(s=>!!s&&typeof s=="object"&&s[re]===Nn,"isAlias"),Oe=l(s=>!!s&&typeof s=="object"&&s[re]===$n,"isDocument"),Je=l(s=>!!s&&typeof s=="object"&&s[re]===be,"isMap"),q=l(s=>!!s&&typeof s=="object"&&s[re]===ii,"isPair"),K=l(s=>!!s&&typeof s=="object"&&s[re]===fe,"isScalar$1"),We=l(s=>!!s&&typeof s=="object"&&s[re]===Ue,"isSeq");function J(s){if(s&&typeof s=="object")switch(s[re]){case be:case Ue:return!0}return!1}l(J,"isCollection$1");function W(s){if(s&&typeof s=="object")switch(s[re]){case Nn:case be:case fe:case Ue:return!0}return!1}l(W,"isNode");const ri=l(s=>(K(s)||J(s))&&!!s.anchor,"hasAnchor"),te=Symbol("break visit"),oi=Symbol("skip children"),he=Symbol("remove node");function Ae(s,e){const t=ai(e);Oe(s)?Ve(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):Ve(null,s,t,Object.freeze([]))}l(Ae,"visit$1"),Ae.BREAK=te,Ae.SKIP=oi,Ae.REMOVE=he;function Ve(s,e,t,n){const i=ci(s,e,t,n);if(W(i)||q(i))return li(s,n,i),Ve(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=Ve(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=Ve("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=Ve("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}l(Ve,"visit_");async function Mt(s,e){const t=ai(e);Oe(s)?await Ge(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):await Ge(null,s,t,Object.freeze([]))}l(Mt,"visitAsync"),Mt.BREAK=te,Mt.SKIP=oi,Mt.REMOVE=he;async function Ge(s,e,t,n){const i=await ci(s,e,t,n);if(W(i)||q(i))return li(s,n,i),Ge(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Ge(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===he&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=await Ge("key",e.key,t,n);if(r===te)return te;r===he&&(e.key=null);const o=await Ge("value",e.value,t,n);if(o===te)return te;o===he&&(e.value=null)}}return i}l(Ge,"visitAsync_");function ai(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}l(ai,"initVisitor");function ci(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Je(e))return t.Map?.(s,e,n);if(We(e))return t.Seq?.(s,e,n);if(q(e))return t.Pair?.(s,e,n);if(K(e))return t.Scalar?.(s,e,n);if(Se(e))return t.Alias?.(s,e,n)}l(ci,"callVisitor");function li(s,e,t){const n=e[e.length-1];if(J(n))n.items[s]=t;else if(q(n))s==="key"?n.key=t:n.value=t;else if(Oe(n))n.contents=t;else{const i=Se(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(li,"replaceNode");const Bo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},qo=l(s=>s.replace(/[!,[\]{}]/g,e=>Bo[e]),"escapeTagName");class X{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},X.defaultYaml,e),this.tags=Object.assign({},X.defaultTags,t)}clone(){const e=new X(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new X(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:X.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},X.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:X.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},X.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),i=n.shift();switch(i){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[r,o]=n;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=n;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[n];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+qo(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&W(e.contents)){const r={};Ae(e.contents,(o,a)=>{W(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
+ `)}}X.defaultYaml={explicit:!1,version:"1.2"},X.defaultTags={"!!":"tag:yaml.org,2002:"};function ui(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}l(ui,"anchorIsValid");function fi(s){const e=new Set;return Ae(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(fi,"anchorNames");function hi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(hi,"findNewAnchor");function Uo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=fi(s));const o=hi(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(K(o.node)||J(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}l(Uo,"createNodeAnchors");function ze(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let i=0,r=n.length;i<r;++i){const o=n[i],a=ze(s,n,String(i),o);a===void 0?delete n[i]:a!==o&&(n[i]=a)}else if(n instanceof Map)for(const i of Array.from(n.keys())){const r=n.get(i),o=ze(s,n,i,r);o===void 0?n.delete(i):o!==r&&n.set(i,o)}else if(n instanceof Set)for(const i of Array.from(n)){const r=ze(s,n,i,i);r===void 0?n.delete(i):r!==i&&(n.delete(i),n.add(r))}else for(const[i,r]of Object.entries(n)){const o=ze(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}l(ze,"applyReviver");function oe(s,e,t){if(Array.isArray(s))return s.map((n,i)=>oe(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!ri(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}l(oe,"toJS");class Pn{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,re,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:i,reviver:r}={}){if(!Oe(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=oe(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?ze(r,{"":a},"",a):a}}class jt extends Pn{static{l(this,"Alias")}constructor(e){super(Nn),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=[],Ae(e,{Node:l((r,o)=>{(Se(o)||ri(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(oe(o,null,t),a=n.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Kt(i,o,n)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(ui(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function Kt(s,e,t){if(Se(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(J(e)){let n=0;for(const i of e.items){const r=Kt(s,i,t);r>n&&(n=r)}return n}else if(q(e)){const n=Kt(s,e.key,t),i=Kt(s,e.value,t);return Math.max(n,i)}return 1}l(Kt,"getAliasCount");const di=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends Pn{static{l(this,"Scalar")}constructor(e){super(fe),this.value=e}toJSON(e,t){return t?.keep?this.value:oe(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const Jo="tag:yaml.org,2002:";function Wo(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}l(Wo,"findTagObject");function lt(s,e,t){if(Oe(s)&&(s=s.contents),W(s))return s;if(q(s)){const h=t.schema[be].createNode?.(t.schema,null,t);return h.items.push(s),h}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=i(s)),new jt(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Jo+e.slice(2));let u=Wo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const h=new L(s);return c&&(c.node=h),h}u=s instanceof Map?o[be]:Symbol.iterator in Object(s)?o[Ue]:o[be]}r&&(r(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 L(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(lt,"createNode");function Ft(s,e,t){let n=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=n,n=o}else n=new Map([[r,n]])}return lt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}l(Ft,"collectionFromPath");const ut=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class pi extends Pn{static{l(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=>W(n)||q(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ut(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(J(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ft(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(J(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&K(r)?r.value:r:J(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!q(t))return!1;const n=t.value;return n==null||e&&K(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return J(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(J(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ft(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Vo=l(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function me(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}l(me,"indentComment");const Ne=l((s,e,t)=>s.endsWith(`
4
4
  `)?me(t,e):t.includes(`
5
5
  `)?`
6
6
  `+me(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),mi="flow",Ln="block",Bt="quoted";function qt(s,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return s;i<r&&(r=0);const c=Math.max(1+r,1+i-e.length);if(s.length<=c)return s;const u=[],f={};let h=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):h=i-n);let p,g,w=!1,d=-1,y=-1,C=-1;t===Ln&&(d=gi(s,d,e.length),d!==-1&&(h=d+c));for(let A;A=s[d+=1];){if(t===Bt&&A==="\\"){switch(y=d,s[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}C=d}if(A===`
7
7
  `)t===Ln&&(d=gi(s,d,e.length)),h=d+e.length+c,p=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
8
- `&&g!==" "){const I=s[d+1];I&&I!==" "&&I!==`
9
- `&&I!==" "&&(p=d)}if(d>=h)if(p)u.push(p),h=p+c,p=void 0;else if(t===Bt){for(;g===" "||g===" ";)g=A,A=s[d+=1],w=!0;const I=d>C+1?d-2:y-1;if(f[I])return s;u.push(I),f[I]=!0,h=I+c,p=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let v=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const I=u[A],N=u[A+1]||s.length;I===0?v=`
10
- ${e}${s.slice(0,N)}`:(t===Bt&&f[I]&&(v+=`${s[I]}\\`),v+=`
11
- ${e}${s.slice(I+1,N)}`)}return v}l(qt,"foldFlowLines");function gi(s,e,t){let n=e,i=e+1,r=s[i];for(;r===" "||r===" ";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`
8
+ `&&g!==" "){const O=s[d+1];O&&O!==" "&&O!==`
9
+ `&&O!==" "&&(p=d)}if(d>=h)if(p)u.push(p),h=p+c,p=void 0;else if(t===Bt){for(;g===" "||g===" ";)g=A,A=s[d+=1],w=!0;const O=d>C+1?d-2:y-1;if(f[O])return s;u.push(O),f[O]=!0,h=O+c,p=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let v=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const O=u[A],N=u[A+1]||s.length;O===0?v=`
10
+ ${e}${s.slice(0,N)}`:(t===Bt&&f[O]&&(v+=`${s[O]}\\`),v+=`
11
+ ${e}${s.slice(O+1,N)}`)}return v}l(qt,"foldFlowLines");function gi(s,e,t){let n=e,i=e+1,r=s[i];for(;r===" "||r===" ";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`
12
12
  `);n=e,i=e+1,r=s[i]}return n}l(gi,"consumeMoreIndentedLines");const Ut=l((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Jt=l(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Go(s,e,t){if(!e||e<0)return!1;const n=e-t,i=s.length;if(i<=n)return!1;for(let r=0,o=0;r<i;++r)if(s[r]===`
13
13
  `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}l(Go,"lineLengthOverLimit");function ft(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Jt(s)?" ":"");let o="",a=0;for(let c=0,u=t[c];u;u=t[++c])if(u===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);const f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<i)c+=1;else{for(o+=t.slice(a,c)+`
14
14
 
@@ -24,52 +24,52 @@ ${t}`)+"'";return e.implicitKey?n:qt(n,t,mi,Ut(e,!1))}l(xn,"singleQuotedString")
24
24
  `&&N!==" "&&N!==" ")break}let g=t.substring(p);const w=g.indexOf(`
25
25
  `);w===-1?h="-":t===g||w!==g.length-1?(h="+",r&&r()):h="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
26
26
  `&&(g=g.slice(0,-1)),g=g.replace(Dn,`$&${u}`));let d=!1,y,C=-1;for(y=0;y<t.length;++y){const N=t[y];if(N===" ")d=!0;else if(N===`
27
- `)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let I=(d?u?"2":"1":"")+h;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!f){const N=t.replace(/\n+/g,`
28
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const K=Ut(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(K.onOverflow=()=>{$=!0});const O=qt(`${v}${N}${g}`,u,Ln,K);if(!$)return`>${I}
29
- ${u}${O}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
27
+ `)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let O=(d?u?"2":"1":"")+h;if(s&&(O+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!f){const N=t.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const j=Ut(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(j.onOverflow=()=>{$=!0});const I=qt(`${v}${N}${g}`,u,Ln,j);if(!$)return`>${O}
29
+ ${u}${I}`}return t=t.replace(/\n+/g,`$&${u}`),`|${O}
30
30
  ${u}${v}${t}${g}`}l(Wt,"blockString");function zo(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:f}=e;if(a&&r.includes(`
31
31
  `)||f&&/[[\]{},]/.test(r))return He(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||f||!r.includes(`
32
32
  `)?He(r,e):Wt(s,e,t,n);if(!a&&!f&&i!==L.PLAIN&&r.includes(`
33
33
  `))return Wt(s,e,t,n);if(Jt(r)){if(c==="")return e.forceBlockIndent=!0,Wt(s,e,t,n);if(a&&c===u)return He(r,e)}const h=r.replace(/\n+/g,`$&
34
- ${c}`);if(o){const p=l(d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(h),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(p)||g?.some(p))return He(r,e)}return a?h:qt(h,c,mi,Ut(e,!1))}l(zo,"plainString");function ht(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const c=l(f=>{switch(f){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?He(o.value,e):Wt(o,e,t,n);case L.QUOTE_DOUBLE:return ft(o.value,e);case L.QUOTE_SINGLE:return xn(o.value,e);case L.PLAIN:return zo(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:h}=e.options,p=i&&f||h;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}l(ht,"stringifyString");function yi(s,e){const t=Object.assign({blockQuote:!0,commentString:Vo,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}l(yi,"createStringifyContext");function Ho(s,e){if(e.tag){const i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(j(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}l(Ho,"getTagObject");function Yo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(j(s)||J(s))&&s.anchor;r&&ui(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}l(Yo,"stringifyProps");function Ye(s,e,t,n){if(q(s))return s.toString(e,t,n);if(Se(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let i;const r=W(s)?s:e.doc.createNode(s,{onTagObj:l(c=>i=c,"onTagObj")});i??(i=Ho(e.doc.schema.tags,r));const o=Yo(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):j(r)?ht(r,e,t,n):r.toString(e,t,n);return o?j(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
- ${e.indent}${a}`:a}l(Ye,"stringify$2");function Zo({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:h}}=t;let p=W(s)&&s.comment||null;if(h){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(J(s)||!W(s)&&typeof s=="object"){const K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let g=!h&&(!s||p&&e==null&&!t.inFlow||J(s)||(j(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(h||!r),indent:a+c});let w=!1,d=!1,y=Ye(s,t,()=>w=!0,()=>d=!0);if(!g&&!t.inFlow&&y.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!h||e==null&&g)return y=`? ${y}`,p&&!w?y+=Ne(y,t.indent,u(p)):d&&i&&i(),y;w&&(p=null),g?(p&&(y+=Ne(y,t.indent,u(p))),y=`? ${y}
36
- ${a}:`):(y=`${y}:`,p&&(y+=Ne(y,t.indent,u(p))));let C,v,A;W(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!p&&j(e)&&(t.indentAtStart=y.length+1),d=!1,!f&&c.length>=2&&!t.inFlow&&!g&&We(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const N=Ye(e,t,()=>I=!0,()=>d=!0);let $=" ";if(p||C||v){if($=C?`
37
- `:"",v){const K=u(v);$+=`
38
- ${me(K,t.indent)}`}N===""&&!t.inFlow?$===`
34
+ ${c}`);if(o){const p=l(d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(h),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(p)||g?.some(p))return He(r,e)}return a?h:qt(h,c,mi,Ut(e,!1))}l(zo,"plainString");function ht(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const c=l(f=>{switch(f){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?He(o.value,e):Wt(o,e,t,n);case L.QUOTE_DOUBLE:return ft(o.value,e);case L.QUOTE_SINGLE:return xn(o.value,e);case L.PLAIN:return zo(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:h}=e.options,p=i&&f||h;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}l(ht,"stringifyString");function yi(s,e){const t=Object.assign({blockQuote:!0,commentString:Vo,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}l(yi,"createStringifyContext");function Ho(s,e){if(e.tag){const i=s.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,n;if(K(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}l(Ho,"getTagObject");function Yo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(K(s)||J(s))&&s.anchor;r&&ui(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}l(Yo,"stringifyProps");function Ye(s,e,t,n){if(q(s))return s.toString(e,t,n);if(Se(s)){if(e.doc.directives)return s.toString(e);if(e.resolvedAliases?.has(s))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(s):e.resolvedAliases=new Set([s]),s=s.resolve(e.doc)}let i;const r=W(s)?s:e.doc.createNode(s,{onTagObj:l(c=>i=c,"onTagObj")});i??(i=Ho(e.doc.schema.tags,r));const o=Yo(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):K(r)?ht(r,e,t,n):r.toString(e,t,n);return o?K(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
+ ${e.indent}${a}`:a}l(Ye,"stringify$2");function Zo({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:h}}=t;let p=W(s)&&s.comment||null;if(h){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(J(s)||!W(s)&&typeof s=="object"){const j="With simple keys, collection cannot be used as a key value";throw new Error(j)}}let g=!h&&(!s||p&&e==null&&!t.inFlow||J(s)||(K(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(h||!r),indent:a+c});let w=!1,d=!1,y=Ye(s,t,()=>w=!0,()=>d=!0);if(!g&&!t.inFlow&&y.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!h||e==null&&g)return y=`? ${y}`,p&&!w?y+=Ne(y,t.indent,u(p)):d&&i&&i(),y;w&&(p=null),g?(p&&(y+=Ne(y,t.indent,u(p))),y=`? ${y}
36
+ ${a}:`):(y=`${y}:`,p&&(y+=Ne(y,t.indent,u(p))));let C,v,A;W(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!p&&K(e)&&(t.indentAtStart=y.length+1),d=!1,!f&&c.length>=2&&!t.inFlow&&!g&&We(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1;const N=Ye(e,t,()=>O=!0,()=>d=!0);let $=" ";if(p||C||v){if($=C?`
37
+ `:"",v){const j=u(v);$+=`
38
+ ${me(j,t.indent)}`}N===""&&!t.inFlow?$===`
39
39
  `&&($=`
40
40
 
41
41
  `):$+=`
42
- ${t.indent}`}else if(!g&&J(e)){const K=N[0],O=N.indexOf(`
43
- `),H=O!==-1,ye=t.inFlow??e.flow??e.items.length===0;if(H||!ye){let xe=!1;if(H&&(K==="&"||K==="!")){let Y=N.indexOf(" ");K==="&"&&Y!==-1&&Y<O&&N[Y+1]==="!"&&(Y=N.indexOf(" ",Y+1)),(Y===-1||O<Y)&&(xe=!0)}xe||($=`
42
+ ${t.indent}`}else if(!g&&J(e)){const j=N[0],I=N.indexOf(`
43
+ `),H=I!==-1,ye=t.inFlow??e.flow??e.items.length===0;if(H||!ye){let xe=!1;if(H&&(j==="&"||j==="!")){let Y=N.indexOf(" ");j==="&"&&Y!==-1&&Y<I&&N[Y+1]==="!"&&(Y=N.indexOf(" ",Y+1)),(Y===-1||I<Y)&&(xe=!0)}xe||($=`
44
44
  ${t.indent}`)}}else(N===""||N[0]===`
45
- `)&&($="");return y+=$+N,t.inFlow?I&&n&&n():A&&!I?y+=Ne(y,t.indent,u(A)):d&&i&&i(),y}l(Zo,"stringifyPair");function wi(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(wi,"warn");const Vt="<<",ge={identify:l(s=>s===Vt||typeof s=="symbol"&&s.description===Vt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new L(Symbol(Vt)),{addToJSMap:bi}),"resolve"),stringify:l(()=>Vt,"stringify")},Qo=l((s,e)=>(ge.identify(e)||j(e)&&(!e.type||e.type===L.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function bi(s,e,t){if(t=s&&Se(t)?t.resolve(s.doc):t,We(t))for(const n of t.items)_n(s,e,n);else if(Array.isArray(t))for(const n of t)_n(s,e,n);else _n(s,e,t)}l(bi,"addMergeToJSMap");function _n(s,e,t){const n=s&&Se(t)?t.resolve(s.doc):t;if(!Je(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(_n,"mergeValue");function Si(s,e,{key:t,value:n}){if(W(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Qo(s,t))bi(s,e,n);else{const i=oe(t,"",s);if(e instanceof Map)e.set(i,oe(n,i,s));else if(e instanceof Set)e.add(i);else{const r=Xo(t,i,s),o=oe(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}l(Si,"addPairToJSMap");function Xo(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(W(s)&&t?.doc){const n=yi(t.doc,{});n.anchors=new Set;for(const r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),wi(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}l(Xo,"stringifyKey");function Rn(s,e,t){const n=lt(s,void 0,t),i=lt(e,void 0,t);return new Q(n,i)}l(Rn,"createPair");class Q{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,re,{value:ii}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return W(t)&&(t=t.clone(e)),W(n)&&(n=n.clone(e)),new Q(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Si(t,n,this)}toString(e,t,n){return e?.doc?Zo(this,e,t,n):JSON.stringify(this)}}function Ci(s,e,t){return(e.inFlow??s.flow?ta:ea)(s,e,t)}l(Ci,"stringifyCollection");function ea({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,f=Object.assign({},t,{indent:r,type:null});let h=!1;const p=[];for(let w=0;w<e.length;++w){const d=e[w];let y=null;if(W(d))!h&&d.spaceBefore&&p.push(""),Gt(t,p,d.commentBefore,h),d.comment&&(y=d.comment);else if(q(d)){const v=W(d.key)?d.key:null;v&&(!h&&v.spaceBefore&&p.push(""),Gt(t,p,v.commentBefore,h))}h=!1;let C=Ye(d,f,()=>y=null,()=>h=!0);y&&(C+=Ne(C,r,u(y))),h&&y&&(h=!1),p.push(n+C)}let g;if(p.length===0)g=i.start+i.end;else{g=p[0];for(let w=1;w<p.length;++w){const d=p[w];g+=d?`
45
+ `)&&($="");return y+=$+N,t.inFlow?O&&n&&n():A&&!O?y+=Ne(y,t.indent,u(A)):d&&i&&i(),y}l(Zo,"stringifyPair");function wi(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(wi,"warn");const Vt="<<",ge={identify:l(s=>s===Vt||typeof s=="symbol"&&s.description===Vt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new L(Symbol(Vt)),{addToJSMap:bi}),"resolve"),stringify:l(()=>Vt,"stringify")},Qo=l((s,e)=>(ge.identify(e)||K(e)&&(!e.type||e.type===L.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function bi(s,e,t){if(t=s&&Se(t)?t.resolve(s.doc):t,We(t))for(const n of t.items)_n(s,e,n);else if(Array.isArray(t))for(const n of t)_n(s,e,n);else _n(s,e,t)}l(bi,"addMergeToJSMap");function _n(s,e,t){const n=s&&Se(t)?t.resolve(s.doc):t;if(!Je(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(_n,"mergeValue");function Si(s,e,{key:t,value:n}){if(W(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Qo(s,t))bi(s,e,n);else{const i=oe(t,"",s);if(e instanceof Map)e.set(i,oe(n,i,s));else if(e instanceof Set)e.add(i);else{const r=Xo(t,i,s),o=oe(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}l(Si,"addPairToJSMap");function Xo(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(W(s)&&t?.doc){const n=yi(t.doc,{});n.anchors=new Set;for(const r of t.anchors.keys())n.anchors.add(r.anchor);n.inFlow=!0,n.inStringifyKey=!0;const i=s.toString(n);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),wi(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}l(Xo,"stringifyKey");function Rn(s,e,t){const n=lt(s,void 0,t),i=lt(e,void 0,t);return new Q(n,i)}l(Rn,"createPair");class Q{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,re,{value:ii}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return W(t)&&(t=t.clone(e)),W(n)&&(n=n.clone(e)),new Q(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Si(t,n,this)}toString(e,t,n){return e?.doc?Zo(this,e,t,n):JSON.stringify(this)}}function Ci(s,e,t){return(e.inFlow??s.flow?ta:ea)(s,e,t)}l(Ci,"stringifyCollection");function ea({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,f=Object.assign({},t,{indent:r,type:null});let h=!1;const p=[];for(let w=0;w<e.length;++w){const d=e[w];let y=null;if(W(d))!h&&d.spaceBefore&&p.push(""),Gt(t,p,d.commentBefore,h),d.comment&&(y=d.comment);else if(q(d)){const v=W(d.key)?d.key:null;v&&(!h&&v.spaceBefore&&p.push(""),Gt(t,p,v.commentBefore,h))}h=!1;let C=Ye(d,f,()=>y=null,()=>h=!0);y&&(C+=Ne(C,r,u(y))),h&&y&&(h=!1),p.push(n+C)}let g;if(p.length===0)g=i.start+i.end;else{g=p[0];for(let w=1;w<p.length;++w){const d=p[w];g+=d?`
46
46
  ${c}${d}`:`
47
47
  `}}return s?(g+=`
48
48
  `+me(u(s),c),a&&a()):h&&o&&o(),g}l(ea,"stringifyBlockCollection");function ta({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const c=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,f=0;const h=[];for(let w=0;w<s.length;++w){const d=s[w];let y=null;if(W(d))d.spaceBefore&&h.push(""),Gt(e,h,d.commentBefore,!1),d.comment&&(y=d.comment);else if(q(d)){const v=W(d.key)?d.key:null;v&&(v.spaceBefore&&h.push(""),Gt(e,h,v.commentBefore,!1),v.comment&&(u=!0));const A=W(d.value)?d.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):d.value==null&&v?.comment&&(y=v.comment)}y&&(u=!0);let C=Ye(d,c,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ne(C,n,a(y))),!u&&(h.length>f||C.includes(`
49
49
  `))&&(u=!0),h.push(C),f=h.length}const{start:p,end:g}=t;if(h.length===0)return p+g;if(!u){const w=h.reduce((d,y)=>d+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=p;for(const d of h)w+=d?`
50
50
  ${r}${i}${d}`:`
51
51
  `;return`${w}
52
- ${i}${g}`}else return`${p}${o}${h.join(" ")}${o}${g}`}l(ta,"stringifyFlowCollection");function Gt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=me(e(n),s);t.push(r.trimStart())}}l(Gt,"addCommentBefore");function $e(s,e){const t=j(e)?e.value:e;for(const n of s)if(q(n)&&(n.key===e||n.key===t||j(n.key)&&n.key.value===t))return n}l($e,"findPair");class se extends pi{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(be,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=l((c,u)=>{if(typeof r=="function")u=r.call(t,c,u);else if(Array.isArray(r)&&!r.includes(c))return;(u!==void 0||i)&&o.items.push(Rn(c,u,n))},"add");if(t instanceof Map)for(const[c,u]of t)a(c,u);else if(t&&typeof t=="object")for(const c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;q(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Q(e,e?.value):n=new Q(e.key,e.value);const i=$e(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);j(i.value)&&di(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=$e(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=$e(this.items,e)?.value;return(!t&&j(i)?i.value:i)??void 0}has(e){return!!$e(this.items,e)}set(e,t){this.add(new Q(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)Si(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!q(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ci(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ze={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return Je(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>se.from(s,e,t),"createNode")};class Ce extends pi{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ue,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=zt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=zt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&j(i)?i.value:i}has(e){const t=zt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=zt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];j(i)&&di(t)?i.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let i=0;for(const r of this.items)n.push(oe(r,String(i++),t));return n}toString(e,t,n){return e?Ci(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const c=t instanceof Set?a:String(o++);a=i.call(t,c,a)}r.items.push(lt(a,void 0,n))}}return r}}function zt(s){let e=j(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(zt,"asItemIndex");const Qe={collection:"seq",default:!0,nodeClass:Ce,tag:"tag:yaml.org,2002:seq",resolve(s,e){return We(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>Ce.from(s,e,t),"createNode")},Ht={identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),ht(s,e,t,n)}},Yt={identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new L(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&Yt.test.test(s)?s:e.options.nullStr,"stringify")},Mn={identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Mn.test.test(s)){const n=s[0]==="t"||s[0]==="T";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}};function ae({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}l(ae,"stringifyNumber");const vi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},ki={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Ti={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},Zt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),jn=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Ei(s,e,t){const{value:n}=s;return Zt(n)&&n>=0?t+n.toString(e):ae(s)}l(Ei,"intStringify$1");const Ii={identify:l(s=>Zt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>jn(s,2,8,t),"resolve"),stringify:l(s=>Ei(s,8,"0o"),"stringify")},Oi={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>jn(s,0,10,t),"resolve"),stringify:ae},Ai={identify:l(s=>Zt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:l((s,e,t)=>jn(s,2,16,t),"resolve"),stringify:l(s=>Ei(s,16,"0x"),"stringify")},na=[Ze,Qe,Ht,Yt,Mn,Ii,Oi,Ai,vi,ki,Ti];function Ni(s){return typeof s=="bigint"||Number.isInteger(s)}l(Ni,"intIdentify$1");const Qt=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),sa=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:Qt},{identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:Qt},{identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:l(s=>s==="true","resolve"),stringify:Qt},{identify:Ni,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:l((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:l(({value:s})=>Ni(s)?s.toString():JSON.stringify(s),"stringify")},{identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:l(s=>parseFloat(s),"resolve"),stringify:Qt}],ia={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},ra=[Ze,Qe].concat(sa,ia),Kn={identify:l(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let h=0,p=0;h<u;++h,p+=c)f[h]=a.substr(p,c);a=f.join(e===L.BLOCK_LITERAL?`
52
+ ${i}${g}`}else return`${p}${o}${h.join(" ")}${o}${g}`}l(ta,"stringifyFlowCollection");function Gt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=me(e(n),s);t.push(r.trimStart())}}l(Gt,"addCommentBefore");function $e(s,e){const t=K(e)?e.value:e;for(const n of s)if(q(n)&&(n.key===e||n.key===t||K(n.key)&&n.key.value===t))return n}l($e,"findPair");class se extends pi{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(be,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=l((c,u)=>{if(typeof r=="function")u=r.call(t,c,u);else if(Array.isArray(r)&&!r.includes(c))return;(u!==void 0||i)&&o.items.push(Rn(c,u,n))},"add");if(t instanceof Map)for(const[c,u]of t)a(c,u);else if(t&&typeof t=="object")for(const c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;q(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Q(e,e?.value):n=new Q(e.key,e.value);const i=$e(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);K(i.value)&&di(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=$e(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=$e(this.items,e)?.value;return(!t&&K(i)?i.value:i)??void 0}has(e){return!!$e(this.items,e)}set(e,t){this.add(new Q(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)Si(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!q(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ci(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ze={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return Je(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>se.from(s,e,t),"createNode")};class Ce extends pi{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ue,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=zt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=zt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&K(i)?i.value:i}has(e){const t=zt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=zt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];K(i)&&di(t)?i.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let i=0;for(const r of this.items)n.push(oe(r,String(i++),t));return n}toString(e,t,n){return e?Ci(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const c=t instanceof Set?a:String(o++);a=i.call(t,c,a)}r.items.push(lt(a,void 0,n))}}return r}}function zt(s){let e=K(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(zt,"asItemIndex");const Qe={collection:"seq",default:!0,nodeClass:Ce,tag:"tag:yaml.org,2002:seq",resolve(s,e){return We(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>Ce.from(s,e,t),"createNode")},Ht={identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),ht(s,e,t,n)}},Yt={identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new L(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&Yt.test.test(s)?s:e.options.nullStr,"stringify")},Mn={identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Mn.test.test(s)){const n=s[0]==="t"||s[0]==="T";if(e===n)return s}return e?t.options.trueStr:t.options.falseStr}};function ae({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}l(ae,"stringifyNumber");const vi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},ki={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Ti={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},Zt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),jn=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Ei(s,e,t){const{value:n}=s;return Zt(n)&&n>=0?t+n.toString(e):ae(s)}l(Ei,"intStringify$1");const Ii={identify:l(s=>Zt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>jn(s,2,8,t),"resolve"),stringify:l(s=>Ei(s,8,"0o"),"stringify")},Oi={identify:Zt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>jn(s,0,10,t),"resolve"),stringify:ae},Ai={identify:l(s=>Zt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:l((s,e,t)=>jn(s,2,16,t),"resolve"),stringify:l(s=>Ei(s,16,"0x"),"stringify")},na=[Ze,Qe,Ht,Yt,Mn,Ii,Oi,Ai,vi,ki,Ti];function Ni(s){return typeof s=="bigint"||Number.isInteger(s)}l(Ni,"intIdentify$1");const Qt=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),sa=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:Qt},{identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:Qt},{identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:l(s=>s==="true","resolve"),stringify:Qt},{identify:Ni,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:l((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:l(({value:s})=>Ni(s)?s.toString():JSON.stringify(s),"stringify")},{identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:l(s=>parseFloat(s),"resolve"),stringify:Qt}],ia={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},ra=[Ze,Qe].concat(sa,ia),Kn={identify:l(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let h=0,p=0;h<u;++h,p+=c)f[h]=a.substr(p,c);a=f.join(e===L.BLOCK_LITERAL?`
53
53
  `:" ")}return ht({comment:s,type:e,value:a},n,i,r)}};function $i(s,e){if(We(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!q(n)){if(Je(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
54
54
  ${i.key.commentBefore}`:n.commentBefore),n.comment){const r=i.value??i.key;r.comment=r.comment?`${n.comment}
55
- ${r.comment}`:n.comment}n=i}s.items[t]=q(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}l($i,"resolvePairs");function Pi(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(Rn(a,c,t))}return i}l(Pi,"createPairs");const Fn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$i,createNode:Pi};class st extends Ce{static{l(this,"YAMLOMap")}constructor(){super(),this.add=se.prototype.add.bind(this),this.delete=se.prototype.delete.bind(this),this.get=se.prototype.get.bind(this),this.has=se.prototype.has.bind(this),this.set=se.prototype.set.bind(this),this.tag=st.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(q(i)?(r=oe(i.key,"",t),o=oe(i.value,r,t)):r=oe(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=Pi(e,t,n),r=new this;return r.items=i.items,r}}st.tag="tag:yaml.org,2002:omap";const Bn={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:st,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=$i(s,e),n=[];for(const{key:i}of t.items)j(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new st,t)},createNode:l((s,e,t)=>st.from(s,e,t),"createNode")};function Li({value:s,source:e},t){return e&&(s?xi:Di).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(Li,"boolStringify");const xi={identify:l(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new L(!0),"resolve"),stringify:Li},Di={identify:l(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new L(!1),"resolve"),stringify:Li},oa={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},aa={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},ca={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},dt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Xt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}l(Xt,"intResolve");function qn(s,e,t){const{value:n}=s;if(dt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}l(qn,"intStringify");const la={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>Xt(s,2,2,t),"resolve"),stringify:l(s=>qn(s,2,"0b"),"stringify")},ua={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>Xt(s,1,8,t),"resolve"),stringify:l(s=>qn(s,8,"0"),"stringify")},fa={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>Xt(s,0,10,t),"resolve"),stringify:ae},ha={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>Xt(s,2,16,t),"resolve"),stringify:l(s=>qn(s,16,"0x"),"stringify")};class it extends se{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=it.tag}add(e){let t;q(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),$e(this.items,t.key)||this.items.push(t)}get(e,t){const n=$e(this.items,e);return!t&&q(n)?j(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=$e(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(Rn(o,null,n));return r}}it.tag="tag:yaml.org,2002:set";const Un={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:it,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>it.from(s,e,t),"createNode"),resolve(s,e){if(Je(s)){if(s.hasAllNullValues(!0))return Object.assign(new it,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Jn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=l(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(Jn,"parseSexagesimal");function _i(s){let{value:e}=s,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ae(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l(_i,"stringifySexagesimal");const Ri={identify:l(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((s,e,{intAsBigInt:t})=>Jn(s,t),"resolve"),stringify:_i},Mi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(s=>Jn(s,!1),"resolve"),stringify:_i},en={identify:l(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(en.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,c);const f=e[8];if(f&&f!=="Z"){let h=Jn(f,!1);Math.abs(h)<30&&(h*=60),u-=6e4*h}return new Date(u)},stringify:l(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},ji=[Ze,Qe,Ht,Yt,xi,Di,la,ua,fa,ha,oa,aa,ca,Kn,ge,Bn,Fn,Un,Ri,Mi,en],Ki=new Map([["core",na],["failsafe",[Ze,Qe,Ht]],["json",ra],["yaml11",ji],["yaml-1.1",ji]]),Fi={binary:Kn,bool:Mn,float:Ti,floatExp:ki,floatNaN:vi,floatTime:Mi,int:Oi,intHex:Ai,intOct:Ii,intTime:Ri,map:Ze,merge:ge,null:Yt,omap:Bn,pairs:Fn,seq:Qe,set:Un,timestamp:en},da={"tag:yaml.org,2002:binary":Kn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":Bn,"tag:yaml.org,2002:pairs":Fn,"tag:yaml.org,2002:set":Un,"tag:yaml.org,2002:timestamp":en};function Wn(s,e,t){const n=Ki.get(e);if(n&&!s)return t&&!n.includes(ge)?n.concat(ge):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(Ki.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(ge)),i.reduce((r,o)=>{const a=typeof o=="string"?Fi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(Fi).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(Wn,"getTags");const pa=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class gn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Wn(e,"compat"):e?Wn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?da:{},this.tags=Wn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:Ze}),Object.defineProperty(this,fe,{value:Ht}),Object.defineProperty(this,Ue,{value:Qe}),this.sortMapEntries=typeof o=="function"?o:o===!0?pa:null}clone(){const e=Object.create(gn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function ma(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const c=s.directives.toString(s);c?(t.push(c),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=yi(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const c=r(s.commentBefore);t.unshift(me(c,""))}let o=!1,a=null;if(s.contents){if(W(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=r(s.contents.commentBefore);t.push(me(f,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const c=a?void 0:()=>o=!0;let u=Ye(s.contents,i,()=>a=null,c);a&&(u+=Ne(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ye(s.contents,i));if(s.directives?.docEnd)if(s.comment){const c=r(s.comment);c.includes(`
55
+ ${r.comment}`:n.comment}n=i}s.items[t]=q(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}l($i,"resolvePairs");function Pi(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(Rn(a,c,t))}return i}l(Pi,"createPairs");const Fn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$i,createNode:Pi};class st extends Ce{static{l(this,"YAMLOMap")}constructor(){super(),this.add=se.prototype.add.bind(this),this.delete=se.prototype.delete.bind(this),this.get=se.prototype.get.bind(this),this.has=se.prototype.has.bind(this),this.set=se.prototype.set.bind(this),this.tag=st.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(q(i)?(r=oe(i.key,"",t),o=oe(i.value,r,t)):r=oe(i,"",t),n.has(r))throw new Error("Ordered maps must not include duplicate keys");n.set(r,o)}return n}static from(e,t,n){const i=Pi(e,t,n),r=new this;return r.items=i.items,r}}st.tag="tag:yaml.org,2002:omap";const Bn={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:st,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=$i(s,e),n=[];for(const{key:i}of t.items)K(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new st,t)},createNode:l((s,e,t)=>st.from(s,e,t),"createNode")};function Li({value:s,source:e},t){return e&&(s?xi:Di).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(Li,"boolStringify");const xi={identify:l(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new L(!0),"resolve"),stringify:Li},Di={identify:l(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new L(!1),"resolve"),stringify:Li},oa={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},aa={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},ca={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},dt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Xt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}l(Xt,"intResolve");function qn(s,e,t){const{value:n}=s;if(dt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}l(qn,"intStringify");const la={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>Xt(s,2,2,t),"resolve"),stringify:l(s=>qn(s,2,"0b"),"stringify")},ua={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>Xt(s,1,8,t),"resolve"),stringify:l(s=>qn(s,8,"0"),"stringify")},fa={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>Xt(s,0,10,t),"resolve"),stringify:ae},ha={identify:dt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>Xt(s,2,16,t),"resolve"),stringify:l(s=>qn(s,16,"0x"),"stringify")};class it extends se{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=it.tag}add(e){let t;q(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),$e(this.items,t.key)||this.items.push(t)}get(e,t){const n=$e(this.items,e);return!t&&q(n)?K(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=$e(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(Rn(o,null,n));return r}}it.tag="tag:yaml.org,2002:set";const Un={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:it,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>it.from(s,e,t),"createNode"),resolve(s,e){if(Je(s)){if(s.hasAllNullValues(!0))return Object.assign(new it,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Jn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=l(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(Jn,"parseSexagesimal");function _i(s){let{value:e}=s,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ae(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l(_i,"stringifySexagesimal");const Ri={identify:l(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((s,e,{intAsBigInt:t})=>Jn(s,t),"resolve"),stringify:_i},Mi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(s=>Jn(s,!1),"resolve"),stringify:_i},en={identify:l(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(en.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,c);const f=e[8];if(f&&f!=="Z"){let h=Jn(f,!1);Math.abs(h)<30&&(h*=60),u-=6e4*h}return new Date(u)},stringify:l(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},ji=[Ze,Qe,Ht,Yt,xi,Di,la,ua,fa,ha,oa,aa,ca,Kn,ge,Bn,Fn,Un,Ri,Mi,en],Ki=new Map([["core",na],["failsafe",[Ze,Qe,Ht]],["json",ra],["yaml11",ji],["yaml-1.1",ji]]),Fi={binary:Kn,bool:Mn,float:Ti,floatExp:ki,floatNaN:vi,floatTime:Mi,int:Oi,intHex:Ai,intOct:Ii,intTime:Ri,map:Ze,merge:ge,null:Yt,omap:Bn,pairs:Fn,seq:Qe,set:Un,timestamp:en},da={"tag:yaml.org,2002:binary":Kn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":Bn,"tag:yaml.org,2002:pairs":Fn,"tag:yaml.org,2002:set":Un,"tag:yaml.org,2002:timestamp":en};function Wn(s,e,t){const n=Ki.get(e);if(n&&!s)return t&&!n.includes(ge)?n.concat(ge):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(Ki.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(s))for(const r of s)i=i.concat(r);else typeof s=="function"&&(i=s(i.slice()));return t&&(i=i.concat(ge)),i.reduce((r,o)=>{const a=typeof o=="string"?Fi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(Fi).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(Wn,"getTags");const pa=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class gn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Wn(e,"compat"):e?Wn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?da:{},this.tags=Wn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,be,{value:Ze}),Object.defineProperty(this,fe,{value:Ht}),Object.defineProperty(this,Ue,{value:Qe}),this.sortMapEntries=typeof o=="function"?o:o===!0?pa:null}clone(){const e=Object.create(gn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function ma(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const c=s.directives.toString(s);c?(t.push(c),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=yi(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const c=r(s.commentBefore);t.unshift(me(c,""))}let o=!1,a=null;if(s.contents){if(W(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=r(s.contents.commentBefore);t.push(me(f,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const c=a?void 0:()=>o=!0;let u=Ye(s.contents,i,()=>a=null,c);a&&(u+=Ne(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ye(s.contents,i));if(s.directives?.docEnd)if(s.comment){const c=r(s.comment);c.includes(`
56
56
  `)?(t.push("..."),t.push(me(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=s.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(me(r(c),"")))}return t.join(`
57
57
  `)+`
58
- `}l(ma,"stringifyDocument");class rt{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re,{value:$n});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new X({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(rt.prototype,{[re]:{value:$n}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=W(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Xe(this.contents)&&this.contents.add(e)}addIn(e,t){Xe(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=fi(this);e.anchor=!t||n.has(t)?hi(t||"a",n):t}return new jt(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=l(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:f}=n??{},{onAnchor:h,setAnchors:p,sourceObjects:g}=Uo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:h,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},d=lt(e,f,w);return a&&J(d)&&(d.flow=!0),p(),d}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Q(i,r)}delete(e){return Xe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut(e)?this.contents==null?!1:(this.contents=null,!0):Xe(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return J(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ut(e)?!t&&j(this.contents)?this.contents.value:this.contents:J(this.contents)?this.contents.getIn(e,t):void 0}has(e){return J(this.contents)?this.contents.has(e):!1}hasIn(e){return ut(e)?this.contents!==void 0:J(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ft(this.schema,[e],t):Xe(this.contents)&&this.contents.set(e,t)}setIn(e,t){ut(e)?this.contents=t:this.contents==null?this.contents=Ft(this.schema,Array.from(e),t):Xe(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new X({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new X({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new gn(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=oe(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:f}of a.anchors.values())r(f,u);return typeof o=="function"?ze(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return ma(this,e)}}function Xe(s){if(J(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(Xe,"assertCollection");class Vn extends Error{static{l(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class Pe extends Vn{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Bi extends Vn{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const tn=l((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
58
+ `}l(ma,"stringifyDocument");class rt{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re,{value:$n});let i=null;typeof t=="function"||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=r;let{version:o}=r;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new X({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(rt.prototype,{[re]:{value:$n}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=W(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Xe(this.contents)&&this.contents.add(e)}addIn(e,t){Xe(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=fi(this);e.anchor=!t||n.has(t)?hi(t||"a",n):t}return new jt(e.anchor)}createNode(e,t,n){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=l(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:f}=n??{},{onAnchor:h,setAnchors:p,sourceObjects:g}=Uo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:h,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},d=lt(e,f,w);return a&&J(d)&&(d.flow=!0),p(),d}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Q(i,r)}delete(e){return Xe(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ut(e)?this.contents==null?!1:(this.contents=null,!0):Xe(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return J(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ut(e)?!t&&K(this.contents)?this.contents.value:this.contents:J(this.contents)?this.contents.getIn(e,t):void 0}has(e){return J(this.contents)?this.contents.has(e):!1}hasIn(e){return ut(e)?this.contents!==void 0:J(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ft(this.schema,[e],t):Xe(this.contents)&&this.contents.set(e,t)}setIn(e,t){ut(e)?this.contents=t:this.contents==null?this.contents=Ft(this.schema,Array.from(e),t):Xe(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let n;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new X({version:"1.1"}),n={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new X({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new gn(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=oe(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:f}of a.anchors.values())r(f,u);return typeof o=="function"?ze(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return ma(this,e)}}function Xe(s){if(J(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(Xe,"assertCollection");class Vn extends Error{static{l(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class Pe extends Vn{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Bi extends Vn{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const tn=l((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
59
  `),o=a+o}if(/[^ ]/.test(o)){let a=1;const c=t.linePos[1];c&&c.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
60
60
 
61
61
  ${o}
62
62
  ${u}
63
- `}},"prettifyError");function et(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,h="",p="",g=!1,w=!1,d=null,y=null,C=null,v=null,A=null,I=null,N=null;for(const O of s)switch(w&&(O.type!=="space"&&O.type!=="newline"&&O.type!=="comma"&&r(O.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),d&&(u&&O.type!=="comment"&&O.type!=="newline"&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),O.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&O.source.includes(" ")&&(d=O),f=!0;break;case"comment":{f||r(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const H=O.source.substring(1)||" ";h?h+=p+H:h=H,p="",u=!1;break}case"newline":u?h?h+=O.source:(!I||t!=="seq-item-ind")&&(c=!0):p+=O.source,u=!0,g=!0,(y||C)&&(v=O),f=!0;break;case"anchor":y&&r(O,"MULTIPLE_ANCHORS","A node can have at most one anchor"),O.source.endsWith(":")&&r(O.offset+O.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=O,N??(N=O.offset),u=!1,f=!1,w=!0;break;case"tag":{C&&r(O,"MULTIPLE_TAGS","A node can have at most one tag"),C=O,N??(N=O.offset),u=!1,f=!1,w=!0;break}case t:(y||C)&&r(O,"BAD_PROP_ORDER",`Anchors and tags must be after the ${O.source} indicator`),I&&r(O,"UNEXPECTED_TOKEN",`Unexpected ${O.source} in ${e??"collection"}`),I=O,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){A&&r(O,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=O,u=!1,f=!1;break}default:r(O,"UNEXPECTED_TOKEN",`Unexpected ${O.type} token`),u=!1,f=!1}const $=s[s.length-1],K=$?$.offset+$.source.length:i;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&r(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(u&&d.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:I,spaceBefore:c,comment:h,hasNewline:g,anchor:y,tag:C,newlineAfterProp:v,end:K,start:N??K}}l(et,"resolveProps");function pt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
64
- `))return!0;if(s.end){for(const e of s.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of s.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(pt(e.key)||pt(e.value))return!0}return!1;default:return!0}}l(pt,"containsNewline");function Gn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&pt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Gn,"flowIndentCheck");function qi(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||j(r)&&j(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(qi,"mapIncludes");const Ui="All mapping items must start at the same column";function ga({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??se,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,u=null;for(const f of n.items){const{start:h,key:p,sep:g,value:w}=f,d=et(h,{indicator:"explicit-key-ind",next:p??g?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!d.found;if(y){if(p&&(p.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&i(c,"BAD_INDENT",Ui)),!d.anchor&&!d.tag&&!g){u=d.end,d.comment&&(a.comment?a.comment+=`
65
- `+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||pt(p))&&i(p??h[h.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&i(c,"BAD_INDENT",Ui);t.atKey=!0;const C=d.end,v=p?s(t,p,d,i):e(t,C,h,null,d,i);t.schema.compat&&Gn(n.indent,p,i),t.atKey=!1,qi(t,a.items,v)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=et(g??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<A.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=w?s(t,w,A,i):e(t,c,g,null,A,i);t.schema.compat&&Gn(n.indent,w,i),c=I.range[2];const N=new Q(v,I);t.options.keepSourceTokens&&(N.srcToken=f),a.items.push(N)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(v.comment?v.comment+=`
66
- `+A.comment:v.comment=A.comment);const I=new Q(v);t.options.keepSourceTokens&&(I.srcToken=f),a.items.push(I)}}return u&&u<c&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,u??c],a}l(ga,"resolveBlockMap");function ya({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??Ce,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,u=null;for(const{start:f,value:h}of n.items){const p=et(f,{indicator:"seq-item-ind",next:h,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||h)h&&h.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}const g=h?s(t,h,p,i):e(t,p.end,f,null,p,i);t.schema.compat&&Gn(n.indent,h,i),c=g.range[2],a.items.push(g)}return a.range=[n.offset,c,u??c],a}l(ya,"resolveBlockSeq");function mt(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:c,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const f=c.substring(1)||" ";i?i+=o+f:i=f,o="";break}case"newline":i&&(o+=c),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:i,offset:e}}l(mt,"resolveEnd");const zn="Block collections are not allowed within flow collections",Hn=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function wa({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?se:Ce),u=new c(t.schema);u.flow=!0;const f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let h=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:v,key:A,sep:I,value:N}=C,$=et(v,{flow:a,indicator:"explicit-key-ind",next:A??I?.[0],offset:h,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!I&&!N){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
- `+$.comment:u.comment=$.comment),h=$.end;continue}!o&&t.options.strict&&pt(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let K="";e:for(const O of v)switch(O.type){case"comma":case"space":break;case"comment":K=O.source.substring(1);break e;default:break e}if(K){let O=u.items[u.items.length-1];q(O)&&(O=O.value??O.key),O.comment?O.comment+=`
68
- `+K:O.comment=K,$.comment=$.comment.substring(K.length+1)}}if(!o&&!I&&!$.found){const K=N?s(t,N,$,i):e(t,$.end,I,null,$,i);u.items.push(K),h=K.range[2],Hn(N)&&i(K.range,"BLOCK_IN_FLOW",zn)}else{t.atKey=!0;const K=$.end,O=A?s(t,A,$,i):e(t,K,v,null,$,i);Hn(A)&&i(O.range,"BLOCK_IN_FLOW",zn),t.atKey=!1;const H=et(I??[],{flow:a,indicator:"map-value-ind",next:N,offset:O.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(H.found){if(!o&&!$.found&&t.options.strict){if(I)for(const Y of I){if(Y===H.found)break;if(Y.type==="newline"){i(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<H.found.offset-1024&&i(H.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source&&N.source[0]===":"?i(N,"MISSING_CHAR",`Missing space after : in ${a}`):i(H.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ye=N?s(t,N,H,i):H.found?e(t,H.end,I,null,H,i):null;ye?Hn(N)&&i(ye.range,"BLOCK_IN_FLOW",zn):H.comment&&(O.comment?O.comment+=`
69
- `+H.comment:O.comment=H.comment);const xe=new Q(O,ye);if(t.options.keepSourceTokens&&(xe.srcToken=C),o){const Y=u;qi(t,Y.items,O)&&i(K,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(xe)}else{const Y=new se(t.schema);Y.flow=!0,Y.items.push(xe);const Cs=(ye??O).range;Y.range=[O.range[0],Cs[1],Cs[2]],u.items.push(Y)}h=ye?ye.range[2]:H.end}}const p=o?"}":"]",[g,...w]=n.end;let d=h;if(g&&g.source===p)d=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;i(h,f?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=mt(w,d,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
63
+ `}},"prettifyError");function et(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,h="",p="",g=!1,w=!1,d=null,y=null,C=null,v=null,A=null,O=null,N=null;for(const I of s)switch(w&&(I.type!=="space"&&I.type!=="newline"&&I.type!=="comma"&&r(I.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),d&&(u&&I.type!=="comment"&&I.type!=="newline"&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),I.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(d=I),f=!0;break;case"comment":{f||r(I,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const H=I.source.substring(1)||" ";h?h+=p+H:h=H,p="",u=!1;break}case"newline":u?h?h+=I.source:(!O||t!=="seq-item-ind")&&(c=!0):p+=I.source,u=!0,g=!0,(y||C)&&(v=I),f=!0;break;case"anchor":y&&r(I,"MULTIPLE_ANCHORS","A node can have at most one anchor"),I.source.endsWith(":")&&r(I.offset+I.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=I,N??(N=I.offset),u=!1,f=!1,w=!0;break;case"tag":{C&&r(I,"MULTIPLE_TAGS","A node can have at most one tag"),C=I,N??(N=I.offset),u=!1,f=!1,w=!0;break}case t:(y||C)&&r(I,"BAD_PROP_ORDER",`Anchors and tags must be after the ${I.source} indicator`),O&&r(I,"UNEXPECTED_TOKEN",`Unexpected ${I.source} in ${e??"collection"}`),O=I,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){A&&r(I,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=I,u=!1,f=!1;break}default:r(I,"UNEXPECTED_TOKEN",`Unexpected ${I.type} token`),u=!1,f=!1}const $=s[s.length-1],j=$?$.offset+$.source.length:i;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&r(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(u&&d.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:O,spaceBefore:c,comment:h,hasNewline:g,anchor:y,tag:C,newlineAfterProp:v,end:j,start:N??j}}l(et,"resolveProps");function pt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
64
+ `))return!0;if(s.end){for(const e of s.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of s.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(pt(e.key)||pt(e.value))return!0}return!1;default:return!0}}l(pt,"containsNewline");function Gn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&pt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Gn,"flowIndentCheck");function qi(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||K(r)&&K(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(qi,"mapIncludes");const Ui="All mapping items must start at the same column";function ga({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??se,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,u=null;for(const f of n.items){const{start:h,key:p,sep:g,value:w}=f,d=et(h,{indicator:"explicit-key-ind",next:p??g?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!d.found;if(y){if(p&&(p.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&i(c,"BAD_INDENT",Ui)),!d.anchor&&!d.tag&&!g){u=d.end,d.comment&&(a.comment?a.comment+=`
65
+ `+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||pt(p))&&i(p??h[h.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&i(c,"BAD_INDENT",Ui);t.atKey=!0;const C=d.end,v=p?s(t,p,d,i):e(t,C,h,null,d,i);t.schema.compat&&Gn(n.indent,p,i),t.atKey=!1,qi(t,a.items,v)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=et(g??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(c=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<A.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const O=w?s(t,w,A,i):e(t,c,g,null,A,i);t.schema.compat&&Gn(n.indent,w,i),c=O.range[2];const N=new Q(v,O);t.options.keepSourceTokens&&(N.srcToken=f),a.items.push(N)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(v.comment?v.comment+=`
66
+ `+A.comment:v.comment=A.comment);const O=new Q(v);t.options.keepSourceTokens&&(O.srcToken=f),a.items.push(O)}}return u&&u<c&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,u??c],a}l(ga,"resolveBlockMap");function ya({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??Ce,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,u=null;for(const{start:f,value:h}of n.items){const p=et(f,{indicator:"seq-item-ind",next:h,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||h)h&&h.type==="block-seq"?i(p.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}const g=h?s(t,h,p,i):e(t,p.end,f,null,p,i);t.schema.compat&&Gn(n.indent,h,i),c=g.range[2],a.items.push(g)}return a.range=[n.offset,c,u??c],a}l(ya,"resolveBlockSeq");function mt(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:c,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const f=c.substring(1)||" ";i?i+=o+f:i=f,o="";break}case"newline":i&&(o+=c),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:i,offset:e}}l(mt,"resolveEnd");const zn="Block collections are not allowed within flow collections",Hn=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function wa({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?se:Ce),u=new c(t.schema);u.flow=!0;const f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let h=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:v,key:A,sep:O,value:N}=C,$=et(v,{flow:a,indicator:"explicit-key-ind",next:A??O?.[0],offset:h,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!O&&!N){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
+ `+$.comment:u.comment=$.comment),h=$.end;continue}!o&&t.options.strict&&pt(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let j="";e:for(const I of v)switch(I.type){case"comma":case"space":break;case"comment":j=I.source.substring(1);break e;default:break e}if(j){let I=u.items[u.items.length-1];q(I)&&(I=I.value??I.key),I.comment?I.comment+=`
68
+ `+j:I.comment=j,$.comment=$.comment.substring(j.length+1)}}if(!o&&!O&&!$.found){const j=N?s(t,N,$,i):e(t,$.end,O,null,$,i);u.items.push(j),h=j.range[2],Hn(N)&&i(j.range,"BLOCK_IN_FLOW",zn)}else{t.atKey=!0;const j=$.end,I=A?s(t,A,$,i):e(t,j,v,null,$,i);Hn(A)&&i(I.range,"BLOCK_IN_FLOW",zn),t.atKey=!1;const H=et(O??[],{flow:a,indicator:"map-value-ind",next:N,offset:I.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(H.found){if(!o&&!$.found&&t.options.strict){if(O)for(const Y of O){if(Y===H.found)break;if(Y.type==="newline"){i(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<H.found.offset-1024&&i(H.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else N&&("source"in N&&N.source&&N.source[0]===":"?i(N,"MISSING_CHAR",`Missing space after : in ${a}`):i(H.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ye=N?s(t,N,H,i):H.found?e(t,H.end,O,null,H,i):null;ye?Hn(N)&&i(ye.range,"BLOCK_IN_FLOW",zn):H.comment&&(I.comment?I.comment+=`
69
+ `+H.comment:I.comment=H.comment);const xe=new Q(I,ye);if(t.options.keepSourceTokens&&(xe.srcToken=C),o){const Y=u;qi(t,Y.items,I)&&i(j,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(xe)}else{const Y=new se(t.schema);Y.flow=!0,Y.items.push(xe);const Cs=(ye??I).range;Y.range=[I.range[0],Cs[1],Cs[2]],u.items.push(Y)}h=ye?ye.range[2]:H.end}}const p=o?"}":"]",[g,...w]=n.end;let d=h;if(g&&g.source===p)d=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;i(h,f?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=mt(w,d,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
70
  `+y.comment:u.comment=y.comment),u.range=[n.offset,d,y.offset]}else u.range=[n.offset,d,d];return u}l(wa,"resolveFlowCollection");function Yn(s,e,t,n,i,r){const o=t.type==="block-map"?ga(s,e,t,n,r):t.type==="block-seq"?ya(s,e,t,n,r):wa(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(Yn,"resolveCollection");function ba(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,p=>i(r,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){const{anchor:p,newlineAfterProp:g}=n,w=p&&r?p.offset>r.offset?p:r:p??r;w&&(!g||g.offset<w.offset)&&i(w,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!r||!o||o==="!"||o===se.tagName&&a==="map"||o===Ce.tagName&&a==="seq")return Yn(s,e,t,i,o);let c=e.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!c){const p=e.schema.knownTags[o];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),c=p;else return p?i(r,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Yn(s,e,t,i,o)}const u=Yn(s,e,t,i,o,c),f=c.resolve?.(u,p=>i(r,"TAG_RESOLVE_FAILED",p),e.options)??u,h=W(f)?f:new L(f);return h.range=u.range,h.tag=o,c?.format&&(h.format=c.format),h}l(ba,"composeCollection");function Ji(s,e,t){const n=e.offset,i=Sa(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?Ca(e.source):[];let a=o.length;for(let d=o.length-1;d>=0;--d){const y=o[d][1];if(y===""||y==="\r")a=d;else break}if(a===0){const d=i.chomp==="+"&&o.length>0?`
71
71
  `.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:d,type:r,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,u=e.offset+i.length,f=0;for(let d=0;d<a;++d){const[y,C]=o[d];if(C===""||C==="\r")i.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=y.length),f=d,c===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+C.length+1}for(let d=o.length-1;d>=a;--d)o[d][0].length>c&&(a=d+1);let h="",p="",g=!1;for(let d=0;d<f;++d)h+=o[d][0].slice(c)+`
72
- `;for(let d=f;d<a;++d){let[y,C]=o[d];u+=y.length+C.length+1;const v=C[C.length-1]==="\r";if(v&&(C=C.slice(0,-1)),C&&y.length<c){const I=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(v?2:1),"BAD_INDENT",I),y=""}r===L.BLOCK_LITERAL?(h+=p+y.slice(c)+C,p=`
72
+ `;for(let d=f;d<a;++d){let[y,C]=o[d];u+=y.length+C.length+1;const v=C[C.length-1]==="\r";if(v&&(C=C.slice(0,-1)),C&&y.length<c){const O=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(v?2:1),"BAD_INDENT",O),y=""}r===L.BLOCK_LITERAL?(h+=p+y.slice(c)+C,p=`
73
73
  `):y.length>c||C[0]===" "?(p===" "?p=`
74
74
  `:!g&&p===`
75
75
  `&&(p=`
@@ -97,7 +97,7 @@ ${u}
97
97
  `);)n===`
98
98
  `&&(t+=`
99
99
  `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}l(Ea,"foldNewline");const Ia={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
100
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Oa(s,e,t,n){const i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}l(Oa,"parseCharCode");function Gi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Ji(s,e,n):Wi(e,s.options.strict,n),c=t?s.directives.tagName(t.source,h=>n(t,"TAG_RESOLVE_FAILED",h)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:c?u=Aa(s.schema,i,c,t,n):e.type==="scalar"?u=Na(s,i,e,n):u=s.schema[fe];let f;try{const h=u.resolve(i,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);f=j(h)?h:new L(h)}catch(h){const p=h instanceof Error?h.message:String(h);n(t??e,"TAG_RESOLVE_FAILED",p),f=new L(i)}return f.range=a,f.source=i,r&&(f.type=r),c&&(f.tag=c),u.format&&(f.format=u.format),o&&(f.comment=o),f}l(Gi,"composeScalar");function Aa(s,e,t,n,i){if(t==="!")return s[fe];const r=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)r.push(a);else return a;for(const a of r)if(a.test?.test(e))return a;const o=s.knownTags[t];return o&&!o.collection?(s.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[fe])}l(Aa,"findScalarTagByName");function Na({atKey:s,directives:e,schema:t},n,i,r){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[fe];if(t.compat){const a=t.compat.find(c=>c.default&&c.test?.test(n))??t[fe];if(o.tag!==a.tag){const c=e.tagString(o.tag),u=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;r(i,"TAG_RESOLVE_FAILED",f,!0)}}return o}l(Na,"findScalarTagByTest");function $a(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":s-=i.source.length;continue}for(i=e[++n];i?.type==="space";)s+=i.source.length,i=e[++n];break}}return s}l($a,"emptyScalarPosition");const Pa={composeNode:zi,composeEmptyNode:Zn};function zi(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=t;let u,f=!0;switch(e.type){case"alias":u=La(s,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=Gi(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=ba(Pa,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const h=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",h),u=Zn(s,e.offset,void 0,null,t,n),f=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!j(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&f&&(u.srcToken=e),u}l(zi,"composeNode");function Zn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const f={type:"scalar",offset:$a(e,t,n),indent:-1,source:""},h=Gi(s,f,a,u);return o&&(h.anchor=o.source.substring(1),h.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(h.spaceBefore=!0),r&&(h.comment=r,h.range[2]=c),h}l(Zn,"composeEmptyNode");function La({options:s},{offset:e,source:t,end:n},i){const r=new jt(t.substring(1));r.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),r.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=mt(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(La,"composeAlias");function xa(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),c=new rt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=et(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?zi(u,i,f,o):Zn(u,f.end,n,null,f,o);const h=c.contents.range[2],p=mt(r,h,!1,o);return p.comment&&(c.comment=p.comment),c.range=[t,h,p.offset],c}l(xa,"composeDoc");function gt(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}l(gt,"getErrorPos");function Hi(s){let e="",t=!1,n=!1;for(let i=0;i<s.length;++i){const r=s[i];switch(r[0]){case"#":e+=(e===""?"":n?`
100
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Oa(s,e,t,n){const i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}l(Oa,"parseCharCode");function Gi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Ji(s,e,n):Wi(e,s.options.strict,n),c=t?s.directives.tagName(t.source,h=>n(t,"TAG_RESOLVE_FAILED",h)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:c?u=Aa(s.schema,i,c,t,n):e.type==="scalar"?u=Na(s,i,e,n):u=s.schema[fe];let f;try{const h=u.resolve(i,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);f=K(h)?h:new L(h)}catch(h){const p=h instanceof Error?h.message:String(h);n(t??e,"TAG_RESOLVE_FAILED",p),f=new L(i)}return f.range=a,f.source=i,r&&(f.type=r),c&&(f.tag=c),u.format&&(f.format=u.format),o&&(f.comment=o),f}l(Gi,"composeScalar");function Aa(s,e,t,n,i){if(t==="!")return s[fe];const r=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)r.push(a);else return a;for(const a of r)if(a.test?.test(e))return a;const o=s.knownTags[t];return o&&!o.collection?(s.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[fe])}l(Aa,"findScalarTagByName");function Na({atKey:s,directives:e,schema:t},n,i,r){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[fe];if(t.compat){const a=t.compat.find(c=>c.default&&c.test?.test(n))??t[fe];if(o.tag!==a.tag){const c=e.tagString(o.tag),u=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;r(i,"TAG_RESOLVE_FAILED",f,!0)}}return o}l(Na,"findScalarTagByTest");function $a(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":s-=i.source.length;continue}for(i=e[++n];i?.type==="space";)s+=i.source.length,i=e[++n];break}}return s}l($a,"emptyScalarPosition");const Pa={composeNode:zi,composeEmptyNode:Zn};function zi(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=t;let u,f=!0;switch(e.type){case"alias":u=La(s,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=Gi(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=ba(Pa,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const h=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",h),u=Zn(s,e.offset,void 0,null,t,n),f=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!K(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&f&&(u.srcToken=e),u}l(zi,"composeNode");function Zn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const f={type:"scalar",offset:$a(e,t,n),indent:-1,source:""},h=Gi(s,f,a,u);return o&&(h.anchor=o.source.substring(1),h.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(h.spaceBefore=!0),r&&(h.comment=r,h.range[2]=c),h}l(Zn,"composeEmptyNode");function La({options:s},{offset:e,source:t,end:n},i){const r=new jt(t.substring(1));r.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),r.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=mt(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(La,"composeAlias");function xa(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),c=new rt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=et(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?zi(u,i,f,o):Zn(u,f.end,n,null,f,o);const h=c.contents.range[2],p=mt(r,h,!1,o);return p.comment&&(c.comment=p.comment),c.range=[t,h,p.offset],c}l(xa,"composeDoc");function gt(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}l(gt,"getErrorPos");function Hi(s){let e="",t=!1,n=!1;for(let i=0;i<s.length;++i){const r=s[i];switch(r[0]){case"#":e+=(e===""?"":n?`
101
101
 
102
102
  `:`
103
103
  `)+(r.substring(1)||" "),t=!0,n=!1;break;case"%":s[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}l(Hi,"parsePrelude");class Qn{static{l(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=gt(t);r?this.warnings.push(new Bi(o,n,i)):this.errors.push(new Pe(o,n,i))},this.directives=new X({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Hi(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
@@ -137,9 +137,9 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
137
137
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
138
  `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ve(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(ir(t.key)&&!ve(t.sep,"newline")){const o=tt(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ve(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=tt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ve(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ve(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ve(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const i=ln(n),r=tt(i);rr(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
139
139
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=ln(e),n=tt(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=ln(e),n=tt(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 or(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new nr||null,prettyErrors:e}}l(or,"parseOptions");function Va(s,e={}){const{lineCounter:t,prettyErrors:n}=or(e),i=new ns(t?.addNewLine),r=new Qn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(tn(s,t)),a.warnings.forEach(tn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Va,"parseAllDocuments");function ar(s,e={}){const{lineCounter:t,prettyErrors:n}=or(e),i=new ns(t?.addNewLine),r=new Qn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Pe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(tn(s,t)),o.warnings.forEach(tn(s,t))),o}l(ar,"parseDocument");function Ga(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=ar(s,t);if(!i)return null;if(i.warnings.forEach(r=>wi(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}l(Ga,"parse");function za(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Oe(s)&&!n?s.toString(t):new rt(s,n,t).toString(t)}l(za,"stringify");var Ha=Object.freeze({__proto__:null,Alias:jt,CST:Ua,Composer:Qn,Document:rt,Lexer:tr,LineCounter:nr,Pair:Q,Parser:ns,Scalar:L,Schema:gn,YAMLError:Vn,YAMLMap:se,YAMLParseError:Pe,YAMLSeq:Ce,YAMLWarning:Bi,isAlias:Se,isCollection:J,isDocument:Oe,isMap:Je,isNode:W,isPair:q,isScalar:j,isSeq:We,parse:Ga,parseAllDocuments:Va,parseDocument:ar,stringify:za,visit:Ae,visitAsync:Mt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Ya={ignored:Ao,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 Za extends In{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ct(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=zr.watch(this.membraneDir,Ya),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=_.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=_.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=_.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=_.relative(this.membraneDir,e);let i;try{i=t?Ha.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Vr.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=_.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=_.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var cr=(s=>(s.Updated="updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(cr||{});const Qa={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class Xa extends In{static{l(this,"RemoteElementWatcher")}constructor(e=Qa){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await F.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;T.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new Hr(n),this.setupEventSourceHandlers()}catch(e){T.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{T.info("[remote-watcher] Connected to workspace events"),this.reconnectAttempts=0,this.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){T.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{T.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Kr.ElementUpdate)return;const{elementId:t,elementType:n}=e;!t||!n||this.scheduleElementUpdate(t,n)}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&T.error("[remote-watcher] Max reconnect attempts reached, giving up");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);T.info(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class lr{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function ec(s="full"){const e={};T.info("[connectors] Getting remote workspace data");const t=await F.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>ss("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];T.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await F.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>ss(n,a))),i.integrationSpecific)for(const a of t){const c=await F.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,ss(n,u))))}r.length>0&&s=="full"&&(console.table(r.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,c)=>(a||(a={}),a[c.key]||(a[c.key]={}),c.universal&&(a[c.key].universal=!0),c.integrationKey&&(a[c.key].integration?a[c.key].integration+=` ${c.integrationKey}`:a[c.key].integration=c.integrationKey),a),{})),console.groupEnd()),e[n]=r}return T.success("[connectors] Remote workspace data retrieved successfully"),e}l(ec,"getWorkspaceData");function ss(s,e){return e=Io(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(ss,"cleanUpForExport");const wt="connectors",bt="development",is={};async function tc({integrations:s,allConnectors:e=!1}){const t=Lo(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(!i[o]?.has(r.connectorVersion)){const c=await ur({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){T.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await oc({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await ac({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(tc,"pullConnectors");async function nc(){const s=await ec("minified"),t=(await F.withClient(c=>c.get("org-workspace-id"))).id,n={};T.info("[connectors] Loading custom connectors");const i=await F.withClient(c=>c.get(`/connectors?workspaceId=${t}`));T.info("[connectors] Loading public connectors"),s.connector=i;const r=rs(),a=(M.existsSync(r)?M.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=U.join(r,c);try{return M.statSync(u).isDirectory()}catch{return!1}});for(const c of a){T.info(`[connectors] Loading connector from: ${c}`);const u=M.readdirSync(U.join(r,c)),f=await os(c);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,T.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await ur({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){T.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await F.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const h=u.filter(p=>M.statSync(U.join(r,c,p)).isDirectory());for(const p of h)await rc({connector:f,version:p,connectorId:n[f.id]})}return n}l(nc,"pushConnectors");function rs(){const s=An();return U.join(s.membraneDirPath,wt)}l(rs,"getConnectorsPath");async function os(s){const e=U.join(rs(),s,`${s}.yml`);if(M.existsSync(e))return Ie.load(M.readFileSync(e,"utf8"))}l(os,"readConnector");async function sc(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=Yr("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const c=U.join(s,a),u=M.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(sc,"createZipArchive");async function ic(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=Qr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=U.join(e,o);M.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=U.join(e,o),u=U.dirname(c);M.mkdirSync(u,{recursive:!0});const f=M.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(ic,"extractZipArchive");async function rc({connector:s,version:e,connectorId:t}){const n=U.join(rs(),un(s),fr(e)),i=U.join(n,"src"),r=U.join(n,"src.zip"),o=M.existsSync(r);if(M.existsSync(i)&&(T.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await sc(i,r)),!M.existsSync(r)){T.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Zr;if(a.append("file",M.createReadStream(r),"file.zip"),T.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==bt)T.info(`[connectors] Uploading connector ${t}`),await F.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await F.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){T.info(`[connectors] Version ${e} already published`);return}T.info(`[connectors] Publishing version ${e} of connector ${t}`),await F.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}T.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){T.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&M.existsSync(r)&&(T.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),M.unlinkSync(r))}}l(rc,"pushConnectorVersion");async function ur({connectorId:s}){if(is[s])return is[s];const e=await F.withClient(t=>t.get(`connectors/${s}`));return is[s]=e,e}l(ur,"getConnector");async function oc({basePath:s,connector:e}){const t=un(e),n=U.join(s,wt,t);M.mkdirSync(n,{recursive:!0});const i=U.join(n,`${un(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}l(oc,"pullConnector");async function ac({connector:s,connectorVersion:e,basePath:t}){const n=un(s),i=fr(e),r=U.join(t,"connectors",n,i),o=await F.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));M.mkdirSync(r,{recursive:!0});const a=U.join(r,"src.zip");if(M.writeFileSync(a,o),!e){const c=U.join(r,"src");M.mkdirSync(c,{recursive:!0}),await ic(o,c)}T.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(ac,"pullConnectorVersion");function un(s){return s.key}l(un,"getConnectorDirName");function fr(s){return s??bt}l(fr,"getConnectorVersionDirName");function cc(s){return s.match(`${wt}/[^/]+/${bt}/src/.*`)!==null}l(cc,"isConnectorSourceFile");async function lc(s){const e=s.match(`${wt}/([^/]+)/${bt}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await os(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await F.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(lc,"putConnectorFile");async function uc(s){const e=s.match(`${wt}/([^/]+)/${bt}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await os(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await F.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(uc,"deleteConnectorFile");const hr=[R.DataSource,R.FieldMapping,R.Action,R.Flow];class kt{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new lr,this.remoteCache=new lr,this.localRepo=new Ko(this.localCache),this.remoteRepo=new Fo(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw T.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw T.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await tc({integrations:this.remoteCache.getElementsByType(R.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await nc();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ee.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ee.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Za({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ie.Updated,e=>this.handleLocalEvent(e,ie.Updated)),this.localWatcher.on(ie.Deleted,e=>this.handleLocalEvent(e,ie.Deleted)),await this.localWatcher.start(),T.success("[local] Tracking changes.."),this.remoteWatcher=new Xa,this.remoteWatcher.on(cr.Updated,({elementId:e,elementType:t})=>this.handleRemoteEvent(e,t)),await this.remoteWatcher.start(),T.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 handleRemoteEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(T.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return T.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){T.error(`[sync] Error handling remote event: ${n}`)}}async handleLocalEvent(e,t){try{if(cc(e.filePath))switch(t){case ie.Updated:await lc(e.filePath);break;case ie.Deleted:await uc(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const i=z.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(T.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${Eo.toSentenceCase(t)}: ${n.id}`),t){case ie.Updated:await this.updateElement(n,ee.OUTGOING);break;case ie.Deleted:await this.deleteElement(n,ee.OUTGOING);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=kt.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=kt.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;T.info("[resolver] Resolving changes.."),T.info("[resolver] Resolving integration elements");const e=this.changes.filter(i=>i.element.type===R.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ee.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==R.Integration)),T.info("[resolver] Resolving universal elements");const t=this.changes.filter(i=>!i.element.hasParent());for(const i of hr){const r=t.filter(o=>o.element.type===i);T.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}T.info("[resolver] Resolving integration level elements");const n=this.changes.filter(i=>i.element.hasParent());for(const i of hr){const r=n.filter(o=>o.element.type===i);T.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}T.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case de.DELETE:return this.deleteElement(e.element,e.direction);case de.CREATE:return this.updateElement(e.element,e.direction);case de.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),h=kt.detectChangeForElement(u,f,e);h&&a.push(h)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);T.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:de.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:de.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:de.UPDATE,element:e,direction:n,isConflict:!0}:null}}const ke=_.join(Xr.tmpdir(),"membrane-mcp-status"),dr=3e4;class fc{static{l(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fn(void 0,e),n=pr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function fn(s,e){try{const t=e||process.cwd();if(!s){const i=pr(t);return i.length===0?null:i[0]}const n=ls(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>dr)return St(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>dr)return St(s,t),null}return c}}catch{s&&e&&St(s,e)}return null}l(fn,"getMcpStatus");function pr(s){try{const e=s||process.cwd(),t=cs(e);if(!x.existsSync(ke))return[];const n=x.readdirSync(ke),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=fn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(pr,"getAllMcpStatusFiles");function as(s){try{const t={...fn(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(ke)||x.mkdirSync(ke,{recursive:!0});const n=ls(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(as,"updateMcpStatus");function St(s,e){try{const t=e||process.cwd();if(s){const n=ls(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=cs(t);if(x.existsSync(ke)){const i=x.readdirSync(ke);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(_.join(ke,r))}}}catch{}}l(St,"clearMcpStatus");function hc(s,e){const t=fn(s,e);t&&as({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(hc,"trackToolExecution");function cs(s){return Gr("md5").update(s).digest("hex").slice(0,8)}l(cs,"getCwdHash");function ls(s,e){const t=cs(e);return _.join(ke,`mcp-${t}-${s}.json`)}l(ls,"getStatusFilePath");const Ct={Agent:"agent",Cli:"cli"},P={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 mr{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=pe,this.mcpStatusService=new fc,this.syncService=new kt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(P.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){T.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(P.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){T.error(`Failed to push workspace: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async syncWorkspaces(e={}){try{await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}catch(t){T.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),at.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){T.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=at.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const i=at.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Ct.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Ct.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Ct.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 gr=vs(null);function dc({children:s,membraneCLIService:e}){const{data:t}=Ts("/account"),[n,i]=B(P.NOT_INITIALIZED),[r,o]=B([]),[a,c]=B({}),[u,f]=B([]),[h,p]=B(null),w=t?.workspaces?.find(d=>d.workspaceKey===h?.workspaceKey)||null;return Ee(()=>{const d=l(({state:I})=>i(I),"handleStateChanged"),y=l(({stats:I})=>c(I),"handleStatsChanged"),C=l(({log:I})=>f(N=>[...N,I]),"handleLogAdded"),v=l(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=l(({config:I})=>p(I),"handleConfigChanged");return e.notifier.on(V.StateChanged,d),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,C),e.notifier.on(V.ConflictsChanged,v),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,d),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,C),e.notifier.off(V.ConflictsChanged,v),e.notifier.off(V.ConfigChanged,A)}},[]),m(gr.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:h,updateConfig:l(d=>e.updateConfig(d),"updateConfig"),resolveConflicts:l(d=>e.syncWorkspaces(d),"resolveConflicts"),pull:l(d=>e.pullWorkspace(d),"pull"),push:l(d=>e.pushWorkspace(d),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(dc,"MembraneCLIServiceProvider");function le(){const s=ks(gr);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const yr=vs(process.cwd());function pc({cwd:s,children:e}){return m(yr.Provider,{value:s,children:e})}l(pc,"CwdProvider");function mc(){return ks(yr)}l(mc,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(pc,{cwd:n,children:m(_r,{value:{fetcher:_o()},children:m(dc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const us=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=_.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const s=_.join(process.cwd(),".cursor"),e=_.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function gc({onExit:s,onComplete:e}){const[t,n]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[f,h]=B("");De((w,d)=>{if(c||f){(d.escape||w==="q"||d.return)&&e();return}if(i)d.return||w===" "?p(o):d.escape&&(r(!1),a(null));else if(d.escape)s();else if(d.upArrow||w==="k")n(Math.max(0,t-1));else if(d.downArrow||w==="j")n(Math.min(us.length-1,t+1));else if(d.return||w===" "){const y=us[t];a(y),r(!0)}});const p=l(w=>{try{const d=w.addConfig();u(d)}catch(d){h(`Failed to write configuration: ${d.message||d}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:c}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:f})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:us.map((w,d)=>E(b,{children:[E(S,{color:t===d?"cyan":"white",children:[t===d?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(gc,"AddMcpServerScreen");function yc(){const[s,e]=B(null),[t,n]=B([]),[i,r]=B(null);return Ee(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(yc,"useMcpStatus");function wc(){const{error:s,serverCount:e,allMcpServers:t}=yc(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(xr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}l(wc,"Agent");const dn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function wr(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(wr,"truncateText");function fs({children:s}){const{state:e,logs:t}=le();if(!e||e===P.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(to,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===P.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===P.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:dn(i.type),children:i.message},i.timestamp+r))})}return s}l(fs,"EnsureInitialized");function br({onExit:s,showEscOption:e=!0}){const[t,n]=B(""),{data:i,error:r,isLoading:o}=Ts("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(De((d,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(It,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(d=>d.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(d=>({label:d.name,value:d.id})),p=h.length,g=c?.length??0;async function w(d){const y=f.find(A=>A.id===d);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return l(w,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(no,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",p," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(so,{options:h,onChange:l(d=>{d&&w(d)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}l(br,"SelectWorkspace");function bc({currentPat:s,onSubmit:e}){const[t,n]=B(""),[i,r]=B(!1),[o,a]=B(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(io,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:E(S,{children:[m(It,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}l(bc,"PersonalAccessTokenInput");var vt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(vt||{});const Sc={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hs=[vt.Authenticate,vt.ConnectWorkspace];function Sr({onComplete:s}){const{config:e}=le(),[t,n]=B(!1),[i,r]=B(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ei(),c=hs[i],u=i+1,f=hs.length,h=hs.map((w,d)=>{let y="pending";return d<i?y="done":d===i&&(y="current"),{id:w,label:Sc[w],status:y}});async function p(w){const d=a&&w===""?a:w,y=new ti;try{await y.request("/account",{headers:{Authorization:`Bearer ${d}`}}),Do(d),r(C=>C+1)}catch(C){console.error(C)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),De((w,d)=>{o&&d.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:h.map(w=>m(Cc,{status:w.status,label:w.label},w.id))})]}),c===vt.Authenticate&&m(bc,{currentPat:a,onSubmit:p}),c===vt.ConnectWorkspace&&m(br,{onExit:g,showEscOption:!1})]})}l(Sr,"Setup");function Cc({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(It,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}l(Cc,"StepDisplay");function ds(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}l(ds,"ElementStats");const ps=5,vc=6;function kc(){const{logs:s}=le(),[e,t]=B(0),n=Math.min(100,process.stdout.columns||100),i=ps,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-vc,u=e<s.length-i,f=e>0;return De((h,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(h==="G"||h==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>ps&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((h,p)=>m(b,{marginLeft:1,children:m(S,{color:dn(h.type),children:wr(h.message,c)})},h.timestamp+p)),s.length>ps&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),f&&m(S,{color:"grey",children:"\u2193 "})]})]})}l(kc,"Logs");const pn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Tc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=B(0),[r,o]=B(!1),[a,c]=B(!1);return De((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(h=>h>0?h-1:pn.length-1):f.downArrow?i(h=>h<pn.length-1?h+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),pn[n].value==="sync"?e({watch:!0}):t())}}),Ee(()=>{s!==P.CONFLICTS&&r&&o(!1)},[s,r]),E(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(ms,{isExpanded:a})}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?E(b,{flexDirection:"row",gap:1,children:[m(It,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:pn.map((u,f)=>m(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(S,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(Tc,"ResolveChangesUI");const Ec={[de.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[de.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[de.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ms({isExpanded:s}){const{conflicts:e}=le(),t=5,n=Rr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(b,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=Ec[o][a];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[c.label," (",r.length,")"]}),m(S,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(b,{marginLeft:2,children:E(S,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(b,{marginLeft:2,children:m(S,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ms,"Conflicts");function Ic(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?wr(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Ac(e),children:[" [",Oc(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(Tc,{}):E(yn,{children:[m(b,{paddingTop:1,children:m(ds,{})}),t.length>0&&m(kc,{})]})]})}l(Ic,"Workspace");function Oc(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}l(Oc,"getStatusDisplay");function Ac(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}l(Ac,"getStatusColor");const Nc="https://console.integration.app/w";function $c(){const s=mc(),e=Mr(!0),{exit:t,state:n}=le(),[i,r]=B(null),o=i??(n===P.SETTING_UP?"setup":"main");De(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===P.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ni(s),u=`${Nc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";eo(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(br,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(gc,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(Sr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(fs,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(wc,{})}),m(Ic,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}l($c,"Main");const Cr=Dr(process.argv.slice(2)),vr=Cr.cwd?$r(Cr.cwd):process.cwd(),Pc=new mr(Ct.Agent,vr),Lc=l(()=>m(hn,{cwd:vr,membraneCLIService:Pc,children:m($c,{})}),"App");function xc(){Tt(m(Lc,{}))}l(xc,"runAgent");function Dc(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
141
- `)).action(t=>{t.key&&t.secret?at.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)):Tt(_e.createElement(hn,{membraneCLIService:e,children:_e.createElement(Sr,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Dc,"setupInitCommand");async function kr(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return Cn.sign(t,e)}l(kr,"generateAdminAccessToken");async function _c(s,e){return(await vn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(_c,"fetchOpenApiSchema");function Tr(s,e=!0){if(!s)return e?Z.string():Z.string().optional();let t;switch(s.type){case"integer":t=Z.coerce.number().int();break;case"number":t=Z.coerce.number();break;case"boolean":t=Z.coerce.boolean();break;case"string":default:t=Z.string();break}return s.format==="uuid"?t=Z.string().uuid():s.format==="email"?t=Z.string().email():s.format==="date"?t=Z.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=Z.string().datetime()),s.enum&&(t=Z.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}l(Tr,"convertOpenApiSchemaToZod");function Er(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(Er,"extractPathParameters");function Rc(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,c={},u={},f={};if(s.parameters){for(const p of s.parameters)if(p.in==="path")u[p.name]=Tr(p.schema,!0).describe(p.description||`Path parameter: ${p.name}`);else if(p.in==="query"){const g=p.required===!0;f[p.name]=Tr(p.schema,g).describe(p.description||`Query parameter: ${p.name}`)}}Object.keys(u).length>0&&(c.params=Z.object(u).describe("Path parameters")),Object.keys(f).length>0&&(c.query=Z.object(f).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(c.body=Z.any().describe("Request body"));const h=Object.keys(c).length>0?Z.object(c):Z.object({});return{name:o,description:a,parameters:h,async execute(p){try{const g=Er(e);if(g.length>0){if(!p.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const I=g.filter(N=>!(N in p.params));if(I.length>0)throw new Error(`Missing required path parameters: ${I.join(", ")}`)}let w=`${n}${e}`;if(p.params)for(const[I,N]of Object.entries(p.params)){const $=`{${I}}`;w.includes($)&&(w=w.replace($,String(N)))}const d=Er(w);if(d.length>0)throw new Error(`Unresolved path parameters: ${d.join(", ")}`);const y=new URLSearchParams;if(p.query)for(const[I,N]of Object.entries(p.query))N!=null&&y.append(I,String(N));y.toString()&&(w+=`?${y.toString()}`);const C=await kr(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};p.body&&t.toLowerCase()!=="get"&&(v.data=p.body);const A=await vn.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return vn.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(Rc,"createApiTool");function Mc(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,c]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&c&&typeof c=="object"){const u=Rc(c,r,a,e,t,n);i.push(u)}}return i}l(Mc,"convertOpenApiToTools");function jc(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
142
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Rt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||On,n=await kr(e.workspaceKey,e.workspaceSecret),i=await _c(t,n),r=Mc(i,t,e.workspaceKey,e.workspaceSecret),o=new ao({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
140
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=ln(e),n=tt(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=ln(e),n=tt(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 or(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new nr||null,prettyErrors:e}}l(or,"parseOptions");function Va(s,e={}){const{lineCounter:t,prettyErrors:n}=or(e),i=new ns(t?.addNewLine),r=new Qn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(tn(s,t)),a.warnings.forEach(tn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Va,"parseAllDocuments");function ar(s,e={}){const{lineCounter:t,prettyErrors:n}=or(e),i=new ns(t?.addNewLine),r=new Qn(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Pe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(tn(s,t)),o.warnings.forEach(tn(s,t))),o}l(ar,"parseDocument");function Ga(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=ar(s,t);if(!i)return null;if(i.warnings.forEach(r=>wi(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}l(Ga,"parse");function za(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Oe(s)&&!n?s.toString(t):new rt(s,n,t).toString(t)}l(za,"stringify");var Ha=Object.freeze({__proto__:null,Alias:jt,CST:Ua,Composer:Qn,Document:rt,Lexer:tr,LineCounter:nr,Pair:Q,Parser:ns,Scalar:L,Schema:gn,YAMLError:Vn,YAMLMap:se,YAMLParseError:Pe,YAMLSeq:Ce,YAMLWarning:Bi,isAlias:Se,isCollection:J,isDocument:Oe,isMap:Je,isNode:W,isPair:q,isScalar:K,isSeq:We,parse:Ga,parseAllDocuments:Va,parseDocument:ar,stringify:za,visit:Ae,visitAsync:Mt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Ya={ignored:Ao,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 Za extends In{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ct(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=zr.watch(this.membraneDir,Ya),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=_.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=_.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=_.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=_.relative(this.membraneDir,e);let i;try{i=t?Ha.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Vr.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=_.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=_.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var cr=(s=>(s.Updated="updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(cr||{});const Qa={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class Xa extends In{static{l(this,"RemoteElementWatcher")}constructor(e=Qa){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await F.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;T.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new Hr(n),this.setupEventSourceHandlers()}catch(e){T.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{T.info("[remote-watcher] Connected to workspace events"),this.reconnectAttempts=0,this.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){T.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{T.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Kr.ElementUpdate)return;const{elementId:t,elementType:n}=e;!t||!n||this.scheduleElementUpdate(t,n)}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&T.error("[remote-watcher] Max reconnect attempts reached, giving up");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);T.info(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class lr{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function ec(s="full"){const e={};T.info("[connectors] Getting remote workspace data");const t=await F.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>ss("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];T.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await F.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>ss(n,a))),i.integrationSpecific)for(const a of t){const c=await F.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,ss(n,u))))}r.length>0&&s=="full"&&(console.table(r.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,c)=>(a||(a={}),a[c.key]||(a[c.key]={}),c.universal&&(a[c.key].universal=!0),c.integrationKey&&(a[c.key].integration?a[c.key].integration+=` ${c.integrationKey}`:a[c.key].integration=c.integrationKey),a),{})),console.groupEnd()),e[n]=r}return T.success("[connectors] Remote workspace data retrieved successfully"),e}l(ec,"getWorkspaceData");function ss(s,e){return e=Io(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(ss,"cleanUpForExport");const wt="connectors",bt="development",is={};async function tc({integrations:s,allConnectors:e=!1}){const t=Lo(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(!i[o]?.has(r.connectorVersion)){const c=await ur({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){T.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await oc({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await ac({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(tc,"pullConnectors");async function nc(){const s=await ec("minified"),t=(await F.withClient(c=>c.get("org-workspace-id"))).id,n={};T.info("[connectors] Loading custom connectors");const i=await F.withClient(c=>c.get(`/connectors?workspaceId=${t}`));T.info("[connectors] Loading public connectors"),s.connector=i;const r=rs(),a=(M.existsSync(r)?M.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=U.join(r,c);try{return M.statSync(u).isDirectory()}catch{return!1}});for(const c of a){T.info(`[connectors] Loading connector from: ${c}`);const u=M.readdirSync(U.join(r,c)),f=await os(c);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,T.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await ur({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){T.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await F.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const h=u.filter(p=>M.statSync(U.join(r,c,p)).isDirectory());for(const p of h)await rc({connector:f,version:p,connectorId:n[f.id]})}return n}l(nc,"pushConnectors");function rs(){const s=An();return U.join(s.membraneDirPath,wt)}l(rs,"getConnectorsPath");async function os(s){const e=U.join(rs(),s,`${s}.yml`);if(M.existsSync(e))return Ie.load(M.readFileSync(e,"utf8"))}l(os,"readConnector");async function sc(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=Yr("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const c=U.join(s,a),u=M.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(sc,"createZipArchive");async function ic(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=Qr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=U.join(e,o);M.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=U.join(e,o),u=U.dirname(c);M.mkdirSync(u,{recursive:!0});const f=M.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(ic,"extractZipArchive");async function rc({connector:s,version:e,connectorId:t}){const n=U.join(rs(),un(s),fr(e)),i=U.join(n,"src"),r=U.join(n,"src.zip"),o=M.existsSync(r);if(M.existsSync(i)&&(T.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await sc(i,r)),!M.existsSync(r)){T.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Zr;if(a.append("file",M.createReadStream(r),"file.zip"),T.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==bt)T.info(`[connectors] Uploading connector ${t}`),await F.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await F.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){T.info(`[connectors] Version ${e} already published`);return}T.info(`[connectors] Publishing version ${e} of connector ${t}`),await F.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}T.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){T.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&M.existsSync(r)&&(T.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),M.unlinkSync(r))}}l(rc,"pushConnectorVersion");async function ur({connectorId:s}){if(is[s])return is[s];const e=await F.withClient(t=>t.get(`connectors/${s}`));return is[s]=e,e}l(ur,"getConnector");async function oc({basePath:s,connector:e}){const t=un(e),n=U.join(s,wt,t);M.mkdirSync(n,{recursive:!0});const i=U.join(n,`${un(e)}.yml`);M.writeFileSync(i,Ie.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}l(oc,"pullConnector");async function ac({connector:s,connectorVersion:e,basePath:t}){const n=un(s),i=fr(e),r=U.join(t,"connectors",n,i),o=await F.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));M.mkdirSync(r,{recursive:!0});const a=U.join(r,"src.zip");if(M.writeFileSync(a,o),!e){const c=U.join(r,"src");M.mkdirSync(c,{recursive:!0}),await ic(o,c)}T.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(ac,"pullConnectorVersion");function un(s){return s.key}l(un,"getConnectorDirName");function fr(s){return s??bt}l(fr,"getConnectorVersionDirName");function cc(s){return s.match(`${wt}/[^/]+/${bt}/src/.*`)!==null}l(cc,"isConnectorSourceFile");async function lc(s){const e=s.match(`${wt}/([^/]+)/${bt}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await os(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await F.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(lc,"putConnectorFile");async function uc(s){const e=s.match(`${wt}/([^/]+)/${bt}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await os(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await F.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(uc,"deleteConnectorFile");const hr=[R.DataSource,R.FieldMapping,R.Action,R.Flow];class kt{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new lr,this.remoteCache=new lr,this.localRepo=new Ko(this.localCache),this.remoteRepo=new Fo(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw T.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw T.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await tc({integrations:this.remoteCache.getElementsByType(R.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await nc();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ee.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ee.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Za({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ie.Updated,e=>this.handleLocalEvent(e,ie.Updated)),this.localWatcher.on(ie.Deleted,e=>this.handleLocalEvent(e,ie.Deleted)),await this.localWatcher.start(),T.success("[local] Tracking changes.."),this.remoteWatcher=new Xa,this.remoteWatcher.on(cr.Updated,({elementId:e,elementType:t})=>this.handleRemoteEvent(e,t)),await this.remoteWatcher.start(),T.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 handleRemoteEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(T.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return T.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){T.error(`[sync] Error handling remote event: ${n}`)}}async handleLocalEvent(e,t){try{if(cc(e.filePath))switch(t){case ie.Updated:await lc(e.filePath);break;case ie.Deleted:await uc(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const i=z.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(T.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${Eo.toSentenceCase(t)}: ${n.id}`),t){case ie.Updated:await this.updateElement(n,ee.OUTGOING);break;case ie.Deleted:await this.deleteElement(n,ee.OUTGOING);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=kt.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=kt.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;T.info("[resolver] Resolving changes.."),T.info("[resolver] Resolving integration elements");const e=this.changes.filter(i=>i.element.type===R.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ee.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==R.Integration)),T.info("[resolver] Resolving universal elements");const t=this.changes.filter(i=>!i.element.hasParent());for(const i of hr){const r=t.filter(o=>o.element.type===i);T.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}T.info("[resolver] Resolving integration level elements");const n=this.changes.filter(i=>i.element.hasParent());for(const i of hr){const r=n.filter(o=>o.element.type===i);T.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}T.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case de.DELETE:return this.deleteElement(e.element,e.direction);case de.CREATE:return this.updateElement(e.element,e.direction);case de.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),h=kt.detectChangeForElement(u,f,e);h&&a.push(h)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);T.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:de.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:de.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:de.UPDATE,element:e,direction:n,isConflict:!0}:null}}const ke=_.join(Xr.tmpdir(),"membrane-mcp-status"),dr=3e4;class fc{static{l(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=fn(void 0,e),n=pr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function fn(s,e){try{const t=e||process.cwd();if(!s){const i=pr(t);return i.length===0?null:i[0]}const n=ls(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>dr)return St(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>dr)return St(s,t),null}return c}}catch{s&&e&&St(s,e)}return null}l(fn,"getMcpStatus");function pr(s){try{const e=s||process.cwd(),t=cs(e);if(!x.existsSync(ke))return[];const n=x.readdirSync(ke),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=fn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(pr,"getAllMcpStatusFiles");function as(s){try{const t={...fn(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(ke)||x.mkdirSync(ke,{recursive:!0});const n=ls(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(as,"updateMcpStatus");function St(s,e){try{const t=e||process.cwd();if(s){const n=ls(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=cs(t);if(x.existsSync(ke)){const i=x.readdirSync(ke);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(_.join(ke,r))}}}catch{}}l(St,"clearMcpStatus");function hc(s,e){const t=fn(s,e);t&&as({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(hc,"trackToolExecution");function cs(s){return Gr("md5").update(s).digest("hex").slice(0,8)}l(cs,"getCwdHash");function ls(s,e){const t=cs(e);return _.join(ke,`mcp-${t}-${s}.json`)}l(ls,"getStatusFilePath");const Ct={Agent:"agent",Cli:"cli"},P={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 mr{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=pe,this.mcpStatusService=new fc,this.syncService=new kt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(P.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){T.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(P.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){T.error(`Failed to push workspace: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async syncWorkspaces(e={}){try{await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}catch(t){T.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),e?.onComplete?.()}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),at.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){T.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=at.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const i=at.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Ct.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Ct.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Ct.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 gr=vs(null);function dc({children:s,membraneCLIService:e}){const{data:t}=Ts("/account"),[n,i]=B(P.NOT_INITIALIZED),[r,o]=B([]),[a,c]=B({}),[u,f]=B([]),[h,p]=B(null),w=t?.workspaces?.find(d=>d.workspaceKey===h?.workspaceKey)||null;return Ee(()=>{const d=l(({state:O})=>i(O),"handleStateChanged"),y=l(({stats:O})=>c(O),"handleStatsChanged"),C=l(({log:O})=>f(N=>[...N,O]),"handleLogAdded"),v=l(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=l(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(V.StateChanged,d),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,C),e.notifier.on(V.ConflictsChanged,v),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,d),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,C),e.notifier.off(V.ConflictsChanged,v),e.notifier.off(V.ConfigChanged,A)}},[]),m(gr.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:h,updateConfig:l(d=>e.updateConfig(d),"updateConfig"),resolveConflicts:l(d=>e.syncWorkspaces(d),"resolveConflicts"),pull:l(d=>e.pullWorkspace(d),"pull"),push:l(d=>e.pushWorkspace(d),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(dc,"MembraneCLIServiceProvider");function le(){const s=ks(gr);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const yr=vs(process.cwd());function pc({cwd:s,children:e}){return m(yr.Provider,{value:s,children:e})}l(pc,"CwdProvider");function mc(){return ks(yr)}l(mc,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(pc,{cwd:n,children:m(_r,{value:{fetcher:_o()},children:m(dc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const us=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=_.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const s=_.join(process.cwd(),".cursor"),e=_.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function gc({onExit:s,onComplete:e}){const[t,n]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[f,h]=B("");De((w,d)=>{if(c||f){(d.escape||w==="q"||d.return)&&e();return}if(i)d.return||w===" "?p(o):d.escape&&(r(!1),a(null));else if(d.escape)s();else if(d.upArrow||w==="k")n(Math.max(0,t-1));else if(d.downArrow||w==="j")n(Math.min(us.length-1,t+1));else if(d.return||w===" "){const y=us[t];a(y),r(!0)}});const p=l(w=>{try{const d=w.addConfig();u(d)}catch(d){h(`Failed to write configuration: ${d.message||d}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:c}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:f})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:us.map((w,d)=>E(b,{children:[E(S,{color:t===d?"cyan":"white",children:[t===d?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(gc,"AddMcpServerScreen");function yc(){const[s,e]=B(null),[t,n]=B([]),[i,r]=B(null);return Ee(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(yc,"useMcpStatus");function wc(){const{error:s,serverCount:e,allMcpServers:t}=yc(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(xr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}l(wc,"Agent");const dn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function wr(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(wr,"truncateText");function fs({children:s}){const{state:e,logs:t}=le();if(!e||e===P.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(to,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===P.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===P.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:dn(i.type),children:i.message},i.timestamp+r))})}return s}l(fs,"EnsureInitialized");function br({onExit:s,showEscOption:e=!0}){const[t,n]=B(""),{data:i,error:r,isLoading:o}=Ts("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(De((d,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(It,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(d=>d.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(d=>({label:d.name,value:d.id})),p=h.length,g=c?.length??0;async function w(d){const y=f.find(A=>A.id===d);if(!y)return;const{key:C,secret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return l(w,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(no,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",p," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(so,{options:h,onChange:l(d=>{d&&w(d)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}l(br,"SelectWorkspace");function bc({currentPat:s,onSubmit:e}){const[t,n]=B(""),[i,r]=B(!1),[o,a]=B(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(io,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:E(S,{children:[m(It,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}l(bc,"PersonalAccessTokenInput");var vt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(vt||{});const Sc={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hs=[vt.Authenticate,vt.ConnectWorkspace];function Sr({onComplete:s}){const{config:e}=le(),[t,n]=B(!1),[i,r]=B(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ei(),c=hs[i],u=i+1,f=hs.length,h=hs.map((w,d)=>{let y="pending";return d<i?y="done":d===i&&(y="current"),{id:w,label:Sc[w],status:y}});async function p(w){const d=a&&w===""?a:w,y=new ti;try{await y.request("/account",{headers:{Authorization:`Bearer ${d}`}}),Do(d),r(C=>C+1)}catch(C){console.error(C)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),De((w,d)=>{o&&d.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:h.map(w=>m(Cc,{status:w.status,label:w.label},w.id))})]}),c===vt.Authenticate&&m(bc,{currentPat:a,onSubmit:p}),c===vt.ConnectWorkspace&&m(br,{onExit:g,showEscOption:!1})]})}l(Sr,"Setup");function Cc({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(It,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}l(Cc,"StepDisplay");function ds(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}l(ds,"ElementStats");const ps=5,vc=6;function kc(){const{logs:s}=le(),[e,t]=B(0),n=Math.min(100,process.stdout.columns||100),i=ps,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-vc,u=e<s.length-i,f=e>0;return De((h,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(h==="G"||h==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>ps&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((h,p)=>m(b,{marginLeft:1,children:m(S,{color:dn(h.type),children:wr(h.message,c)})},h.timestamp+p)),s.length>ps&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),f&&m(S,{color:"grey",children:"\u2193 "})]})]})}l(kc,"Logs");const pn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Tc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=B(0),[r,o]=B(!1),[a,c]=B(!1);return De((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(h=>h>0?h-1:pn.length-1):f.downArrow?i(h=>h<pn.length-1?h+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),pn[n].value==="sync"?e({watch:!0}):t())}}),Ee(()=>{s!==P.CONFLICTS&&r&&o(!1)},[s,r]),E(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(ms,{isExpanded:a})}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?E(b,{flexDirection:"row",gap:1,children:[m(It,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:pn.map((u,f)=>m(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(S,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(Tc,"ResolveChangesUI");const Ec={[de.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[de.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[de.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ms({isExpanded:s}){const{conflicts:e}=le(),t=5,n=Rr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(b,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=Ec[o][a];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[c.label," (",r.length,")"]}),m(S,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(b,{marginLeft:2,children:E(S,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(b,{marginLeft:2,children:m(S,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ms,"Conflicts");function Ic(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?wr(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ee(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Ac(e),children:[" [",Oc(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(Tc,{}):E(yn,{children:[m(b,{paddingTop:1,children:m(ds,{})}),t.length>0&&m(kc,{})]})]})}l(Ic,"Workspace");function Oc(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}l(Oc,"getStatusDisplay");function Ac(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}l(Ac,"getStatusColor");const Nc="https://console.integration.app/w";function $c(){const s=mc(),e=Mr(!0),{exit:t,state:n}=le(),[i,r]=B(null),o=i??(n===P.SETTING_UP?"setup":"main");De(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===P.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ni(s),u=`${Nc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";eo(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ee(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(br,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(gc,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(Sr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(fs,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(wc,{})}),m(Ic,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}l($c,"Main");const Cr=Dr(process.argv.slice(2)),vr=Cr.cwd?$r(Cr.cwd):process.cwd(),Pc=new mr(Ct.Agent,vr),Lc=l(()=>m(hn,{cwd:vr,membraneCLIService:Pc,children:m($c,{})}),"App");function xc(){Tt(m(Lc,{}))}l(xc,"runAgent");function Dc(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
141
+ `)).action(t=>{t.key&&t.secret?at.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)):Tt(_e.createElement(hn,{membraneCLIService:e,children:_e.createElement(Sr,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Dc,"setupInitCommand");async function kr(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Cn.sign(n,e)}l(kr,"generateAdminAccessToken");async function _c(s,e){return(await vn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(_c,"fetchOpenApiSchema");function Tr(s,e=!0){if(!s)return e?Z.string():Z.string().optional();let t;switch(s.type){case"integer":t=Z.coerce.number().int();break;case"number":t=Z.coerce.number();break;case"boolean":t=Z.coerce.boolean();break;case"string":default:t=Z.string();break}return s.format==="uuid"?t=Z.string().uuid():s.format==="email"?t=Z.string().email():s.format==="date"?t=Z.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=Z.string().datetime()),s.enum&&(t=Z.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}l(Tr,"convertOpenApiSchemaToZod");function Er(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(Er,"extractPathParameters");function Rc(s,e,t,n,i,r,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,c=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},f={},h={};if(s.parameters){for(const g of s.parameters)if(g.in==="path")f[g.name]=Tr(g.schema,!0).describe(g.description||`Path parameter: ${g.name}`);else if(g.in==="query"){const w=g.required===!0;h[g.name]=Tr(g.schema,w).describe(g.description||`Query parameter: ${g.name}`)}}Object.keys(f).length>0&&(u.params=Z.object(f).describe("Path parameters")),Object.keys(h).length>0&&(u.query=Z.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=Z.any().describe("Request body"));const p=Object.keys(u).length>0?Z.object(u):Z.object({});return{name:a,description:c,parameters:p,async execute(g){try{const w=Er(e);if(w.length>0){if(!g.params)throw new Error(`Missing required path parameters: ${w.join(", ")}`);const N=w.filter($=>!($ in g.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let d=`${n}${e}`;if(g.params)for(const[N,$]of Object.entries(g.params)){const j=`{${N}}`;d.includes(j)&&(d=d.replace(j,String($)))}const y=Er(d);if(y.length>0)throw new Error(`Unresolved path parameters: ${y.join(", ")}`);const C=new URLSearchParams;if(g.query)for(const[N,$]of Object.entries(g.query))$!=null&&C.append(N,String($));C.toString()&&(d+=`?${C.toString()}`);const v=await kr(i,r,o),A={method:t.toUpperCase(),headers:{Authorization:`Bearer ${v}`,"Content-Type":"application/json"}};g.body&&t.toLowerCase()!=="get"&&(A.data=g.body);const O=await vn.request({url:d,...A});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(w){return vn.isAxiosError(w)?{content:[{type:"text",text:`Error: ${w.response?.data?`HTTP ${w.response.status}: ${w.response.statusText} - ${JSON.stringify(w.response.data)}`:`HTTP ${w.response?.status||"unknown"}: ${w.message}`}`}],isError:!0}:w instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${w.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(Rc,"createApiTool");function Mc(s,e,t,n,i){const r=[];if(!s.paths)return r;for(const[o,a]of Object.entries(s.paths))if(typeof a=="object"&&a!==null){for(const[c,u]of Object.entries(a))if(["get","post","put","delete","patch"].includes(c)&&u&&typeof u=="object"){const f=Rc(u,o,c,e,t,n,i);r.push(f)}}return r}l(Mc,"convertOpenApiToTools");function jc(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
142
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Rt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||On,n=await kr(e.workspaceKey,e.workspaceSecret,e.testCustomerId),i=await _c(t,n),r=Mc(i,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new ao({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
143
143
  Use it for anything related to Membrane or integrations.
144
144
  `,version:"1.0.0"});for(const u of r){const f=u.execute;u.execute=async h=>(hc(process.pid,process.cwd()),f(h)),o.addTool(u)}as({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{as({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),St(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await c(),process.exit(0)}),process.on("SIGTERM",async()=>{await c(),process.exit(0)}),process.on("exit",()=>{St(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await c(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await c(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}l(jc,"setupMcpCommand");const Kc={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Fc={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class G{static{l(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=Kc[t],c=Fc[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
145
145
  ${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
@@ -331,7 +331,7 @@ ${JSON.stringify(i,null,2)}`).join(`
331
331
 
332
332
  `)}.
333
333
 
334
- 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 Os(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),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 i of t){const r=As(i);n[r]=await this.fetchExampleRecords(i)}return n}}const bs={spec:{testerClass:il},create:{testerClass:Qc,operationKey:"create"},"find-by-id":{testerClass:el,operationKey:"findById"},list:{testerClass:tl,operationKey:"list"},match:{testerClass:nl,operationKey:"match"},search:{testerClass:sl,operationKey:"search"},update:{testerClass:rl,operationKey:"update"},delete:{testerClass:Xc,operationKey:"delete"}};class ol extends Zc{static{l(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);G.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=bs[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(bs).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(bs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){G.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class al extends zc{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){G.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(G.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(G.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),G.error("Supported test types: connectors"),process.exit(1));const c=o,u=r,f=[...a,...t?t.split("/"):[]].join("/"),h=await Ss.create({connectionId:c,testBasePath:u,options:{fix:n}}),g=await h.client.get(`connections/${c}/data`),w=[],d=f?f.split("/"):[];if(d.length===0||d[0]==="data"){d[0]==="data"&&d.shift();let C,v;d.length>=1&&(v=d[0],d.length>=2&&d[1].trim()!==""&&(C=d[1]));for(const A of g){if(v&&v!==A.key)continue;const I=new ol({environment:h,dataCollectionKey:A.key,testMethod:C});w.push(I)}}w.length===0&&(G.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const C of w){await C.run();const v=C.getResult();G.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),kn(y,v)}console.debug("[TestRunner] All results collected:",Object.keys(y)),h.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const mn=l(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
334
+ 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 Os(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:r,parameters:o}))}return i}),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 i of t){const r=As(i);n[r]=await this.fetchExampleRecords(i)}return n}}const bs={spec:{testerClass:il},create:{testerClass:Qc,operationKey:"create"},"find-by-id":{testerClass:el,operationKey:"findById"},list:{testerClass:tl,operationKey:"list"},match:{testerClass:nl,operationKey:"match"},search:{testerClass:sl,operationKey:"search"},update:{testerClass:rl,operationKey:"update"},delete:{testerClass:Xc,operationKey:"delete"}};class ol extends Zc{static{l(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);G.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=bs[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(bs).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(bs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){G.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class al extends zc{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){G.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(G.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(G.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),G.error("Supported test types: connectors"),process.exit(1));const c=o,u=r,f=[...a,...t?t.split("/"):[]].join("/"),h=await Ss.create({connectionId:c,testBasePath:u,options:{fix:n}}),g=await h.client.get(`connections/${c}/data`),w=[],d=f?f.split("/"):[];if(d.length===0||d[0]==="data"){d[0]==="data"&&d.shift();let C,v;d.length>=1&&(v=d[0],d.length>=2&&d[1].trim()!==""&&(C=d[1]));for(const A of g){if(v&&v!==A.key)continue;const O=new ol({environment:h,dataCollectionKey:A.key,testMethod:C});w.push(O)}}w.length===0&&(G.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const C of w){await C.run();const v=C.getResult();G.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),kn(y,v)}console.debug("[TestRunner] All results collected:",Object.keys(y)),h.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const mn=l(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
335
335
  `),"createExperimentalWarning");function cl(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",mn()).action(async()=>{console.warn(mn()),G.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",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",mn()].join(`
336
336
  `)).action(async(t,n)=>{try{console.warn(mn()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new al({testPath:t,path:n.path,fix:n.fix});await i.initialize(),await i.run(),G.success("Tests completed")}catch(i){i instanceof Error&&(G.error(i.message),process.exit(1)),G.error("An unknown error occurred"),process.exit(1)}})}l(cl,"setupTestCommand");const ll=l(()=>{try{const s=ro(import.meta.url),e=Pr(s),t=Lr(e,"..","package.json");return JSON.parse(Ur(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Or=ll();function ul(){const s=new oo().name("membrane").description("Command-line interface for Membrane Agent").version(Or,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:l(t=>k.cyan(t.name()),"subcommandTerm"),commandUsage:l(t=>t.name()==="membrane"?`${k.cyan(t.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:l(t=>{const n=t.flags;return`${k.gray("\u25B8")} ${k.cyan(n)}`},"optionTerm"),subcommandDescription:l(t=>k.gray(t.description()),"subcommandDescription"),optionDescription:l(t=>k.gray(t.description),"optionDescription"),commandDescription:l(t=>k.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
337
  ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Or}`)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@membranehq/cli",
3
- "version": "0.10.18",
3
+ "version": "0.11.0",
4
4
  "keywords": [
5
5
  "cli",
6
6
  "integration",
@@ -33,10 +33,10 @@
33
33
  "@buildwithlayer/openapi-to-tools": "^1.3.3",
34
34
  "@faker-js/faker": "^9.8.0",
35
35
  "@inkjs/ui": "^2.0.0",
36
- "@membranehq/sdk": "^0.8.0",
36
+ "@membranehq/sdk": "^0.8.1",
37
37
  "@types/jsonwebtoken": "^9.0.10",
38
38
  "archiver": "^7.0.1",
39
- "axios": "^1.10.0",
39
+ "axios": "^1.12.0",
40
40
  "chalk": "^4.1.2",
41
41
  "chokidar": "^3.5.3",
42
42
  "commander": "^12.0.0",