@membranehq/cli 0.11.2 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +75 -74
  2. package/package.json +3 -2
package/dist/index.js CHANGED
@@ -1,75 +1,76 @@
1
1
  #!/usr/bin/env node
2
- var $r=Object.defineProperty;var l=(s,e)=>$r(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as wn}from"react/jsx-runtime";import*as j from"node:path";import{resolve as Lr,dirname as Pr,join as Dr}from"node:path";import{useInput as Me,Box as S,Text as b,Newline as xr,render as It}from"ink";import _r from"minimist";import{SWRConfig as Rr}from"swr";import je,{createContext as Ts,useState as q,useEffect as Ae,useContext as Es,useMemo as Mr,useRef as jr}from"react";import Is from"swr/immutable";import{MembraneConfigLoader as Kr,WorkspaceElementType as R,WorkspaceElementSpecs as be,MembraneClient as Os,WorkspaceSyncEventType as Fr,ConnectorFileUpdateType as bn,setValueAtLocator as Sn,extractMembraneErrorData as ue,getDataCollectionCreateFields as Cn,excludeWriteOnlyFieldsFromSchema as As,valueToSchema as Ot,getRequiredFieldsFromSchema as Br,getValueAtLocator as qr,walkSchema as Ns,makeDataLocationPath as $s,getDataCollectionUpdateFields as vn}from"@membranehq/sdk";import Ur from"lodash/isEqual.js";import*as x from"node:fs";import{readFileSync as Jr}from"node:fs";import Ne from"js-yaml";import Ls from"os";import{EventEmitter as Wr}from"events";import M from"path";import Vr from"conf";import kn from"jsonwebtoken";import*as Gr from"node:crypto";import{createHash as zr}from"node:crypto";import Hr from"chokidar";import{EventSource as Yr}from"eventsource";import D from"fs";import Zr from"archiver";import Qr from"form-data";import Xr from"unzipper";import*as eo from"node:os";import{exec as to}from"node:child_process";import{Spinner as no,TextInput as so,Select as io}from"@inkjs/ui";import At from"ink-spinner";import ro from"ink-text-input";import{fileURLToPath as oo}from"node:url";import T from"chalk";import{Command as ao}from"commander";import Tn from"axios";import{FastMCP as co}from"fastmcp";import{z as Z}from"zod";import En from"lodash/merge.js";import lo from"@anthropic-ai/sdk";import{faker as lt}from"@faker-js/faker";import uo from"lodash/template.js";import fo from"lodash/templateSettings.js";class rt{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Kr}static getInstance(){return rt.instance||(rt.instance=new rt),rt.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 ut=rt.getInstance();var _={},Nt={},Ps;function Ds(){if(Ps)return Nt;Ps=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,"toCamelCase"),Nt.default=s,Nt}l(Ds,"requireJsCamelcase");var $t={},xs;function _s(){if(xs)return $t;xs=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,"toSnakeCase"),$t.default=s,$t}l(_s,"requireJsSnakecase");var Lt={},Rs;function Ms(){if(Rs)return Lt;Rs=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-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"),Lt.default=s,Lt}l(Ms,"requireJsPascalcase");var Pt={},js;function ho(){if(js)return Pt;js=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,"toDotCase"),Pt.default=s,Pt}l(ho,"requireJsDotcase");var Dt={},Ks;function po(){if(Ks)return Dt;Ks=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():""}return l(s,"toPathCase"),Dt.default=s,Dt}l(po,"requireJsPathcase");var xt={},Fs;function mo(){if(Fs)return xt;Fs=1,Object.defineProperty(xt,"__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"),xt.default=s,xt}l(mo,"requireJsTextcase");var _t={},Bs;function go(){if(Bs)return _t;Bs=1,Object.defineProperty(_t,"__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"),_t.default=s,_t}l(go,"requireJsSentencecase");var Rt={},qs;function yo(){if(qs)return Rt;qs=1,Object.defineProperty(Rt,"__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"),Rt.default=s,Rt}l(yo,"requireJsHeadercase");var Mt={},Us;function Js(){if(Us)return Mt;Us=1,Object.defineProperty(Mt,"__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"),Mt.default=s,Mt}l(Js,"requireJsKebabcase");var Ke={},In={},Ws;function Fe(){return Ws||(Ws=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})}}(In)),In}l(Fe,"requireUtils");var Vs;function wo(){if(Vs)return Ke;Vs=1;var s=Ke&&Ke.__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(Ke,"__esModule",{value:!0});var e=Fe();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 d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"lowerKeys"),Ke.default=t,Ke}l(wo,"requireLowercaseKeysObject");var Be={},Gs;function bo(){if(Gs)return Be;Gs=1;var s=Be&&Be.__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(Be,"__esModule",{value:!0});var e=Fe();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 d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"upperKeys"),Be.default=t,Be}l(bo,"requireUppercaseKeysObject");var qe={},zs;function So(){if(zs)return qe;zs=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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Fe(),t=Ds();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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"camelKeys"),qe.default=n,qe}l(So,"requireCamelcaseKeysObject");var Ue={},Hs;function Co(){if(Hs)return Ue;Hs=1;var s=Ue&&Ue.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Ue,"__esModule",{value:!0});var e=Fe(),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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"snakeKeys"),Ue.default=n,Ue}l(Co,"requireSnakecaseKeysObject");var Je={},Ys;function vo(){if(Ys)return Je;Ys=1;var s=Je&&Je.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Je,"__esModule",{value:!0});var e=Fe(),t=Ms();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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"pascalKeys"),Je.default=n,Je}l(vo,"requirePascalcaseKeysObject");var We={},Zs;function ko(){if(Zs)return We;Zs=1;var s=We&&We.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(We,"__esModule",{value:!0});var e=Fe(),t=Js();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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"kebabKeys"),We.default=n,We}l(ko,"requireKebabcaseKeysObject");var Qs;function To(){if(Qs)return _;Qs=1,Object.defineProperty(_,"__esModule",{value:!0}),_.kebabKeys=_.pascalKeys=_.snakeKeys=_.camelKeys=_.upperKeys=_.lowerKeys=_.toLowerCase=_.toUpperCase=_.toKebabCase=_.toHeaderCase=_.toSentenceCase=_.toTextCase=_.toPathCase=_.toDotCase=_.toPascalCase=_.toSnakeCase=_.toCamelCase=void 0;var s=Ds();_.toCamelCase=s.default;var e=_s();_.toSnakeCase=e.default;var t=Ms();_.toPascalCase=t.default;var n=ho();_.toDotCase=n.default;var i=po();_.toPathCase=i.default;var r=mo();_.toTextCase=r.default;var o=go();_.toSentenceCase=o.default;var a=yo();_.toHeaderCase=a.default;var c=Js();_.toKebabCase=c.default;var u=wo();_.lowerKeys=u.default;var f=bo();_.upperKeys=f.default;var d=So();_.camelKeys=d.default;var p=Co();_.snakeKeys=p.default;var g=vo();_.pascalKeys=g.default;var w=ko();_.kebabKeys=w.default;var h=l(function(k){return String(k||"").toLowerCase()},"toLowerCase");_.toLowerCase=h;var y=l(function(k){return String(k||"").toUpperCase()},"toUpperCase");_.toUpperCase=y;var v={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:h,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:p.default,pascalKeys:g.default,kebabKeys:w.default};return _.default=v,_}l(To,"requireLib");var On,Xs;function Eo(){return Xs||(Xs=1,On=To()),On}l(Eo,"requireJsConvertCase");var Io=Eo();const he={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 Oo(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(Oo,"baseExportCleanup");const Ao="membrane",No=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function ft(s){return j.join(s,Ao)}l(ft,"getMembraneDir");const $o=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],ei=[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=be[this.type].apiPath;if(this.integrationKey){const t=be[R.Integration].apiPath;return j.join(t,this.integrationKey,e,this.key)}return j.join(e,this.key)}get path(){return j.join(this.dirPath,"spec.yaml")}get relativePath(){return j.relative(ft(process.cwd()),this.path)}get absolutePath(){return j.resolve(j.join(ft(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Ur(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return $o.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(be).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,d=this.getElementTypeFromPath(u);if(d)return{type:d,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=>be[t].apiPath===e)}static getRelativePath(e){return j.relative(ft(process.cwd()),e)}static isIntegrationSpecific(e){return ei.includes(e)}static canBeIntegrationSpecific(e){return ei.includes(e)}}const V={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class An extends Wr{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 Lo="membrane",Po="membrane.config.yml",Nn="https://api.integration.app";function $n(){const s=process.cwd(),e=j.join(s,Lo),t=j.join(s,Po),n=e,i=j.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}l($n,"getPaths");function Do(){return $n().membraneDirPath}l(Do,"getBasePath");const xo={pat:{type:"string"},workspace:{type:"object"}},ti=new Vr({schema:xo,configName:"config",cwd:M.join(Ls.homedir(),".membrane")}),_o=l(s=>{ti.set("pat",s)},"setPat"),ni=l(()=>ti.get("pat"),"getPat");class si{static{l(this,"AccountApiClient")}constructor(e=Nn){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=ni();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 Ro=l(s=>{const e=new si(Nn);return t=>e.get(t)},"createAccountApiFetcher");function jt(s){return ut.loadConfig(s)}l(jt,"readProjectConfig");class Mo{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 kn.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=jt(e);return!t?.workspaceKey||!t?.workspaceSecret?null:{workspaceKey:t.workspaceKey,workspaceSecret:t.workspaceSecret,apiUri:t.apiUri}}async createClient(e){const t=await this.generateAccessToken(e.workspaceKey,e.workspaceSecret);return this.tokenExpiry=Date.now()+36e5,this.currentConfig=e,new Os({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,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 K=new Mo;async function ii(s){const{id:e}=await K.withClient(t=>t.get("org-workspace-id"),s);return e}l(ii,"getWorkspaceId");class jo extends An{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 K.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 K.withClient(t=>t.post("/local-clients",{hostname:Ls.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 K.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await K.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 jo({heartbeatIntervalMs:15e3});class Ko{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 C=new Ko;class ri{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 C.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 Fo extends ri{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ft(process.cwd())}async getElementsByType(e,t){const n=[],i=j.join(this.basePath,be[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=j.join(this.basePath,be[R.Integration].apiPath,o.key,be[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&C.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=j.join(this.basePath,t.dirPath),i=j.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ne.dump(e.data)),C.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=j.join(this.basePath,e.path),n=j.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),C.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=j.join(this.basePath,be[R.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ne.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=j.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(j.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Bo extends ri{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&&C.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await K.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 K.withClient(o=>o[ne[e.type].elements].create(n),process.cwd()),r=z.fromData(e.type,i);return C.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 K.withClient(a=>a[ne[e.type].element](t.data.id).put(i),process.cwd()),o=z.fromData(t.type,r);return C.info(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await K.withClient(t=>t[ne[e.type].element](e.data.id).archive(),process.cwd()),C.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await K.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>z.fromData(R.Integration,n));return t.length>0&&C.success(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await K.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 K.withClient(i=>i[ne[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>z.fromData(e,i))}}const Ln=Symbol.for("yaml.alias"),Pn=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),oi=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Ve=Symbol.for("yaml.seq"),re=Symbol.for("yaml.node.type"),Ce=l(s=>!!s&&typeof s=="object"&&s[re]===Ln,"isAlias"),$e=l(s=>!!s&&typeof s=="object"&&s[re]===Pn,"isDocument"),Ge=l(s=>!!s&&typeof s=="object"&&s[re]===Se,"isMap"),U=l(s=>!!s&&typeof s=="object"&&s[re]===oi,"isPair"),B=l(s=>!!s&&typeof s=="object"&&s[re]===fe,"isScalar$1"),ze=l(s=>!!s&&typeof s=="object"&&s[re]===Ve,"isSeq");function J(s){if(s&&typeof s=="object")switch(s[re]){case Se:case Ve:return!0}return!1}l(J,"isCollection$1");function W(s){if(s&&typeof s=="object")switch(s[re]){case Ln:case Se:case fe:case Ve:return!0}return!1}l(W,"isNode");const ai=l(s=>(B(s)||J(s))&&!!s.anchor,"hasAnchor"),te=Symbol("break visit"),ci=Symbol("skip children"),de=Symbol("remove node");function Le(s,e){const t=li(e);$e(s)?He(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):He(null,s,t,Object.freeze([]))}l(Le,"visit$1"),Le.BREAK=te,Le.SKIP=ci,Le.REMOVE=de;function He(s,e,t,n){const i=ui(s,e,t,n);if(W(i)||U(i))return fi(s,n,i),He(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=He(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===de&&(e.items.splice(r,1),r-=1)}}}else if(U(e)){n=Object.freeze(n.concat(e));const r=He("key",e.key,t,n);if(r===te)return te;r===de&&(e.key=null);const o=He("value",e.value,t,n);if(o===te)return te;o===de&&(e.value=null)}}return i}l(He,"visit_");async function Kt(s,e){const t=li(e);$e(s)?await Ye(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await Ye(null,s,t,Object.freeze([]))}l(Kt,"visitAsync"),Kt.BREAK=te,Kt.SKIP=ci,Kt.REMOVE=de;async function Ye(s,e,t,n){const i=await ui(s,e,t,n);if(W(i)||U(i))return fi(s,n,i),Ye(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 Ye(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===de&&(e.items.splice(r,1),r-=1)}}}else if(U(e)){n=Object.freeze(n.concat(e));const r=await Ye("key",e.key,t,n);if(r===te)return te;r===de&&(e.key=null);const o=await Ye("value",e.value,t,n);if(o===te)return te;o===de&&(e.value=null)}}return i}l(Ye,"visitAsync_");function li(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(li,"initVisitor");function ui(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Ge(e))return t.Map?.(s,e,n);if(ze(e))return t.Seq?.(s,e,n);if(U(e))return t.Pair?.(s,e,n);if(B(e))return t.Scalar?.(s,e,n);if(Ce(e))return t.Alias?.(s,e,n)}l(ui,"callVisitor");function fi(s,e,t){const n=e[e.length-1];if(J(n))n.items[s]=t;else if(U(n))s==="key"?n.key=t:n.value=t;else if($e(n))n.contents=t;else{const i=Ce(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(fi,"replaceNode");const qo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Uo=l(s=>s.replace(/[!,[\]{}]/g,e=>qo[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+Uo(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={};Le(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 di(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(di,"anchorIsValid");function hi(s){const e=new Set;return Le(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(hi,"anchorNames");function pi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(pi,"findNewAnchor");function Jo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=hi(s));const o=pi(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&&(B(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(Jo,"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||!ai(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 Dn{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(!$e(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 Ft extends Dn{static{l(this,"Alias")}constructor(e){super(Ln),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=[],Le(e,{Node:l((r,o)=>{(Ce(o)||ai(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=Bt(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(di(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 Bt(s,e,t){if(Ce(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=Bt(s,i,t);r>n&&(n=r)}return n}else if(U(e)){const n=Bt(s,e.key,t),i=Bt(s,e.value,t);return Math.max(n,i)}return 1}l(Bt,"getAliasCount");const mi=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class P extends Dn{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)}}P.BLOCK_FOLDED="BLOCK_FOLDED",P.BLOCK_LITERAL="BLOCK_LITERAL",P.PLAIN="PLAIN",P.QUOTE_DOUBLE="QUOTE_DOUBLE",P.QUOTE_SINGLE="QUOTE_SINGLE";const Wo="tag:yaml.org,2002:";function Vo(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(Vo,"findTagObject");function dt(s,e,t){if($e(s)&&(s=s.contents),W(s))return s;if(U(s)){const d=t.schema[Se].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=i(s)),new Ft(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Wo+e.slice(2));let u=Vo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new P(s);return c&&(c.node=d),d}u=s instanceof Map?o[Se]:Symbol.iterator in Object(s)?o[Ve]:o[Se]}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 P(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(dt,"createNode");function qt(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 dt(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(qt,"collectionFromPath");const ht=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class gi extends Dn{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)||U(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ht(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,qt(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&&B(r)?r.value:r:J(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!U(t))return!1;const n=t.value;return n==null||e&&B(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,qt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Go=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 Pe=l((s,e,t)=>s.endsWith(`
2
+ var Dr=Object.defineProperty;var l=(s,e)=>Dr(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as wn}from"react/jsx-runtime";import*as j from"node:path";import{join as bn,resolve as Pr,dirname as xr}from"node:path";import{useInput as Me,Box as S,Text as C,Newline as Rr,render as It}from"ink";import _r from"minimist";import{SWRConfig as Mr}from"swr";import je,{createContext as Es,useState as B,useEffect as Ae,useContext as Is,useMemo as jr,useRef as Kr}from"react";import Os from"swr/immutable";import{MembraneConfigLoader as Fr,WorkspaceElementType as _,WorkspaceElementSpecs as be,MembraneAxiosInstance as qr,MembraneClient as As,WorkspaceSyncEventType as Br,ConnectorFileUpdateType as Sn,setValueAtLocator as Cn,extractMembraneErrorData as ue,getDataCollectionCreateFields as vn,excludeWriteOnlyFieldsFromSchema as Ns,valueToSchema as Ot,getRequiredFieldsFromSchema as Ur,getValueAtLocator as Jr,walkSchema as $s,makeDataLocationPath as Ls,getDataCollectionUpdateFields as kn}from"@membranehq/sdk";import Wr from"lodash/isEqual.js";import*as x from"node:fs";import{mkdirSync as Vr,writeFileSync as Gr,readFileSync as zr}from"node:fs";import Ne from"js-yaml";import Ds from"os";import{EventEmitter as Hr}from"events";import M from"path";import Yr from"conf";import Tn from"jsonwebtoken";import*as Zr from"node:crypto";import{createHash as Qr}from"node:crypto";import Xr from"chokidar";import{EventSource as eo}from"eventsource";import P from"fs";import to from"archiver";import no from"form-data";import so from"unzipper";import*as io from"node:os";import{exec as ro}from"node:child_process";import{Spinner as oo,TextInput as ao,Select as co}from"@inkjs/ui";import At from"ink-spinner";import lo from"ink-text-input";import{fileURLToPath as uo}from"node:url";import T from"chalk";import{Command as fo}from"commander";import En from"axios";import{FastMCP as ho}from"fastmcp";import{z as Z}from"zod";import In from"lodash/merge.js";import po from"@anthropic-ai/sdk";import{faker as ut}from"@faker-js/faker";import mo from"lodash/template.js";import go from"lodash/templateSettings.js";class ot{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Fr}static getInstance(){return ot.instance||(ot.instance=new ot),ot.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const ft=ot.getInstance();var R={},Nt={},Ps;function xs(){if(Ps)return Nt;Ps=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,"toCamelCase"),Nt.default=s,Nt}l(xs,"requireJsCamelcase");var $t={},Rs;function _s(){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,"toSnakeCase"),$t.default=s,$t}l(_s,"requireJsSnakecase");var Lt={},Ms;function js(){if(Ms)return Lt;Ms=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-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"),Lt.default=s,Lt}l(js,"requireJsPascalcase");var Dt={},Ks;function yo(){if(Ks)return Dt;Ks=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():""}return l(s,"toDotCase"),Dt.default=s,Dt}l(yo,"requireJsDotcase");var Pt={},Fs;function wo(){if(Fs)return Pt;Fs=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(wo,"requireJsPathcase");var xt={},qs;function bo(){if(qs)return xt;qs=1,Object.defineProperty(xt,"__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"),xt.default=s,xt}l(bo,"requireJsTextcase");var Rt={},Bs;function So(){if(Bs)return Rt;Bs=1,Object.defineProperty(Rt,"__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"),Rt.default=s,Rt}l(So,"requireJsSentencecase");var _t={},Us;function Co(){if(Us)return _t;Us=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().replace(/( ?)(\w+)( ?)/g,function(t,n,i,r){return n+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(s,"toHeaderCase"),_t.default=s,_t}l(Co,"requireJsHeadercase");var Mt={},Js;function Ws(){if(Js)return Mt;Js=1,Object.defineProperty(Mt,"__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"),Mt.default=s,Mt}l(Ws,"requireJsKebabcase");var Ke={},On={},Vs;function Fe(){return Vs||(Vs=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})}}(On)),On}l(Fe,"requireUtils");var Gs;function vo(){if(Gs)return Ke;Gs=1;var s=Ke&&Ke.__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(Ke,"__esModule",{value:!0});var e=Fe();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 d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"lowerKeys"),Ke.default=t,Ke}l(vo,"requireLowercaseKeysObject");var qe={},zs;function ko(){if(zs)return qe;zs=1;var s=qe&&qe.__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(qe,"__esModule",{value:!0});var e=Fe();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 d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"upperKeys"),qe.default=t,qe}l(ko,"requireUppercaseKeysObject");var Be={},Hs;function To(){if(Hs)return Be;Hs=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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Be,"__esModule",{value:!0});var e=Fe(),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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"camelKeys"),Be.default=n,Be}l(To,"requireCamelcaseKeysObject");var Ue={},Ys;function Eo(){if(Ys)return Ue;Ys=1;var s=Ue&&Ue.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Ue,"__esModule",{value:!0});var e=Fe(),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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"snakeKeys"),Ue.default=n,Ue}l(Eo,"requireSnakecaseKeysObject");var Je={},Zs;function Io(){if(Zs)return Je;Zs=1;var s=Je&&Je.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Je,"__esModule",{value:!0});var e=Fe(),t=js();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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"pascalKeys"),Je.default=n,Je}l(Io,"requirePascalcaseKeysObject");var We={},Qs;function Oo(){if(Qs)return We;Qs=1;var s=We&&We.__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,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(We,"__esModule",{value:!0});var e=Fe(),t=Ws();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 d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var p=n({key:f},r);d=p.key}return d}))),o[u]=c}),o}return l(n,"kebabKeys"),We.default=n,We}l(Oo,"requireKebabcaseKeysObject");var Xs;function Ao(){if(Xs)return R;Xs=1,Object.defineProperty(R,"__esModule",{value:!0}),R.kebabKeys=R.pascalKeys=R.snakeKeys=R.camelKeys=R.upperKeys=R.lowerKeys=R.toLowerCase=R.toUpperCase=R.toKebabCase=R.toHeaderCase=R.toSentenceCase=R.toTextCase=R.toPathCase=R.toDotCase=R.toPascalCase=R.toSnakeCase=R.toCamelCase=void 0;var s=xs();R.toCamelCase=s.default;var e=_s();R.toSnakeCase=e.default;var t=js();R.toPascalCase=t.default;var n=yo();R.toDotCase=n.default;var i=wo();R.toPathCase=i.default;var r=bo();R.toTextCase=r.default;var o=So();R.toSentenceCase=o.default;var a=Co();R.toHeaderCase=a.default;var c=Ws();R.toKebabCase=c.default;var u=vo();R.lowerKeys=u.default;var f=ko();R.upperKeys=f.default;var d=To();R.camelKeys=d.default;var p=Eo();R.snakeKeys=p.default;var g=Io();R.pascalKeys=g.default;var w=Oo();R.kebabKeys=w.default;var h=l(function(k){return String(k||"").toLowerCase()},"toLowerCase");R.toLowerCase=h;var y=l(function(k){return String(k||"").toUpperCase()},"toUpperCase");R.toUpperCase=y;var v={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:h,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:p.default,pascalKeys:g.default,kebabKeys:w.default};return R.default=v,R}l(Ao,"requireLib");var An,ei;function No(){return ei||(ei=1,An=Ao()),An}l(No,"requireJsConvertCase");var $o=No();const he={UPDATE:"update",DELETE:"delete",CREATE:"create"},ee={INCOMING:"incoming",OUTGOING:"outgoing"},ne={[_.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")},[_.Connector]:{element:"connector",elements:"connectors",exportable:!1},[_.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(s=>(delete s.integration,s),"exportCleanup")},[_.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[_.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[_.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[_.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[_.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:l(s=>(delete s.dataSourceId,s),"exportCleanup")},[_.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Lo(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(Lo,"baseExportCleanup");const Do="membrane",Po=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Ve(s){return j.join(s,Do)}l(Ve,"getMembraneDir");const xo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],ti=[_.Action,_.FieldMapping,_.Flow,_.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=be[this.type].apiPath;if(this.integrationKey){const t=be[_.Integration].apiPath;return j.join(t,this.integrationKey,e,this.key)}return j.join(e,this.key)}get path(){return j.join(this.dirPath,"spec.yaml")}get relativePath(){return j.relative(Ve(process.cwd()),this.path)}get absolutePath(){return j.resolve(j.join(Ve(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Wr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return xo.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===_.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(be).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,d=this.getElementTypeFromPath(u);if(d)return{type:d,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(_).find(t=>be[t].apiPath===e)}static getRelativePath(e){return j.relative(Ve(process.cwd()),e)}static isIntegrationSpecific(e){return ti.includes(e)}static canBeIntegrationSpecific(e){return ti.includes(e)}}const V={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Nn extends Hr{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 Ro="membrane",_o="membrane.config.yml",$n="https://api.integration.app";function Ln(){const s=process.cwd(),e=j.join(s,Ro),t=j.join(s,_o),n=e,i=j.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}l(Ln,"getPaths");function Mo(){return Ln().membraneDirPath}l(Mo,"getBasePath");const jo={pat:{type:"string"},workspace:{type:"object"}},ni=new Yr({schema:jo,configName:"config",cwd:M.join(Ds.homedir(),".membrane")}),Ko=l(s=>{ni.set("pat",s)},"setPat"),si=l(()=>ni.get("pat"),"getPat");class ii{static{l(this,"AccountApiClient")}constructor(e=$n){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=si();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 Fo=l(s=>{const e=new ii($n);return t=>e.get(t)},"createAccountApiFetcher");function jt(s){return ft.loadConfig(s)}l(jt,"readProjectConfig");class qo{static{l(this,"RequestLogger")}constructor(e=qr){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=l(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{t.metadata={startTime:Date.now()};const{method:n,url:i}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:i}=this.getRequestDetails(t.config),r=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${i} - ${o} ${a} (${r}ms)`),t},e),this.interceptorsConfigured=!0}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const i=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:i}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){const{method:t,url:n}=this.getRequestDetails(e.config),i=this.getDuration(e.config);if(e.response){const{status:r,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${r} ${o} (${i}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class Bo{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();requestLogger=null;constructor(e={}){this.init(e)}init(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,this.requestLogger=new qo,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Tn.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=jt(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 As({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,t="operation"){let n;for(let i=0;i<=this.maxRetries;i++)try{return await e()}catch(r){if(n=r,!this.isRetryableError(r)||i===this.maxRetries)throw r;const o=new Date().toISOString(),a=i+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let c=this.retryDelay*Math.pow(2,i);if(this.enableJitter){const u=c*.25*(Math.random()*2-1);c=Math.max(0,c+u)}await new Promise(u=>setTimeout(u,c))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const 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 K=new Bo;async function ri(s){const{id:e}=await K.withClient(t=>t.get("org-workspace-id"),s);return e}l(ri,"getWorkspaceId");class Uo extends Nn{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 K.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 K.withClient(t=>t.post("/local-clients",{hostname:Ds.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 K.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await K.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 Uo({heartbeatIntervalMs:15e3}),oi=bn(Ve(process.cwd()),".logs");class Jo{static{l(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=pe}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",i=`${t}${n}.txt`;Vr(oi,{recursive:!0});const r=bn(oi,i),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
3
+ `);return Gr(r,o,"utf-8"),r}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new Jo;class ai{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=[_.Integration,_.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 b.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 Wo extends ai{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=Ve(process.cwd())}async getElementsByType(e,t){const n=[],i=j.join(this.basePath,be[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=j.join(this.basePath,be[_.Integration].apiPath,o.key,be[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=j.join(this.basePath,t.dirPath),i=j.join(this.basePath,t.path);return x.existsSync(n)||x.mkdirSync(n,{recursive:!0}),x.writeFileSync(i,Ne.dump(e.data)),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=j.join(this.basePath,e.path),n=j.join(this.basePath,e.dirPath);x.existsSync(t)&&x.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=j.join(this.basePath,be[_.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!x.existsSync(e))return;const t=x.readFileSync(e,"utf8"),n=Ne.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=j.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(j.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Vo extends ai{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&&b.debug(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){const t=await K.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 K.withClient(o=>o[ne[e.type].elements].create(n),process.cwd()),r=z.fromData(e.type,i);return b.debug(`[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 K.withClient(a=>a[ne[e.type].element](t.data.id).put(i),process.cwd()),o=z.fromData(t.type,r);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await K.withClient(t=>t[ne[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await K.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>z.fromData(_.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await K.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===_.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===_.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===_.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===_.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 K.withClient(i=>i[ne[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>z.fromData(e,i))}}const Dn=Symbol.for("yaml.alias"),Pn=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),ci=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Ge=Symbol.for("yaml.seq"),re=Symbol.for("yaml.node.type"),Ce=l(s=>!!s&&typeof s=="object"&&s[re]===Dn,"isAlias"),$e=l(s=>!!s&&typeof s=="object"&&s[re]===Pn,"isDocument"),ze=l(s=>!!s&&typeof s=="object"&&s[re]===Se,"isMap"),U=l(s=>!!s&&typeof s=="object"&&s[re]===ci,"isPair"),q=l(s=>!!s&&typeof s=="object"&&s[re]===fe,"isScalar$1"),He=l(s=>!!s&&typeof s=="object"&&s[re]===Ge,"isSeq");function J(s){if(s&&typeof s=="object")switch(s[re]){case Se:case Ge:return!0}return!1}l(J,"isCollection$1");function W(s){if(s&&typeof s=="object")switch(s[re]){case Dn:case Se:case fe:case Ge:return!0}return!1}l(W,"isNode");const li=l(s=>(q(s)||J(s))&&!!s.anchor,"hasAnchor"),te=Symbol("break visit"),ui=Symbol("skip children"),de=Symbol("remove node");function Le(s,e){const t=fi(e);$e(s)?Ye(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):Ye(null,s,t,Object.freeze([]))}l(Le,"visit$1"),Le.BREAK=te,Le.SKIP=ui,Le.REMOVE=de;function Ye(s,e,t,n){const i=di(s,e,t,n);if(W(i)||U(i))return hi(s,n,i),Ye(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=Ye(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===de&&(e.items.splice(r,1),r-=1)}}}else if(U(e)){n=Object.freeze(n.concat(e));const r=Ye("key",e.key,t,n);if(r===te)return te;r===de&&(e.key=null);const o=Ye("value",e.value,t,n);if(o===te)return te;o===de&&(e.value=null)}}return i}l(Ye,"visit_");async function Kt(s,e){const t=fi(e);$e(s)?await Ze(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await Ze(null,s,t,Object.freeze([]))}l(Kt,"visitAsync"),Kt.BREAK=te,Kt.SKIP=ui,Kt.REMOVE=de;async function Ze(s,e,t,n){const i=await di(s,e,t,n);if(W(i)||U(i))return hi(s,n,i),Ze(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 Ze(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===te)return te;o===de&&(e.items.splice(r,1),r-=1)}}}else if(U(e)){n=Object.freeze(n.concat(e));const r=await Ze("key",e.key,t,n);if(r===te)return te;r===de&&(e.key=null);const o=await Ze("value",e.value,t,n);if(o===te)return te;o===de&&(e.value=null)}}return i}l(Ze,"visitAsync_");function fi(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(fi,"initVisitor");function di(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(ze(e))return t.Map?.(s,e,n);if(He(e))return t.Seq?.(s,e,n);if(U(e))return t.Pair?.(s,e,n);if(q(e))return t.Scalar?.(s,e,n);if(Ce(e))return t.Alias?.(s,e,n)}l(di,"callVisitor");function hi(s,e,t){const n=e[e.length-1];if(J(n))n.items[s]=t;else if(U(n))s==="key"?n.key=t:n.value=t;else if($e(n))n.contents=t;else{const i=Ce(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(hi,"replaceNode");const Go={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},zo=l(s=>s.replace(/[!,[\]{}]/g,e=>Go[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+zo(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={};Le(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(`
4
+ `)}}X.defaultYaml={explicit:!1,version:"1.2"},X.defaultTags={"!!":"tag:yaml.org,2002:"};function pi(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(pi,"anchorIsValid");function mi(s){const e=new Set;return Le(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(mi,"anchorNames");function gi(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(gi,"findNewAnchor");function Ho(s,e){const t=[],n=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=mi(s));const o=gi(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&&(q(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(Ho,"createNodeAnchors");function Qe(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=Qe(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=Qe(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=Qe(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=Qe(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}l(Qe,"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||!li(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 xn{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(!$e(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"?Qe(r,{"":a},"",a):a}}class Ft extends xn{static{l(this,"Alias")}constructor(e){super(Dn),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=[],Le(e,{Node:l((r,o)=>{(Ce(o)||li(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=qt(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(pi(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 qt(s,e,t){if(Ce(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=qt(s,i,t);r>n&&(n=r)}return n}else if(U(e)){const n=qt(s,e.key,t),i=qt(s,e.value,t);return Math.max(n,i)}return 1}l(qt,"getAliasCount");const yi=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class D extends xn{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)}}D.BLOCK_FOLDED="BLOCK_FOLDED",D.BLOCK_LITERAL="BLOCK_LITERAL",D.PLAIN="PLAIN",D.QUOTE_DOUBLE="QUOTE_DOUBLE",D.QUOTE_SINGLE="QUOTE_SINGLE";const Yo="tag:yaml.org,2002:";function Zo(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(Zo,"findTagObject");function dt(s,e,t){if($e(s)&&(s=s.contents),W(s))return s;if(U(s)){const d=t.schema[Se].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=i(s)),new Ft(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Yo+e.slice(2));let u=Zo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new D(s);return c&&(c.node=d),d}u=s instanceof Map?o[Se]:Symbol.iterator in Object(s)?o[Ge]:o[Se]}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 D(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(dt,"createNode");function Bt(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 dt(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(Bt,"collectionFromPath");const ht=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class wi extends xn{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)||U(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ht(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,Bt(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&&q(r)?r.value:r:J(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!U(t))return!1;const n=t.value;return n==null||e&&q(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,Bt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Qo=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 De=l((s,e,t)=>s.endsWith(`
4
5
  `)?me(t,e):t.includes(`
5
6
  `)?`
6
- `+me(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),yi="flow",xn="block",Ut="quoted";function Jt(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 d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let p,g,w=!1,h=-1,y=-1,v=-1;t===xn&&(h=wi(s,h,e.length),h!==-1&&(d=h+c));for(let A;A=s[h+=1];){if(t===Ut&&A==="\\"){switch(y=h,s[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(A===`
7
- `)t===xn&&(h=wi(s,h,e.length)),d=h+e.length+c,p=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
7
+ `+me(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),bi="flow",Rn="block",Ut="quoted";function Jt(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 d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let p,g,w=!1,h=-1,y=-1,v=-1;t===Rn&&(h=Si(s,h,e.length),h!==-1&&(d=h+c));for(let A;A=s[h+=1];){if(t===Ut&&A==="\\"){switch(y=h,s[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}v=h}if(A===`
8
+ `)t===Rn&&(h=Si(s,h,e.length)),d=h+e.length+c,p=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
8
9
  `&&g!==" "){const O=s[h+1];O&&O!==" "&&O!==`
9
10
  `&&O!==" "&&(p=h)}if(h>=d)if(p)u.push(p),d=p+c,p=void 0;else if(t===Ut){for(;g===" "||g===" ";)g=A,A=s[h+=1],w=!0;const O=h>v+1?h-2:y-1;if(f[O])return s;u.push(O),f[O]=!0,d=O+c,p=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let k=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?k=`
10
11
  ${e}${s.slice(0,N)}`:(t===Ut&&f[O]&&(k+=`${s[O]}\\`),k+=`
11
- ${e}${s.slice(O+1,N)}`)}return k}l(Jt,"foldFlowLines");function wi(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
- `);n=e,i=e+1,r=s[i]}return n}l(wi,"consumeMoreIndentedLines");const Wt=l((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Vt=l(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function zo(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
- `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}l(zo,"lineLengthOverLimit");function pt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Vt(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)+`
12
+ ${e}${s.slice(O+1,N)}`)}return k}l(Jt,"foldFlowLines");function Si(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!==`
13
+ `);n=e,i=e+1,r=s[i]}return n}l(Si,"consumeMoreIndentedLines");const Wt=l((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Vt=l(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Xo(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]===`
14
+ `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}l(Xo,"lineLengthOverLimit");function pt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Vt(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
15
 
15
16
  `;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
16
17
  `,c+=2;o+=r,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:Jt(o,r,Ut,Wt(e,!1))}l(pt,"doubleQuotedString");function _n(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
18
  `)||/[ \t]\n|\n[ \t]/.test(s))return pt(s,e);const t=e.indent||(Vt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${t}`)+"'";return e.implicitKey?n:Jt(n,t,yi,Wt(e,!1))}l(_n,"singleQuotedString");function Qe(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=pt;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=_n:r&&!i?n=pt:n=t?_n:pt}return n(s,e)}l(Qe,"quotedString");let Rn;try{Rn=new RegExp(`(^|(?<!
19
+ ${t}`)+"'";return e.implicitKey?n:Jt(n,t,bi,Wt(e,!1))}l(_n,"singleQuotedString");function Xe(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=pt;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=_n:r&&!i?n=pt:n=t?_n:pt}return n(s,e)}l(Xe,"quotedString");let Mn;try{Mn=new RegExp(`(^|(?<!
19
20
  ))
20
21
  +(?!
21
- |$)`,"g")}catch{Rn=/\n+(?!\n|$)/g}function Gt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Qe(t,n);const u=n.indent||(n.forceBlockIndent||Vt(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===P.BLOCK_FOLDED?!1:e===P.BLOCK_LITERAL?!0:!zo(t,c,u.length);if(!t)return f?`|
22
+ |$)`,"g")}catch{Mn=/\n+(?!\n|$)/g}function Gt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Xe(t,n);const u=n.indent||(n.forceBlockIndent||Vt(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Xo(t,c,u.length);if(!t)return f?`|
22
23
  `:`>
23
24
  `;let d,p;for(p=t.length;p>0;--p){const N=t[p-1];if(N!==`
24
25
  `&&N!==" "&&N!==" ")break}let g=t.substring(p);const w=g.indexOf(`
25
26
  `);w===-1?d="-":t===g||w!==g.length-1?(d="+",r&&r()):d="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
26
- `&&(g=g.slice(0,-1)),g=g.replace(Rn,`$&${u}`));let h=!1,y,v=-1;for(y=0;y<t.length;++y){const N=t[y];if(N===" ")h=!0;else if(N===`
27
+ `&&(g=g.slice(0,-1)),g=g.replace(Mn,`$&${u}`));let h=!1,y,v=-1;for(y=0;y<t.length;++y){const N=t[y];if(N===" ")h=!0;else if(N===`
27
28
  `)v=y;else break}let k=t.substring(0,v<y?v+1:y);k&&(t=t.substring(k.length),k=k.replace(/\n+/g,`$&${u}`));let O=(h?u?"2":"1":"")+d;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 F=Wt(n,!0);o!=="folded"&&e!==P.BLOCK_FOLDED&&(F.onOverflow=()=>{$=!0});const I=Jt(`${k}${N}${g}`,u,xn,F);if(!$)return`>${O}
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const F=Wt(n,!0);o!=="folded"&&e!==D.BLOCK_FOLDED&&(F.onOverflow=()=>{$=!0});const I=Jt(`${k}${N}${g}`,u,Rn,F);if(!$)return`>${O}
29
30
  ${u}${I}`}return t=t.replace(/\n+/g,`$&${u}`),`|${O}
30
- ${u}${k}${t}${g}`}l(Gt,"blockString");function Ho(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
- `)||f&&/[[\]{},]/.test(r))return Qe(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||f||!r.includes(`
32
- `)?Qe(r,e):Gt(s,e,t,n);if(!a&&!f&&i!==P.PLAIN&&r.includes(`
33
- `))return Gt(s,e,t,n);if(Vt(r)){if(c==="")return e.forceBlockIndent=!0,Gt(s,e,t,n);if(a&&c===u)return Qe(r,e)}const d=r.replace(/\n+/g,`$&
34
- ${c}`);if(o){const p=l(h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(p)||g?.some(p))return Qe(r,e)}return a?d:Jt(d,c,yi,Wt(e,!1))}l(Ho,"plainString");function mt(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!==P.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=P.QUOTE_DOUBLE);const c=l(f=>{switch(f){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return i||r?Qe(o.value,e):Gt(o,e,t,n);case P.QUOTE_DOUBLE:return pt(o.value,e);case P.QUOTE_SINGLE:return _n(o.value,e);case P.PLAIN:return Ho(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,p=i&&f||d;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}l(mt,"stringifyString");function bi(s,e){const t=Object.assign({blockQuote:!0,commentString:Go,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(bi,"createStringifyContext");function Yo(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(B(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(Yo,"getTagObject");function Zo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(B(s)||J(s))&&s.anchor;r&&di(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(Zo,"stringifyProps");function Xe(s,e,t,n){if(U(s))return s.toString(e,t,n);if(Ce(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=Yo(e.doc.schema.tags,r));const o=Zo(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):B(r)?mt(r,e,t,n):r.toString(e,t,n);return o?B(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
- ${e.indent}${a}`:a}l(Xe,"stringify$2");function Qo({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=t;let p=W(s)&&s.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(J(s)||!W(s)&&typeof s=="object"){const F="With simple keys, collection cannot be used as a key value";throw new Error(F)}}let g=!d&&(!s||p&&e==null&&!t.inFlow||J(s)||(B(s)?s.type===P.BLOCK_FOLDED||s.type===P.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+c});let w=!1,h=!1,y=Xe(s,t,()=>w=!0,()=>h=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!d||e==null&&g)return y=`? ${y}`,p&&!w?y+=Pe(y,t.indent,u(p)):h&&i&&i(),y;w&&(p=null),g?(p&&(y+=Pe(y,t.indent,u(p))),y=`? ${y}
36
- ${a}:`):(y=`${y}:`,p&&(y+=Pe(y,t.indent,u(p))));let v,k,A;W(e)?(v=!!e.spaceBefore,k=e.commentBefore,A=e.comment):(v=!1,k=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!p&&B(e)&&(t.indentAtStart=y.length+1),h=!1,!f&&c.length>=2&&!t.inFlow&&!g&&ze(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1;const N=Xe(e,t,()=>O=!0,()=>h=!0);let $=" ";if(p||v||k){if($=v?`
31
+ ${u}${k}${t}${g}`}l(Gt,"blockString");function ea(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(`
32
+ `)||f&&/[[\]{},]/.test(r))return Xe(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||f||!r.includes(`
33
+ `)?Xe(r,e):Gt(s,e,t,n);if(!a&&!f&&i!==D.PLAIN&&r.includes(`
34
+ `))return Gt(s,e,t,n);if(Vt(r)){if(c==="")return e.forceBlockIndent=!0,Gt(s,e,t,n);if(a&&c===u)return Xe(r,e)}const d=r.replace(/\n+/g,`$&
35
+ ${c}`);if(o){const p=l(h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(p)||g?.some(p))return Xe(r,e)}return a?d:Jt(d,c,bi,Wt(e,!1))}l(ea,"plainString");function mt(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!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=D.QUOTE_DOUBLE);const c=l(f=>{switch(f){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return i||r?Xe(o.value,e):Gt(o,e,t,n);case D.QUOTE_DOUBLE:return pt(o.value,e);case D.QUOTE_SINGLE:return _n(o.value,e);case D.PLAIN:return ea(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,p=i&&f||d;if(u=c(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}l(mt,"stringifyString");function Ci(s,e){const t=Object.assign({blockQuote:!0,commentString:Qo,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(Ci,"createStringifyContext");function ta(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(q(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(ta,"getTagObject");function na(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(q(s)||J(s))&&s.anchor;r&&pi(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(na,"stringifyProps");function et(s,e,t,n){if(U(s))return s.toString(e,t,n);if(Ce(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=ta(e.doc.schema.tags,r));const o=na(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):q(r)?mt(r,e,t,n):r.toString(e,t,n);return o?q(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
+ ${e.indent}${a}`:a}l(et,"stringify$2");function sa({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=t;let p=W(s)&&s.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(J(s)||!W(s)&&typeof s=="object"){const F="With simple keys, collection cannot be used as a key value";throw new Error(F)}}let g=!d&&(!s||p&&e==null&&!t.inFlow||J(s)||(q(s)?s.type===D.BLOCK_FOLDED||s.type===D.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+c});let w=!1,h=!1,y=et(s,t,()=>w=!0,()=>h=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!d||e==null&&g)return y=`? ${y}`,p&&!w?y+=De(y,t.indent,u(p)):h&&i&&i(),y;w&&(p=null),g?(p&&(y+=De(y,t.indent,u(p))),y=`? ${y}
37
+ ${a}:`):(y=`${y}:`,p&&(y+=De(y,t.indent,u(p))));let v,k,A;W(e)?(v=!!e.spaceBefore,k=e.commentBefore,A=e.comment):(v=!1,k=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!p&&q(e)&&(t.indentAtStart=y.length+1),h=!1,!f&&c.length>=2&&!t.inFlow&&!g&&He(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1;const N=et(e,t,()=>O=!0,()=>h=!0);let $=" ";if(p||v||k){if($=v?`
37
38
  `:"",k){const F=u(k);$+=`
38
39
  ${me(F,t.indent)}`}N===""&&!t.inFlow?$===`
39
40
  `&&($=`
40
41
 
41
42
  `):$+=`
42
43
  ${t.indent}`}else if(!g&&J(e)){const F=N[0],I=N.indexOf(`
43
- `),H=I!==-1,we=t.inFlow??e.flow??e.items.length===0;if(H||!we){let Re=!1;if(H&&(F==="&"||F==="!")){let Y=N.indexOf(" ");F==="&"&&Y!==-1&&Y<I&&N[Y+1]==="!"&&(Y=N.indexOf(" ",Y+1)),(Y===-1||I<Y)&&(Re=!0)}Re||($=`
44
+ `),H=I!==-1,we=t.inFlow??e.flow??e.items.length===0;if(H||!we){let _e=!1;if(H&&(F==="&"||F==="!")){let Y=N.indexOf(" ");F==="&"&&Y!==-1&&Y<I&&N[Y+1]==="!"&&(Y=N.indexOf(" ",Y+1)),(Y===-1||I<Y)&&(_e=!0)}_e||($=`
44
45
  ${t.indent}`)}}else(N===""||N[0]===`
45
- `)&&($="");return y+=$+N,t.inFlow?O&&n&&n():A&&!O?y+=Pe(y,t.indent,u(A)):h&&i&&i(),y}l(Qo,"stringifyPair");function Si(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(Si,"warn");const zt="<<",ge={identify:l(s=>s===zt||typeof s=="symbol"&&s.description===zt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new P(Symbol(zt)),{addToJSMap:Ci}),"resolve"),stringify:l(()=>zt,"stringify")},Xo=l((s,e)=>(ge.identify(e)||B(e)&&(!e.type||e.type===P.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function Ci(s,e,t){if(t=s&&Ce(t)?t.resolve(s.doc):t,ze(t))for(const n of t.items)Mn(s,e,n);else if(Array.isArray(t))for(const n of t)Mn(s,e,n);else Mn(s,e,t)}l(Ci,"addMergeToJSMap");function Mn(s,e,t){const n=s&&Ce(t)?t.resolve(s.doc):t;if(!Ge(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(Mn,"mergeValue");function vi(s,e,{key:t,value:n}){if(W(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Xo(s,t))Ci(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=ea(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(vi,"addPairToJSMap");function ea(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(W(s)&&t?.doc){const n=bi(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)+'..."'),Si(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(ea,"stringifyKey");function jn(s,e,t){const n=dt(s,void 0,t),i=dt(e,void 0,t);return new Q(n,i)}l(jn,"createPair");class Q{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,re,{value:oi}),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 vi(t,n,this)}toString(e,t,n){return e?.doc?Qo(this,e,t,n):JSON.stringify(this)}}function ki(s,e,t){return(e.inFlow??s.flow?na:ta)(s,e,t)}l(ki,"stringifyCollection");function ta({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 d=!1;const p=[];for(let w=0;w<e.length;++w){const h=e[w];let y=null;if(W(h))!d&&h.spaceBefore&&p.push(""),Ht(t,p,h.commentBefore,d),h.comment&&(y=h.comment);else if(U(h)){const k=W(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),Ht(t,p,k.commentBefore,d))}d=!1;let v=Xe(h,f,()=>y=null,()=>d=!0);y&&(v+=Pe(v,r,u(y))),d&&y&&(d=!1),p.push(n+v)}let g;if(p.length===0)g=i.start+i.end;else{g=p[0];for(let w=1;w<p.length;++w){const h=p[w];g+=h?`
46
+ `)&&($="");return y+=$+N,t.inFlow?O&&n&&n():A&&!O?y+=De(y,t.indent,u(A)):h&&i&&i(),y}l(sa,"stringifyPair");function vi(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(vi,"warn");const zt="<<",ge={identify:l(s=>s===zt||typeof s=="symbol"&&s.description===zt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new D(Symbol(zt)),{addToJSMap:ki}),"resolve"),stringify:l(()=>zt,"stringify")},ia=l((s,e)=>(ge.identify(e)||q(e)&&(!e.type||e.type===D.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function ki(s,e,t){if(t=s&&Ce(t)?t.resolve(s.doc):t,He(t))for(const n of t.items)jn(s,e,n);else if(Array.isArray(t))for(const n of t)jn(s,e,n);else jn(s,e,t)}l(ki,"addMergeToJSMap");function jn(s,e,t){const n=s&&Ce(t)?t.resolve(s.doc):t;if(!ze(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(jn,"mergeValue");function Ti(s,e,{key:t,value:n}){if(W(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(ia(s,t))ki(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=ra(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(Ti,"addPairToJSMap");function ra(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(W(s)&&t?.doc){const n=Ci(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)+'..."'),vi(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(ra,"stringifyKey");function Kn(s,e,t){const n=dt(s,void 0,t),i=dt(e,void 0,t);return new Q(n,i)}l(Kn,"createPair");class Q{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,re,{value:ci}),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 Ti(t,n,this)}toString(e,t,n){return e?.doc?sa(this,e,t,n):JSON.stringify(this)}}function Ei(s,e,t){return(e.inFlow??s.flow?aa:oa)(s,e,t)}l(Ei,"stringifyCollection");function oa({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 d=!1;const p=[];for(let w=0;w<e.length;++w){const h=e[w];let y=null;if(W(h))!d&&h.spaceBefore&&p.push(""),Ht(t,p,h.commentBefore,d),h.comment&&(y=h.comment);else if(U(h)){const k=W(h.key)?h.key:null;k&&(!d&&k.spaceBefore&&p.push(""),Ht(t,p,k.commentBefore,d))}d=!1;let v=et(h,f,()=>y=null,()=>d=!0);y&&(v+=De(v,r,u(y))),d&&y&&(d=!1),p.push(n+v)}let g;if(p.length===0)g=i.start+i.end;else{g=p[0];for(let w=1;w<p.length;++w){const h=p[w];g+=h?`
46
47
  ${c}${h}`:`
47
48
  `}}return s?(g+=`
48
- `+me(u(s),c),a&&a()):d&&o&&o(),g}l(ta,"stringifyBlockCollection");function na({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 d=[];for(let w=0;w<s.length;++w){const h=s[w];let y=null;if(W(h))h.spaceBefore&&d.push(""),Ht(e,d,h.commentBefore,!1),h.comment&&(y=h.comment);else if(U(h)){const k=W(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Ht(e,d,k.commentBefore,!1),k.comment&&(u=!0));const A=W(h.value)?h.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):h.value==null&&k?.comment&&(y=k.comment)}y&&(u=!0);let v=Xe(h,c,()=>y=null);w<s.length-1&&(v+=","),y&&(v+=Pe(v,n,a(y))),!u&&(d.length>f||v.includes(`
49
+ `+me(u(s),c),a&&a()):d&&o&&o(),g}l(oa,"stringifyBlockCollection");function aa({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 d=[];for(let w=0;w<s.length;++w){const h=s[w];let y=null;if(W(h))h.spaceBefore&&d.push(""),Ht(e,d,h.commentBefore,!1),h.comment&&(y=h.comment);else if(U(h)){const k=W(h.key)?h.key:null;k&&(k.spaceBefore&&d.push(""),Ht(e,d,k.commentBefore,!1),k.comment&&(u=!0));const A=W(h.value)?h.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):h.value==null&&k?.comment&&(y=k.comment)}y&&(u=!0);let v=et(h,c,()=>y=null);w<s.length-1&&(v+=","),y&&(v+=De(v,n,a(y))),!u&&(d.length>f||v.includes(`
49
50
  `))&&(u=!0),d.push(v),f=d.length}const{start:p,end:g}=t;if(d.length===0)return p+g;if(!u){const w=d.reduce((h,y)=>h+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=p;for(const h of d)w+=h?`
50
51
  ${r}${i}${h}`:`
51
52
  `;return`${w}
52
- ${i}${g}`}else return`${p}${o}${d.join(" ")}${o}${g}`}l(na,"stringifyFlowCollection");function Ht({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(Ht,"addCommentBefore");function De(s,e){const t=B(e)?e.value:e;for(const n of s)if(U(n)&&(n.key===e||n.key===t||B(n.key)&&n.key.value===t))return n}l(De,"findPair");class se extends gi{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Se,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(jn(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;U(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=De(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);B(i.value)&&mi(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=De(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=De(this.items,e)?.value;return(!t&&B(i)?i.value:i)??void 0}has(e){return!!De(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)vi(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!U(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})),ki(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const et={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return Ge(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>se.from(s,e,t),"createNode")};class ve extends gi{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ve,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Yt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Yt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&B(i)?i.value:i}has(e){const t=Yt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Yt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];B(i)&&mi(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?ki(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(dt(a,void 0,n))}}return r}}function Yt(s){let e=B(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(Yt,"asItemIndex");const tt={collection:"seq",default:!0,nodeClass:ve,tag:"tag:yaml.org,2002:seq",resolve(s,e){return ze(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>ve.from(s,e,t),"createNode")},Zt={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),mt(s,e,t,n)}},Qt={identify:l(s=>s==null,"identify"),createNode:l(()=>new P(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new P(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&Qt.test.test(s)?s:e.options.nullStr,"stringify")},Kn={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 P(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Kn.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 Ti={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},Ei={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)}},Ii={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 P(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},Xt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Fn=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Oi(s,e,t){const{value:n}=s;return Xt(n)&&n>=0?t+n.toString(e):ae(s)}l(Oi,"intStringify$1");const Ai={identify:l(s=>Xt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>Fn(s,2,8,t),"resolve"),stringify:l(s=>Oi(s,8,"0o"),"stringify")},Ni={identify:Xt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>Fn(s,0,10,t),"resolve"),stringify:ae},$i={identify:l(s=>Xt(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)=>Fn(s,2,16,t),"resolve"),stringify:l(s=>Oi(s,16,"0x"),"stringify")},sa=[et,tt,Zt,Qt,Kn,Ai,Ni,$i,Ti,Ei,Ii];function Li(s){return typeof s=="bigint"||Number.isInteger(s)}l(Li,"intIdentify$1");const en=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),ia=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:en},{identify:l(s=>s==null,"identify"),createNode:l(()=>new P(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:en},{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:en},{identify:Li,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})=>Li(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:en}],ra={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},oa=[et,tt].concat(ia,ra),Bn={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=P.BLOCK_LITERAL),e!==P.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 d=0,p=0;d<u;++d,p+=c)f[d]=a.substr(p,c);a=f.join(e===P.BLOCK_LITERAL?`
53
- `:" ")}return mt({comment:s,type:e,value:a},n,i,r)}};function Pi(s,e){if(ze(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!U(n)){if(Ge(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new P(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
53
+ ${i}${g}`}else return`${p}${o}${d.join(" ")}${o}${g}`}l(aa,"stringifyFlowCollection");function Ht({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(Ht,"addCommentBefore");function Pe(s,e){const t=q(e)?e.value:e;for(const n of s)if(U(n)&&(n.key===e||n.key===t||q(n.key)&&n.key.value===t))return n}l(Pe,"findPair");class se extends wi{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Se,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(Kn(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;U(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=Pe(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);q(i.value)&&yi(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=Pe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=Pe(this.items,e)?.value;return(!t&&q(i)?i.value:i)??void 0}has(e){return!!Pe(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)Ti(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!U(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})),Ei(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const tt={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return ze(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>se.from(s,e,t),"createNode")};class ve extends wi{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ge,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Yt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Yt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&q(i)?i.value:i}has(e){const t=Yt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Yt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];q(i)&&yi(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?Ei(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(dt(a,void 0,n))}}return r}}function Yt(s){let e=q(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(Yt,"asItemIndex");const nt={collection:"seq",default:!0,nodeClass:ve,tag:"tag:yaml.org,2002:seq",resolve(s,e){return He(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>ve.from(s,e,t),"createNode")},Zt={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),mt(s,e,t,n)}},Qt={identify:l(s=>s==null,"identify"),createNode:l(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new D(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&Qt.test.test(s)?s:e.options.nullStr,"stringify")},Fn={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 D(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Fn.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 Ii={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},Oi={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)}},Ai={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 D(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},Xt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),qn=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function Ni(s,e,t){const{value:n}=s;return Xt(n)&&n>=0?t+n.toString(e):ae(s)}l(Ni,"intStringify$1");const $i={identify:l(s=>Xt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>qn(s,2,8,t),"resolve"),stringify:l(s=>Ni(s,8,"0o"),"stringify")},Li={identify:Xt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>qn(s,0,10,t),"resolve"),stringify:ae},Di={identify:l(s=>Xt(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)=>qn(s,2,16,t),"resolve"),stringify:l(s=>Ni(s,16,"0x"),"stringify")},ca=[tt,nt,Zt,Qt,Fn,$i,Li,Di,Ii,Oi,Ai];function Pi(s){return typeof s=="bigint"||Number.isInteger(s)}l(Pi,"intIdentify$1");const en=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),la=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:en},{identify:l(s=>s==null,"identify"),createNode:l(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:en},{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:en},{identify:Pi,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})=>Pi(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:en}],ua={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},fa=[tt,nt].concat(la,ua),Bn={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=D.BLOCK_LITERAL),e!==D.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 d=0,p=0;d<u;++d,p+=c)f[d]=a.substr(p,c);a=f.join(e===D.BLOCK_LITERAL?`
54
+ `:" ")}return mt({comment:s,type:e,value:a},n,i,r)}};function xi(s,e){if(He(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!U(n)){if(ze(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new D(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
54
55
  ${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]=U(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}l(Pi,"resolvePairs");function Di(s,e,t){const{replacer:n}=t,i=new ve(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(jn(a,c,t))}return i}l(Di,"createPairs");const qn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Pi,createNode:Di};class ot extends ve{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=ot.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(U(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=Di(e,t,n),r=new this;return r.items=i.items,r}}ot.tag="tag:yaml.org,2002:omap";const Un={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:ot,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Pi(s,e),n=[];for(const{key:i}of t.items)B(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ot,t)},createNode:l((s,e,t)=>ot.from(s,e,t),"createNode")};function xi({value:s,source:e},t){return e&&(s?_i:Ri).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(xi,"boolStringify");const _i={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 P(!0),"resolve"),stringify:xi},Ri={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 P(!1),"resolve"),stringify:xi},aa={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},ca={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)}},la={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 P(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},gt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function tn(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(tn,"intResolve");function Jn(s,e,t){const{value:n}=s;if(gt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}l(Jn,"intStringify");const ua={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>tn(s,2,2,t),"resolve"),stringify:l(s=>Jn(s,2,"0b"),"stringify")},fa={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>tn(s,1,8,t),"resolve"),stringify:l(s=>Jn(s,8,"0"),"stringify")},da={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>tn(s,0,10,t),"resolve"),stringify:ae},ha={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>tn(s,2,16,t),"resolve"),stringify:l(s=>Jn(s,16,"0x"),"stringify")};class at extends se{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=at.tag}add(e){let t;U(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),De(this.items,t.key)||this.items.push(t)}get(e,t){const n=De(this.items,e);return!t&&U(n)?B(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=De(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(jn(o,null,n));return r}}at.tag="tag:yaml.org,2002:set";const Wn={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:at,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>at.from(s,e,t),"createNode"),resolve(s,e){if(Ge(s)){if(s.hasAllNullValues(!0))return Object.assign(new at,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Vn(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(Vn,"parseSexagesimal");function Mi(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(Mi,"stringifySexagesimal");const ji={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})=>Vn(s,t),"resolve"),stringify:Mi},Ki={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=>Vn(s,!1),"resolve"),stringify:Mi},nn={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(nn.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 d=Vn(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:l(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Fi=[et,tt,Zt,Qt,_i,Ri,ua,fa,da,ha,aa,ca,la,Bn,ge,Un,qn,Wn,ji,Ki,nn],Bi=new Map([["core",sa],["failsafe",[et,tt,Zt]],["json",oa],["yaml11",Fi],["yaml-1.1",Fi]]),qi={binary:Bn,bool:Kn,float:Ii,floatExp:Ei,floatNaN:Ti,floatTime:Ki,int:Ni,intHex:$i,intOct:Ai,intTime:ji,map:et,merge:ge,null:Qt,omap:Un,pairs:qn,seq:tt,set:Wn,timestamp:nn},pa={"tag:yaml.org,2002:binary":Bn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":Un,"tag:yaml.org,2002:pairs":qn,"tag:yaml.org,2002:set":Wn,"tag:yaml.org,2002:timestamp":nn};function Gn(s,e,t){const n=Bi.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(Bi.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"?qi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(qi).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(Gn,"getTags");const ma=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class yn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Gn(e,"compat"):e?Gn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?pa:{},this.tags=Gn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:et}),Object.defineProperty(this,fe,{value:Zt}),Object.defineProperty(this,Ve,{value:tt}),this.sortMapEntries=typeof o=="function"?o:o===!0?ma:null}clone(){const e=Object.create(yn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function ga(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=bi(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=Xe(s.contents,i,()=>a=null,c);a&&(u+=Pe(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Xe(s.contents,i));if(s.directives?.docEnd)if(s.comment){const c=r(s.comment);c.includes(`
56
+ ${r.comment}`:n.comment}n=i}s.items[t]=U(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}l(xi,"resolvePairs");function Ri(s,e,t){const{replacer:n}=t,i=new ve(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(Kn(a,c,t))}return i}l(Ri,"createPairs");const Un={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:xi,createNode:Ri};class at extends ve{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=at.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(U(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=Ri(e,t,n),r=new this;return r.items=i.items,r}}at.tag="tag:yaml.org,2002:omap";const Jn={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:at,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=xi(s,e),n=[];for(const{key:i}of t.items)q(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new at,t)},createNode:l((s,e,t)=>at.from(s,e,t),"createNode")};function _i({value:s,source:e},t){return e&&(s?Mi:ji).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(_i,"boolStringify");const Mi={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 D(!0),"resolve"),stringify:_i},ji={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 D(!1),"resolve"),stringify:_i},da={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},ha={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)}},pa={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 D(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},gt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function tn(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(tn,"intResolve");function Wn(s,e,t){const{value:n}=s;if(gt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}l(Wn,"intStringify");const ma={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>tn(s,2,2,t),"resolve"),stringify:l(s=>Wn(s,2,"0b"),"stringify")},ga={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>tn(s,1,8,t),"resolve"),stringify:l(s=>Wn(s,8,"0"),"stringify")},ya={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>tn(s,0,10,t),"resolve"),stringify:ae},wa={identify:gt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>tn(s,2,16,t),"resolve"),stringify:l(s=>Wn(s,16,"0x"),"stringify")};class ct extends se{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=ct.tag}add(e){let t;U(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),Pe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Pe(this.items,e);return!t&&U(n)?q(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=Pe(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(Kn(o,null,n));return r}}ct.tag="tag:yaml.org,2002:set";const Vn={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:ct,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>ct.from(s,e,t),"createNode"),resolve(s,e){if(ze(s)){if(s.hasAllNullValues(!0))return Object.assign(new ct,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Gn(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(Gn,"parseSexagesimal");function Ki(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(Ki,"stringifySexagesimal");const Fi={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})=>Gn(s,t),"resolve"),stringify:Ki},qi={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=>Gn(s,!1),"resolve"),stringify:Ki},nn={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(nn.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 d=Gn(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:l(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Bi=[tt,nt,Zt,Qt,Mi,ji,ma,ga,ya,wa,da,ha,pa,Bn,ge,Jn,Un,Vn,Fi,qi,nn],Ui=new Map([["core",ca],["failsafe",[tt,nt,Zt]],["json",fa],["yaml11",Bi],["yaml-1.1",Bi]]),Ji={binary:Bn,bool:Fn,float:Ai,floatExp:Oi,floatNaN:Ii,floatTime:qi,int:Li,intHex:Di,intOct:$i,intTime:Fi,map:tt,merge:ge,null:Qt,omap:Jn,pairs:Un,seq:nt,set:Vn,timestamp:nn},ba={"tag:yaml.org,2002:binary":Bn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":Jn,"tag:yaml.org,2002:pairs":Un,"tag:yaml.org,2002:set":Vn,"tag:yaml.org,2002:timestamp":nn};function zn(s,e,t){const n=Ui.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(Ui.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"?Ji[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(Ji).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(zn,"getTags");const Sa=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class yn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?zn(e,"compat"):e?zn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?ba:{},this.tags=zn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:tt}),Object.defineProperty(this,fe,{value:Zt}),Object.defineProperty(this,Ge,{value:nt}),this.sortMapEntries=typeof o=="function"?o:o===!0?Sa:null}clone(){const e=Object.create(yn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Ca(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=Ci(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=et(s.contents,i,()=>a=null,c);a&&(u+=De(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(et(s.contents,i));if(s.directives?.docEnd)if(s.comment){const c=r(s.comment);c.includes(`
56
57
  `)?(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
58
  `)+`
58
- `}l(ga,"stringifyDocument");class ct{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re,{value:Pn});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(ct.prototype,{[re]:{value:Pn}});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){nt(this.contents)&&this.contents.add(e)}addIn(e,t){nt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=hi(this);e.anchor=!t||n.has(t)?pi(t||"a",n):t}return new Ft(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(k=>typeof k=="number"||k instanceof String||k instanceof Number,"keyToStr"),v=t.filter(y).map(String);v.length>0&&(t=t.concat(v)),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:d,setAnchors:p,sourceObjects:g}=Jo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},h=dt(e,f,w);return a&&J(h)&&(h.flow=!0),p(),h}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 nt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ht(e)?this.contents==null?!1:(this.contents=null,!0):nt(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 ht(e)?!t&&B(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 ht(e)?this.contents!==void 0:J(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=qt(this.schema,[e],t):nt(this.contents)&&this.contents.set(e,t)}setIn(e,t){ht(e)?this.contents=t:this.contents==null?this.contents=qt(this.schema,Array.from(e),t):nt(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 yn(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 ga(this,e)}}function nt(s){if(J(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(nt,"assertCollection");class zn 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 xe extends zn{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ui extends zn{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const sn=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
+ `}l(Ca,"stringifyDocument");class lt{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,re,{value:Pn});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(lt.prototype,{[re]:{value:Pn}});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){st(this.contents)&&this.contents.add(e)}addIn(e,t){st(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=mi(this);e.anchor=!t||n.has(t)?gi(t||"a",n):t}return new Ft(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(k=>typeof k=="number"||k instanceof String||k instanceof Number,"keyToStr"),v=t.filter(y).map(String);v.length>0&&(t=t.concat(v)),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:d,setAnchors:p,sourceObjects:g}=Ho(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},h=dt(e,f,w);return a&&J(h)&&(h.flow=!0),p(),h}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 st(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ht(e)?this.contents==null?!1:(this.contents=null,!0):st(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 ht(e)?!t&&q(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 ht(e)?this.contents!==void 0:J(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Bt(this.schema,[e],t):st(this.contents)&&this.contents.set(e,t)}setIn(e,t){ht(e)?this.contents=t:this.contents==null?this.contents=Bt(this.schema,Array.from(e),t):st(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 yn(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"?Qe(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 Ca(this,e)}}function st(s){if(J(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(st,"assertCollection");class Hn 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 xe extends Hn{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Wi extends Hn{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const sn=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
60
  `),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
61
 
61
62
  ${o}
62
63
  ${u}
63
- `}},"prettifyError");function st(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,d="",p="",g=!1,w=!1,h=null,y=null,v=null,k=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),h&&(u&&I.type!=="comment"&&I.type!=="newline"&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),I.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(h=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)||" ";d?d+=p+H:d=H,p="",u=!1;break}case"newline":u?d?d+=I.source:(!O||t!=="seq-item-ind")&&(c=!0):p+=I.source,u=!0,g=!0,(y||v)&&(k=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":{v&&r(I,"MULTIPLE_TAGS","A node can have at most one tag"),v=I,N??(N=I.offset),u=!1,f=!1,w=!0;break}case t:(y||v)&&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],F=$?$.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"),h&&(u&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:O,spaceBefore:c,comment:d,hasNewline:g,anchor:y,tag:v,newlineAfterProp:k,end:F,start:N??F}}l(st,"resolveProps");function yt(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(yt(e.key)||yt(e.value))return!0}return!1;default:return!0}}l(yt,"containsNewline");function Hn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&yt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Hn,"flowIndentCheck");function Ji(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||B(r)&&B(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(Ji,"mapIncludes");const Wi="All mapping items must start at the same column";function ya({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:d,key:p,sep:g,value:w}=f,h=st(d,{indicator:"explicit-key-ind",next:p??g?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.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",Wi)),!h.anchor&&!h.tag&&!g){u=h.end,h.comment&&(a.comment?a.comment+=`
65
- `+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||yt(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Wi);t.atKey=!0;const v=h.end,k=p?s(t,p,h,i):e(t,v,d,null,h,i);t.schema.compat&&Hn(n.indent,p,i),t.atKey=!1,Ji(t,a.items,k)&&i(v,"DUPLICATE_KEY","Map keys must be unique");const A=st(g??[],{indicator:"map-value-ind",next:w,offset:k.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&&h.start<A.found.offset-1024&&i(k.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&&Hn(n.indent,w,i),c=O.range[2];const N=new Q(k,O);t.options.keepSourceTokens&&(N.srcToken=f),a.items.push(N)}else{y&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(k.comment?k.comment+=`
66
- `+A.comment:k.comment=A.comment);const O=new Q(k);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(ya,"resolveBlockMap");function wa({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ve,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:d}of n.items){const p=st(f,{indicator:"seq-item-ind",next:d,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d&&d.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=d?s(t,d,p,i):e(t,p.end,f,null,p,i);t.schema.compat&&Hn(n.indent,d,i),c=g.range[2],a.items.push(g)}return a.range=[n.offset,c,u??c],a}l(wa,"resolveBlockSeq");function wt(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(wt,"resolveEnd");const Yn="Block collections are not allowed within flow collections",Zn=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ba({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?se:ve),u=new c(t.schema);u.flow=!0;const f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const v=n.items[y],{start:k,key:A,sep:O,value:N}=v,$=st(k,{flow:a,indicator:"explicit-key-ind",next:A??O?.[0],offset:d,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+=`
64
+ `}},"prettifyError");function it(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,d="",p="",g=!1,w=!1,h=null,y=null,v=null,k=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),h&&(u&&I.type!=="comment"&&I.type!=="newline"&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),I.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&I.source.includes(" ")&&(h=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)||" ";d?d+=p+H:d=H,p="",u=!1;break}case"newline":u?d?d+=I.source:(!O||t!=="seq-item-ind")&&(c=!0):p+=I.source,u=!0,g=!0,(y||v)&&(k=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":{v&&r(I,"MULTIPLE_TAGS","A node can have at most one tag"),v=I,N??(N=I.offset),u=!1,f=!1,w=!0;break}case t:(y||v)&&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],F=$?$.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"),h&&(u&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:O,spaceBefore:c,comment:d,hasNewline:g,anchor:y,tag:v,newlineAfterProp:k,end:F,start:N??F}}l(it,"resolveProps");function yt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
65
+ `))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(yt(e.key)||yt(e.value))return!0}return!1;default:return!0}}l(yt,"containsNewline");function Yn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&yt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Yn,"flowIndentCheck");function Vi(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||q(r)&&q(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(Vi,"mapIncludes");const Gi="All mapping items must start at the same column";function va({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:d,key:p,sep:g,value:w}=f,h=it(d,{indicator:"explicit-key-ind",next:p??g?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!h.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",Gi)),!h.anchor&&!h.tag&&!g){u=h.end,h.comment&&(a.comment?a.comment+=`
66
+ `+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||yt(p))&&i(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&i(c,"BAD_INDENT",Gi);t.atKey=!0;const v=h.end,k=p?s(t,p,h,i):e(t,v,d,null,h,i);t.schema.compat&&Yn(n.indent,p,i),t.atKey=!1,Vi(t,a.items,k)&&i(v,"DUPLICATE_KEY","Map keys must be unique");const A=it(g??[],{indicator:"map-value-ind",next:w,offset:k.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&&h.start<A.found.offset-1024&&i(k.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&&Yn(n.indent,w,i),c=O.range[2];const N=new Q(k,O);t.options.keepSourceTokens&&(N.srcToken=f),a.items.push(N)}else{y&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(k.comment?k.comment+=`
67
+ `+A.comment:k.comment=A.comment);const O=new Q(k);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(va,"resolveBlockMap");function ka({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ve,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:d}of n.items){const p=it(f,{indicator:"seq-item-ind",next:d,offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d&&d.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=d?s(t,d,p,i):e(t,p.end,f,null,p,i);t.schema.compat&&Yn(n.indent,d,i),c=g.range[2],a.items.push(g)}return a.range=[n.offset,c,u??c],a}l(ka,"resolveBlockSeq");function wt(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(wt,"resolveEnd");const Zn="Block collections are not allowed within flow collections",Qn=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Ta({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?se:ve),u=new c(t.schema);u.flow=!0;const f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const v=n.items[y],{start:k,key:A,sep:O,value:N}=v,$=it(k,{flow:a,indicator:"explicit-key-ind",next:A??O?.[0],offset:d,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
68
  `+$.comment:u.comment=$.comment),d=$.end;continue}!o&&t.options.strict&&yt(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 F="";e:for(const I of k)switch(I.type){case"comma":case"space":break;case"comment":F=I.source.substring(1);break e;default:break e}if(F){let I=u.items[u.items.length-1];U(I)&&(I=I.value??I.key),I.comment?I.comment+=`
68
- `+F:I.comment=F,$.comment=$.comment.substring(F.length+1)}}if(!o&&!O&&!$.found){const F=N?s(t,N,$,i):e(t,$.end,O,null,$,i);u.items.push(F),d=F.range[2],Zn(N)&&i(F.range,"BLOCK_IN_FLOW",Yn)}else{t.atKey=!0;const F=$.end,I=A?s(t,A,$,i):e(t,F,k,null,$,i);Zn(A)&&i(I.range,"BLOCK_IN_FLOW",Yn),t.atKey=!1;const H=st(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 we=N?s(t,N,H,i):H.found?e(t,H.end,O,null,H,i):null;we?Zn(N)&&i(we.range,"BLOCK_IN_FLOW",Yn):H.comment&&(I.comment?I.comment+=`
69
- `+H.comment:I.comment=H.comment);const Re=new Q(I,we);if(t.options.keepSourceTokens&&(Re.srcToken=v),o){const Y=u;Ji(t,Y.items,I)&&i(F,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(Re)}else{const Y=new se(t.schema);Y.flow=!0,Y.items.push(Re);const ks=(we??I).range;Y.range=[I.range[0],ks[1],ks[2]],u.items.push(Y)}d=we?we.range[2]:H.end}}const p=o?"}":"]",[g,...w]=n.end;let h=d;if(g&&g.source===p)h=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),v=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;i(d,f?"MISSING_CHAR":"BAD_INDENT",v),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=wt(w,h,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
- `+y.comment:u.comment=y.comment),u.range=[n.offset,h,y.offset]}else u.range=[n.offset,h,h];return u}l(ba,"resolveFlowCollection");function Qn(s,e,t,n,i,r){const o=t.type==="block-map"?ya(s,e,t,n,r):t.type==="block-seq"?wa(s,e,t,n,r):ba(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(Qn,"resolveCollection");function Sa(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===ve.tagName&&a==="seq")return Qn(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),Qn(s,e,t,i,o)}const u=Qn(s,e,t,i,o,c),f=c.resolve?.(u,p=>i(r,"TAG_RESOLVE_FAILED",p),e.options)??u,d=W(f)?f:new P(f);return d.range=u.range,d.tag=o,c?.format&&(d.format=c.format),d}l(Sa,"composeCollection");function Vi(s,e,t){const n=e.offset,i=Ca(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?P.BLOCK_FOLDED:P.BLOCK_LITERAL,o=e.source?va(e.source):[];let a=o.length;for(let h=o.length-1;h>=0;--h){const y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){const h=i.chomp==="+"&&o.length>0?`
69
+ `+F:I.comment=F,$.comment=$.comment.substring(F.length+1)}}if(!o&&!O&&!$.found){const F=N?s(t,N,$,i):e(t,$.end,O,null,$,i);u.items.push(F),d=F.range[2],Qn(N)&&i(F.range,"BLOCK_IN_FLOW",Zn)}else{t.atKey=!0;const F=$.end,I=A?s(t,A,$,i):e(t,F,k,null,$,i);Qn(A)&&i(I.range,"BLOCK_IN_FLOW",Zn),t.atKey=!1;const H=it(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 we=N?s(t,N,H,i):H.found?e(t,H.end,O,null,H,i):null;we?Qn(N)&&i(we.range,"BLOCK_IN_FLOW",Zn):H.comment&&(I.comment?I.comment+=`
70
+ `+H.comment:I.comment=H.comment);const _e=new Q(I,we);if(t.options.keepSourceTokens&&(_e.srcToken=v),o){const Y=u;Vi(t,Y.items,I)&&i(F,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(_e)}else{const Y=new se(t.schema);Y.flow=!0,Y.items.push(_e);const Ts=(we??I).range;Y.range=[I.range[0],Ts[1],Ts[2]],u.items.push(Y)}d=we?we.range[2]:H.end}}const p=o?"}":"]",[g,...w]=n.end;let h=d;if(g&&g.source===p)h=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),v=f?`${y} must end with a ${p}`:`${y} in block collection must be sufficiently indented and end with a ${p}`;i(d,f?"MISSING_CHAR":"BAD_INDENT",v),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=wt(w,h,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
71
+ `+y.comment:u.comment=y.comment),u.range=[n.offset,h,y.offset]}else u.range=[n.offset,h,h];return u}l(Ta,"resolveFlowCollection");function Xn(s,e,t,n,i,r){const o=t.type==="block-map"?va(s,e,t,n,r):t.type==="block-seq"?ka(s,e,t,n,r):Ta(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(Xn,"resolveCollection");function Ea(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===ve.tagName&&a==="seq")return Xn(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),Xn(s,e,t,i,o)}const u=Xn(s,e,t,i,o,c),f=c.resolve?.(u,p=>i(r,"TAG_RESOLVE_FAILED",p),e.options)??u,d=W(f)?f:new D(f);return d.range=u.range,d.tag=o,c?.format&&(d.format=c.format),d}l(Ea,"composeCollection");function zi(s,e,t){const n=e.offset,i=Ia(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,o=e.source?Oa(e.source):[];let a=o.length;for(let h=o.length-1;h>=0;--h){const y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){const h=i.chomp==="+"&&o.length>0?`
71
72
  `.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:h,type:r,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,u=e.offset+i.length,f=0;for(let h=0;h<a;++h){const[y,v]=o[h];if(v===""||v==="\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=h,c===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+v.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>c&&(a=h+1);let d="",p="",g=!1;for(let h=0;h<f;++h)d+=o[h][0].slice(c)+`
72
- `;for(let h=f;h<a;++h){let[y,v]=o[h];u+=y.length+v.length+1;const k=v[v.length-1]==="\r";if(k&&(v=v.slice(0,-1)),v&&y.length<c){const O=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-v.length-(k?2:1),"BAD_INDENT",O),y=""}r===P.BLOCK_LITERAL?(d+=p+y.slice(c)+v,p=`
73
+ `;for(let h=f;h<a;++h){let[y,v]=o[h];u+=y.length+v.length+1;const k=v[v.length-1]==="\r";if(k&&(v=v.slice(0,-1)),v&&y.length<c){const O=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-v.length-(k?2:1),"BAD_INDENT",O),y=""}r===D.BLOCK_LITERAL?(d+=p+y.slice(c)+v,p=`
73
74
  `):y.length>c||v[0]===" "?(p===" "?p=`
74
75
  `:!g&&p===`
75
76
  `&&(p=`
@@ -82,46 +83,46 @@ ${u}
82
83
  `+o[h][0].slice(c);d[d.length-1]!==`
83
84
  `&&(d+=`
84
85
  `);break;default:d+=`
85
- `}const w=n+i.length+e.source.length;return{value:d,type:r,comment:i.comment,range:[n,w,w]}}l(Vi,"resolveBlockScalar");function Ca({offset:s,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",c=-1;for(let p=1;p<i.length;++p){const g=i[p];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:c===-1&&(c=s+p)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,f="",d=i.length;for(let p=1;p<e.length;++p){const g=e[p];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,f=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const h=g.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:r,indent:o,chomp:a,comment:f,length:d}}l(Ca,"parseBlockScalarHeader");function va(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}l(va,"splitLines");function Gi(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,c;const u=l((p,g,w)=>t(n+p,g,w),"_onError");switch(i){case"scalar":a=P.PLAIN,c=ka(r,u);break;case"single-quoted-scalar":a=P.QUOTE_SINGLE,c=Ta(r,u);break;case"double-quoted-scalar":a=P.QUOTE_DOUBLE,c=Ea(r,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+r.length,n+r.length]}}const f=n+r.length,d=wt(o,f,e,t);return{value:c,type:a,comment:d.comment,range:[n,f,d.offset]}}l(Gi,"resolveFlowScalar");function ka(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),zi(s)}l(ka,"plainValue");function Ta(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),zi(s.slice(1,-1)).replace(/''/g,"'")}l(Ta,"singleQuotedValue");function zi(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
+ `}const w=n+i.length+e.source.length;return{value:d,type:r,comment:i.comment,range:[n,w,w]}}l(zi,"resolveBlockScalar");function Ia({offset:s,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",c=-1;for(let p=1;p<i.length;++p){const g=i[p];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:c===-1&&(c=s+p)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,f="",d=i.length;for(let p=1;p<e.length;++p){const g=e[p];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,f=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const h=g.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:r,indent:o,chomp:a,comment:f,length:d}}l(Ia,"parseBlockScalarHeader");function Oa(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}l(Oa,"splitLines");function Hi(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,c;const u=l((p,g,w)=>t(n+p,g,w),"_onError");switch(i){case"scalar":a=D.PLAIN,c=Aa(r,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,c=Na(r,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,c=$a(r,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+r.length,n+r.length]}}const f=n+r.length,d=wt(o,f,e,t);return{value:c,type:a,comment:d.comment,range:[n,f,d.offset]}}l(Hi,"resolveFlowScalar");function Aa(s,e){let t="";switch(s[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${s[0]}`;break}case"@":case"`":{t=`reserved character ${s[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Yi(s)}l(Aa,"plainValue");function Na(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Yi(s.slice(1,-1)).replace(/''/g,"'")}l(Na,"singleQuotedValue");function Yi(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
87
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
87
88
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(s);if(!n)return s;let i=n[1],r=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(s);)n[1]===""?r===`
88
89
  `?i+=r:r=`
89
- `:(i+=r+n[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),i+r+(n?.[1]??"")}l(zi,"foldLines");function Ea(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
90
+ `:(i+=r+n[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),i+r+(n?.[1]??"")}l(Yi,"foldLines");function $a(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
90
91
  `))if(i===`
91
- `){const{fold:r,offset:o}=Ia(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=Oa[r];if(o)t+=o;else if(r===`
92
+ `){const{fold:r,offset:o}=La(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=Da[r];if(o)t+=o;else if(r===`
92
93
  `)for(r=s[n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="\r"&&s[n+1]===`
93
- `)for(r=s[++n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=Aa(s,n+1,a,e),n+=a}else{const a=s.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
94
+ `)for(r=s[++n+1];r===" "||r===" ";)r=s[++n+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=Pa(s,n+1,a,e),n+=a}else{const a=s.substr(n-1,2);e(n-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
94
95
  `&&!(o==="\r"&&s[n+2]===`
95
- `)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}l(Ea,"doubleQuotedValue");function Ia(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
+ `)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}l($a,"doubleQuotedValue");function La(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
97
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
97
98
  `);)n===`
98
99
  `&&(t+=`
99
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}l(Ia,"foldNewline");const Oa={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 Aa(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(Aa,"parseCharCode");function Hi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Vi(s,e,n):Gi(e,s.options.strict,n),c=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:c?u=Na(s.schema,i,c,t,n):e.type==="scalar"?u=$a(s,i,e,n):u=s.schema[fe];let f;try{const d=u.resolve(i,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);f=B(d)?d:new P(d)}catch(d){const p=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",p),f=new P(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(Hi,"composeScalar");function Na(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(Na,"findScalarTagByName");function $a({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($a,"findScalarTagByTest");function La(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(La,"emptyScalarPosition");const Pa={composeNode:Yi,composeEmptyNode:Xn};function Yi(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=Da(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=Hi(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Sa(Pa,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=Xn(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&&(!B(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(Yi,"composeNode");function Xn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const f={type:"scalar",offset:La(e,t,n),indent:-1,source:""},d=Hi(s,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),r&&(d.comment=r,d.range[2]=c),d}l(Xn,"composeEmptyNode");function Da({options:s},{offset:e,source:t,end:n},i){const r=new Ft(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=wt(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(Da,"composeAlias");function xa(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),c=new ct(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=st(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?Yi(u,i,f,o):Xn(u,f.end,n,null,f,o);const d=c.contents.range[2],p=wt(r,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[t,d,p.offset],c}l(xa,"composeDoc");function bt(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(bt,"getErrorPos");function Zi(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
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}l(La,"foldNewline");const Da={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Pa(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(Pa,"parseCharCode");function Zi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?zi(s,e,n):Hi(e,s.options.strict,n),c=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:c?u=xa(s.schema,i,c,t,n):e.type==="scalar"?u=Ra(s,i,e,n):u=s.schema[fe];let f;try{const d=u.resolve(i,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);f=q(d)?d:new D(d)}catch(d){const p=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",p),f=new D(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(Zi,"composeScalar");function xa(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(xa,"findScalarTagByName");function Ra({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(Ra,"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 Ma={composeNode:Qi,composeEmptyNode:es};function Qi(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=ja(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=Zi(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Ea(Ma,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",d),u=es(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&&(!q(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(Qi,"composeNode");function es(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:""},d=Zi(s,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),r&&(d.comment=r,d.range[2]=c),d}l(es,"composeEmptyNode");function ja({options:s},{offset:e,source:t,end:n},i){const r=new Ft(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=wt(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(ja,"composeAlias");function Ka(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),c=new lt(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=it(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?Qi(u,i,f,o):es(u,f.end,n,null,f,o);const d=c.contents.range[2],p=wt(r,d,!1,o);return p.comment&&(c.comment=p.comment),c.range=[t,d,p.offset],c}l(Ka,"composeDoc");function bt(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(bt,"getErrorPos");function Xi(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
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(Zi,"parsePrelude");class es{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=bt(t);r?this.warnings.push(new Ui(o,n,i)):this.errors.push(new xe(o,n,i))},this.directives=new X({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Zi(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ `)+(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(Xi,"parsePrelude");class ts{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=bt(t);r?this.warnings.push(new Wi(o,n,i)):this.errors.push(new xe(o,n,i))},this.directives=new X({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Xi(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
105
  ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(J(r)&&!r.flow&&r.items.length>0){let o=r.items[0];U(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
105
106
  ${a}`:n}else{const o=r.commentBefore;r.commentBefore=o?`${n}
106
- ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Zi(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,i)=>{const r=bt(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=xa(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new xe(bt(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const n="Unexpected doc-end without preceding document";this.errors.push(new xe(bt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=wt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
107
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new xe(bt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const n=Object.assign({_directives:this.directives},this.options),i=new ct(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function _a(s,e=!0,t){if(s){const n=l((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new xe([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Gi(s,e,n);case"block-scalar":return Vi({options:{strict:e}},s,n)}}return null}l(_a,"resolveAsScalar");function Ra(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=mt({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
107
+ ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Xi(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(const i of e)yield*this.next(i);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,i)=>{const r=bt(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Ka(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new xe(bt(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case"doc-end":{if(!this.doc){const n="Unexpected doc-end without preceding document";this.errors.push(new xe(bt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=wt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
108
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new xe(bt(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const n=Object.assign({_directives:this.directives},this.options),i=new lt(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function Fa(s,e=!0,t){if(s){const n=l((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new xe([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Hi(s,e,n);case"block-scalar":return zi({options:{strict:e}},s,n)}}return null}l(Fa,"resolveAsScalar");function qa(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=mt({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
108
109
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
109
110
  `),f=a.substring(0,u),d=a.substring(u+1)+`
110
- `,p=[{type:"block-scalar-header",offset:r,indent:n,source:f}];return Qi(p,c)||p.push({type:"newline",offset:-1,indent:n,source:`
111
- `}),{type:"block-scalar",offset:r,indent:n,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:c};default:return{type:"scalar",offset:r,indent:n,source:a,end:c}}}l(Ra,"createScalarToken");function Ma(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=mt({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":ja(s,c);break;case'"':ts(s,c,"double-quoted-scalar");break;case"'":ts(s,c,"single-quoted-scalar");break;default:ts(s,c,"scalar")}}l(Ma,"setScalarValue");function ja(s,e){const t=e.indexOf(`
111
+ `,p=[{type:"block-scalar-header",offset:r,indent:n,source:f}];return er(p,c)||p.push({type:"newline",offset:-1,indent:n,source:`
112
+ `}),{type:"block-scalar",offset:r,indent:n,props:p,source:d}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:c};default:return{type:"scalar",offset:r,indent:n,source:a,end:c}}}l(qa,"createScalarToken");function Ba(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=mt({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":Ua(s,c);break;case'"':ns(s,c,"double-quoted-scalar");break;case"'":ns(s,c,"single-quoted-scalar");break;default:ns(s,c,"scalar")}}l(Ba,"setScalarValue");function Ua(s,e){const t=e.indexOf(`
112
113
  `),n=e.substring(0,t),i=e.substring(t+1)+`
113
- `;if(s.type==="block-scalar"){const r=s.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=n,s.source=i}else{const{offset:r}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:n}];Qi(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
- `});for(const c of Object.keys(s))c!=="type"&&c!=="offset"&&delete s[c];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}l(ja,"setBlockScalarValue");function Qi(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}l(Qi,"addEndtoBlockProps");function ts(s,e,t){switch(s.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":s.type=t,s.source=e;break;case"block-scalar":{const n=s.props.slice(1);let i=e.length;s.props[0].type==="block-scalar-header"&&(i-=s.props[0].source.length);for(const r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const i={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
115
- `};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{const n="indent"in s?s.indent:-1,i="end"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(s))r!=="type"&&r!=="offset"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}l(ts,"setFlowScalarValue");const Ka=l(s=>"type"in s?rn(s):on(s),"stringify$1");function rn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=rn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=on(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=on(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=on(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}l(rn,"stringifyToken");function on({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=rn(e)),t)for(const r of t)i+=r.source;return n&&(i+=rn(n)),i}l(on,"stringifyItem");const ns=Symbol("break visit"),Fa=Symbol("skip children"),Xi=Symbol("remove item");function _e(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),er(Object.freeze([]),s,e)}l(_e,"visit"),_e.BREAK=ns,_e.SKIP=Fa,_e.REMOVE=Xi,_e.itemAtPath=(s,e)=>{let t=s;for(const[n,i]of e){const r=t?.[n];if(r&&"items"in r)t=r.items[i];else return}return t},_e.parentCollection=(s,e)=>{const t=_e.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function er(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const i of["key","value"]){const r=e[i];if(r&&"items"in r){for(let o=0;o<r.items.length;++o){const a=er(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ns)return ns;a===Xi&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}l(er,"_visit");const an="\uFEFF",cn="",ln="",St="",Ba=l(s=>!!s&&"items"in s,"isCollection"),qa=l(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Ua(s){switch(s){case an:return"<BOM>";case cn:return"<DOC>";case ln:return"<FLOW_END>";case St:return"<SCALAR>";default:return JSON.stringify(s)}}l(Ua,"prettyToken");function tr(s){switch(s){case an:return"byte-order-mark";case cn:return"doc-mode";case ln:return"flow-error-end";case St:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
114
+ `;if(s.type==="block-scalar"){const r=s.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=n,s.source=i}else{const{offset:r}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:n}];er(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
+ `});for(const c of Object.keys(s))c!=="type"&&c!=="offset"&&delete s[c];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}l(Ua,"setBlockScalarValue");function er(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}l(er,"addEndtoBlockProps");function ns(s,e,t){switch(s.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":s.type=t,s.source=e;break;case"block-scalar":{const n=s.props.slice(1);let i=e.length;s.props[0].type==="block-scalar-header"&&(i-=s.props[0].source.length);for(const r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const i={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
116
+ `};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{const n="indent"in s?s.indent:-1,i="end"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(s))r!=="type"&&r!=="offset"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}l(ns,"setFlowScalarValue");const Ja=l(s=>"type"in s?rn(s):on(s),"stringify$1");function rn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=rn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=on(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=on(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=on(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}l(rn,"stringifyToken");function on({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=rn(e)),t)for(const r of t)i+=r.source;return n&&(i+=rn(n)),i}l(on,"stringifyItem");const ss=Symbol("break visit"),Wa=Symbol("skip children"),tr=Symbol("remove item");function Re(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),nr(Object.freeze([]),s,e)}l(Re,"visit"),Re.BREAK=ss,Re.SKIP=Wa,Re.REMOVE=tr,Re.itemAtPath=(s,e)=>{let t=s;for(const[n,i]of e){const r=t?.[n];if(r&&"items"in r)t=r.items[i];else return}return t},Re.parentCollection=(s,e)=>{const t=Re.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],i=t?.[n];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function nr(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const i of["key","value"]){const r=e[i];if(r&&"items"in r){for(let o=0;o<r.items.length;++o){const a=nr(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ss)return ss;a===tr&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}l(nr,"_visit");const an="\uFEFF",cn="",ln="",St="",Va=l(s=>!!s&&"items"in s,"isCollection"),Ga=l(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function za(s){switch(s){case an:return"<BOM>";case cn:return"<DOC>";case ln:return"<FLOW_END>";case St:return"<SCALAR>";default:return JSON.stringify(s)}}l(za,"prettyToken");function sr(s){switch(s){case an:return"byte-order-mark";case cn:return"doc-mode";case ln:return"flow-error-end";case St:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
117
  `:case`\r
117
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}l(tr,"tokenType");var Ja=Object.freeze({__proto__:null,BOM:an,DOCUMENT:cn,FLOW_END:ln,SCALAR:St,createScalarToken:Ra,isCollection:Ba,isScalar:qa,prettyToken:Ua,resolveAsScalar:_a,setScalarValue:Ma,stringify:Ka,tokenType:tr,visit:_e});function ce(s){switch(s){case void 0:case" ":case`
118
- `:case"\r":case" ":return!0;default:return!1}}l(ce,"isEmpty");const nr=new Set("0123456789ABCDEFabcdef"),Wa=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),Va=new Set(` ,[]{}
119
- \r `),ss=l(s=>!s||Va.has(s),"isNotAnchorChar");class sr{static{l(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
118
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}l(sr,"tokenType");var Ha=Object.freeze({__proto__:null,BOM:an,DOCUMENT:cn,FLOW_END:ln,SCALAR:St,createScalarToken:qa,isCollection:Va,isScalar:Ga,prettyToken:za,resolveAsScalar:Fa,setScalarValue:Ba,stringify:Ja,tokenType:sr,visit:Re});function ce(s){switch(s){case void 0:case" ":case`
119
+ `:case"\r":case" ":return!0;default:return!1}}l(ce,"isEmpty");const ir=new Set("0123456789ABCDEFabcdef"),Ya=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),un=new Set(",[]{}"),Za=new Set(` ,[]{}
120
+ \r `),is=l(s=>!s||Za.has(s),"isNotAnchorChar");class rr{static{l(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
120
121
  `?!0:t==="\r"?this.buffer[e+1]===`
121
122
  `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){const i=this.buffer[n+e+1];if(i===`
122
123
  `||!i&&!this.atEnd)return e+n+1}return t===`
123
124
  `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ce(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
124
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===an&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const r=e[n-1];if(r===" "||r===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const r=e[t-1];if(r===" "||r===" ")t-=1;else break}const i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield cn,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&ce(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ce(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ss),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&ce(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield ln,yield*this.parseLineStart();let r=0;for(;i[r]===",";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ss),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ce(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let i=n.indexOf(`
125
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===an&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const r=e[n-1];if(r===" "||r===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const r=e[t-1];if(r===" "||r===" ")t-=1;else break}const i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield cn,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&ce(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&ce(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(is),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&i[0]!=="#"||n===0&&(i.startsWith("---")||i.startsWith("..."))&&ce(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield ln,yield*this.parseLineStart();let r=0;for(;i[r]===",";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(is),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ce(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let i=n.indexOf(`
125
126
  `,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=n.indexOf(`
126
127
  `,r)}i!==-1&&(t=i-(n[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ce(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case" ":t+=1;break;case`
127
128
  `:e=r,t=0;break;case"\r":{const o=this.buffer[r+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
@@ -131,22 +132,22 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
131
132
  `&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield St,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,n=this.pos-1,i;for(;i=this.buffer[++n];)if(i===":"){const r=this.buffer[n+1];if(ce(r)||e&&un.has(r))break;t=n}else if(ce(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
132
133
  `?(n+=1,i=`
133
134
  `,r=this.buffer[n+1]):t=n),r==="#"||e&&un.has(r))break;if(i===`
134
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&un.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield St,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(ss))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ce(t)||e&&un.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ce(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Wa.has(t))t=this.buffer[++e];else if(t==="%"&&nr.has(this.buffer[e+1])&&nr.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
135
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&un.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield St,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(is))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ce(t)||e&&un.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!ce(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Ya.has(t))t=this.buffer[++e];else if(t==="%"&&ir.has(this.buffer[e+1])&&ir.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
135
136
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
136
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class ir{static{l(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function ke(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}l(ke,"includesToken");function rr(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}l(rr,"findNonEmptyIndex");function or(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}l(or,"isFlowToken");function fn(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}l(fn,"getPrevProps");function it(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}l(it,"getFirstKeyStartProps");function ar(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!ke(e.start,"explicit-key-ind")&&!ke(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,or(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}l(ar,"fixFlowSeqItems");class is{static{l(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new sr,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}const t=tr(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{const n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&ar(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{const i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&rr(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{rr(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){const t=fn(this.peek(2)),n=it(t);let i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
137
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class or{static{l(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function ke(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}l(ke,"includesToken");function ar(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}l(ar,"findNonEmptyIndex");function cr(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}l(cr,"isFlowToken");function fn(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}l(fn,"getPrevProps");function rt(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}l(rt,"getFirstKeyStartProps");function lr(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!ke(e.start,"explicit-key-ind")&&!ke(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,cr(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}l(lr,"fixFlowSeqItems");class rs{static{l(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new rr,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}const t=sr(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const n=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:n,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{const n=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in n?n.indent:0:t.type==="flow-collection"&&n.type==="document"&&(t.indent=0),t.type==="flow-collection"&&lr(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const i=n.items[n.items.length-1];if(i.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{const i=n.items[n.items.length-1];i.value?n.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=n.items[n.items.length-1];!i||i.value?n.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((n.type==="document"||n.type==="block-map"||n.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&ar(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(n.type==="document"?n.end=i.start:n.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{ar(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){const t=fn(this.peek(2)),n=rt(t);let i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
137
138
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
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(ke(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(or(t.key)&&!ke(t.sep,"newline")){const o=it(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=it(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ke(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ke(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ke(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const i=fn(n),r=it(i);ar(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
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,i=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ke(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(cr(t.key)&&!ke(t.sep,"newline")){const o=rt(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=rt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ke(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ke(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ke(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const i=fn(n),r=rt(i);lr(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
139
140
  `)+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=fn(e),n=it(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=fn(e),n=it(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 cr(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new ir||null,prettyErrors:e}}l(cr,"parseOptions");function Ga(s,e={}){const{lineCounter:t,prettyErrors:n}=cr(e),i=new is(t?.addNewLine),r=new es(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(sn(s,t)),a.warnings.forEach(sn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Ga,"parseAllDocuments");function lr(s,e={}){const{lineCounter:t,prettyErrors:n}=cr(e),i=new is(t?.addNewLine),r=new es(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new xe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(sn(s,t)),o.warnings.forEach(sn(s,t))),o}l(lr,"parseDocument");function za(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=lr(s,t);if(!i)return null;if(i.warnings.forEach(r=>Si(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(za,"parse");function Ha(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return $e(s)&&!n?s.toString(t):new ct(s,n,t).toString(t)}l(Ha,"stringify");var Ya=Object.freeze({__proto__:null,Alias:Ft,CST:Ja,Composer:es,Document:ct,Lexer:sr,LineCounter:ir,Pair:Q,Parser:is,Scalar:P,Schema:yn,YAMLError:zn,YAMLMap:se,YAMLParseError:xe,YAMLSeq:ve,YAMLWarning:Ui,isAlias:Ce,isCollection:J,isDocument:$e,isMap:Ge,isNode:W,isPair:U,isScalar:B,isSeq:ze,parse:za,parseAllDocuments:Ga,parseDocument:lr,stringify:Ha,visit:Le,visitAsync:Kt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Za={ignored:No,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 Qa extends An{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ft(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=Hr.watch(this.membraneDir,Za),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=j.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=j.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=j.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};C.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&&(C.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=j.relative(this.membraneDir,e);let i;try{i=t?Ya.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 Gr.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=j.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=j.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var rs=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(rs||{});const Xa={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class ec extends An{static{l(this,"RemoteElementWatcher")}constructor(e=Xa){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;C.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new Yr(n),this.setupEventSourceHandlers()}catch(e){C.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{C.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){C.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{C.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Fr.ElementUpdate)return;const{elementId:t,elementType:n,data:i={}}=e;if(!(!t||!n)){if(n===R.Connector){const{filePath:r,eventType:o,newPath:a}=i;return C.info(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${r}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,r,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleConnectorFileUpdate(e,t,n,i){const r=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(r);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(r),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:i})},this.config.debounceMs);this.debounceTimeouts.set(r,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&C.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);C.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 ur{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 tc(s="full"){const e={};C.info("[connectors] Getting remote workspace data");const t=await K.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>os("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];C.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await K.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>os(n,a))),i.integrationSpecific)for(const a of t){const c=await K.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,os(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 C.success("[connectors] Remote workspace data retrieved successfully"),e}l(tc,"getWorkspaceData");function os(s,e){return e=Oo(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(os,"cleanUpForExport");const Ct="connectors",ye="development",as={};async function nc({integrations:s,allConnectors:e=!1}){const t=Do(),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 fr({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){C.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await ac({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await cc({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(nc,"pullConnectors");async function sc(){const s=await tc("minified"),t=(await K.withClient(c=>c.get("org-workspace-id"))).id,n={};C.info("[connectors] Loading custom connectors");const i=await K.withClient(c=>c.get(`/connectors?workspaceId=${t}`));C.info("[connectors] Loading public connectors"),s.connector=i;const r=Te(),a=(D.existsSync(r)?D.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=M.join(r,c);try{return D.statSync(u).isDirectory()}catch{return!1}});for(const c of a){C.info(`[connectors] Loading connector from: ${c}`);const u=D.readdirSync(M.join(r,c)),f=await cs(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,C.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await fr({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){C.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await K.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const d=u.filter(p=>D.statSync(M.join(r,c,p)).isDirectory());for(const p of d)await oc({connector:f,version:p,connectorId:n[f.id]})}return n}l(sc,"pushConnectors");function Te(){const s=$n();return M.join(s.membraneDirPath,Ct)}l(Te,"getConnectorsPath");async function cs(s){const e=M.join(Te(),s,`${s}.yml`);if(D.existsSync(e))return Ne.load(D.readFileSync(e,"utf8"))}l(cs,"readConnector");async function ic(s,e){return C.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=D.createWriteStream(e),r=Zr("zip",{zlib:{level:9}});i.on("close",()=>{C.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{C.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=D.readdirSync(s);for(const a of o){const c=M.join(s,a),u=D.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(ic,"createZipArchive");async function rc(s,e){return C.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=Xr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=M.join(e,o);D.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=M.join(e,o),u=M.dirname(c);D.mkdirSync(u,{recursive:!0});const f=D.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{C.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(rc,"extractZipArchive");async function oc({connector:s,version:e,connectorId:t}){const n=M.join(Te(),Ee(s),dr(e)),i=M.join(n,"src"),r=M.join(n,"src.zip"),o=D.existsSync(r);if(D.existsSync(i)&&(C.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await ic(i,r)),!D.existsSync(r)){C.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Qr;if(a.append("file",D.createReadStream(r),"file.zip"),C.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ye)C.info(`[connectors] Uploading connector ${t}`),await K.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){C.info(`[connectors] Version ${e} already published`);return}C.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}C.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){C.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&D.existsSync(r)&&(C.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),D.unlinkSync(r))}}l(oc,"pushConnectorVersion");async function fr({connectorId:s}){if(as[s])return as[s];const e=await K.withClient(t=>t.get(`connectors/${s}`));return as[s]=e,e}l(fr,"getConnector");async function ac({basePath:s,connector:e}){const t=Ee(e),n=M.join(s,Ct,t);D.mkdirSync(n,{recursive:!0});const i=M.join(n,`${Ee(e)}.yml`);D.writeFileSync(i,Ne.dump(e)),C.info(`[connectors] Pulled connector ${e.name}`)}l(ac,"pullConnector");async function cc({connector:s,connectorVersion:e,basePath:t}){const n=Ee(s),i=dr(e),r=M.join(t,"connectors",n,i),o=await K.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));D.mkdirSync(r,{recursive:!0});const a=M.join(r,"src.zip");if(D.writeFileSync(a,o),!e){const c=M.join(r,"src");D.mkdirSync(c,{recursive:!0}),await rc(o,c)}C.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(cc,"pullConnectorVersion");function Ee(s){return s.key}l(Ee,"getConnectorDirName");function dr(s){return s??ye}l(dr,"getConnectorVersionDirName");function lc(s){return s.match(`${Ct}/[^/]+/${ye}/src/.*`)!==null}l(lc,"isConnectorSourceFile");async function uc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await cs(t);if(!i){C.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=D.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),C.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(uc,"putConnectorFile");async function fc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await cs(t);if(!i){C.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await K.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),C.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(fc,"deleteConnectorFile");async function dc(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){C.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),i=Ee(t),r=M.join(Te(),i,ye,"src",e);D.mkdirSync(M.dirname(r),{recursive:!0}),n!=null?(D.writeFileSync(r,n),C.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):D.existsSync(r)&&(D.unlinkSync(r),C.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){C.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}l(dc,"pullConnectorFile");async function hc(s,e){const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){C.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);D.existsSync(i)&&(D.unlinkSync(i),C.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(hc,"deleteLocalConnectorFile");async function pc(s,e,t){if(t&&e!==t)try{const n=await K.withClient(c=>c.get(`connectors/${s}`));if(!n){C.warning(`[connectors] Connector ${s} not found`);return}const i=Ee(n),r=M.join(Te(),i,ye,"src"),o=M.join(r,e),a=M.join(r,t);D.existsSync(o)&&(D.mkdirSync(M.dirname(a),{recursive:!0}),D.renameSync(o,a),C.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${i}`))}catch(n){C.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}l(pc,"renameLocalConnectorDirectory");async function mc(s,e){try{const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){C.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);if(D.existsSync(i)){const r=M.resolve(Te());if(!M.resolve(i).startsWith(r))return;D.rmSync(i,{recursive:!0,force:!0}),C.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){C.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}l(mc,"deleteLocalConnectorDirectory");const hr=[R.DataSource,R.FieldMapping,R.Action,R.Flow];class Et{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new ur,this.remoteCache=new ur,this.localRepo=new Fo(this.localCache),this.remoteRepo=new Bo(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 C.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 C.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await nc({integrations:this.remoteCache.getElementsByType(R.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await sc();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 Qa({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(),C.success("[local] Tracking changes.."),this.remoteWatcher=new ec,this.remoteWatcher.on(rs.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(rs.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:i})=>this.handleRemoteConnectorFileEvent(e,t,n,i)),await this.remoteWatcher.start(),C.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(C.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return C.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){C.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,i){try{switch(n){case bn.ConnectorFileDeleted:await hc(e,t);break;case bn.ConnectorDirectoryRenamed:await pc(e,t,i);break;case bn.ConnectorDirectoryDeleted:await mc(e,t);break;default:await dc(e,t);break}}catch(r){C.error(`[sync] Error handling remote connector file event: ${r}`)}}async handleLocalEvent(e,t){try{if(lc(e.filePath))switch(t){case ie.Updated:await uc(e.filePath);break;case ie.Deleted:await fc(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(C.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${Io.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){C.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Et.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Et.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;C.info("[resolver] Resolving changes.."),C.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)),C.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);C.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}C.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);C.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}C.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case he.DELETE:return this.deleteElement(e.element,e.direction);case he.CREATE:return this.updateElement(e.element,e.direction);case he.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),d=Et.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);C.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:he.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:he.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:he.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ie=j.join(eo.tmpdir(),"membrane-mcp-status"),pr=3e4;class gc{static{l(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=dn(void 0,e),n=mr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{C.error("Failed to check MCP status")}}}function dn(s,e){try{const t=e||process.cwd();if(!s){const i=mr(t);return i.length===0?null:i[0]}const n=fs(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>pr)return vt(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>pr)return vt(s,t),null}return c}}catch{s&&e&&vt(s,e)}return null}l(dn,"getMcpStatus");function mr(s){try{const e=s||process.cwd(),t=us(e);if(!x.existsSync(Ie))return[];const n=x.readdirSync(Ie),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=dn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(mr,"getAllMcpStatusFiles");function ls(s){try{const t={...dn(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(Ie)||x.mkdirSync(Ie,{recursive:!0});const n=fs(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(ls,"updateMcpStatus");function vt(s,e){try{const t=e||process.cwd();if(s){const n=fs(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=us(t);if(x.existsSync(Ie)){const i=x.readdirSync(Ie);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(j.join(Ie,r))}}}catch{}}l(vt,"clearMcpStatus");function yc(s,e){const t=dn(s,e);t&&ls({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(yc,"trackToolExecution");function us(s){return zr("md5").update(s).digest("hex").slice(0,8)}l(us,"getCwdHash");function fs(s,e){const t=us(e);return j.join(Ie,`mcp-${t}-${s}.json`)}l(fs,"getStatusFilePath");const kt={Agent:"agent",Cli:"cli"},L={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class gr{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 gc,this.syncService=new Et,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){C.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){C.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async syncWorkspaces(e={}){try{await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}catch(t){C.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),e?.onComplete?.()}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),ut.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){C.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=ut.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=ut.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===kt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const yr=Ts(null);function wc({children:s,membraneCLIService:e}){const{data:t}=Is("/account"),[n,i]=q(L.NOT_INITIALIZED),[r,o]=q([]),[a,c]=q({}),[u,f]=q([]),[d,p]=q(null),w=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ae(()=>{const h=l(({state:O})=>i(O),"handleStateChanged"),y=l(({stats:O})=>c(O),"handleStatsChanged"),v=l(({log:O})=>f(N=>[...N,O]),"handleLogAdded"),k=l(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=l(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(V.StateChanged,h),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,v),e.notifier.on(V.ConflictsChanged,k),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,h),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,v),e.notifier.off(V.ConflictsChanged,k),e.notifier.off(V.ConfigChanged,A)}},[]),m(yr.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:l(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:l(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:l(h=>e.pullWorkspace(h),"pull"),push:l(h=>e.pushWorkspace(h),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(wc,"MembraneCLIServiceProvider");function le(){const s=Es(yr);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const wr=Ts(process.cwd());function bc({cwd:s,children:e}){return m(wr.Provider,{value:s,children:e})}l(bc,"CwdProvider");function Sc(){return Es(wr)}l(Sc,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(bc,{cwd:n,children:m(Rr,{value:{fetcher:Ro()},children:m(wc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const ds=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=j.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const s=j.join(process.cwd(),".cursor"),e=j.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Cc({onExit:s,onComplete:e}){const[t,n]=q(0),[i,r]=q(!1),[o,a]=q(null),[c,u]=q(""),[f,d]=q("");Me((w,h)=>{if(c||f){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?p(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(ds.length-1,t+1));else if(h.return||w===" "){const y=ds[t];a(y),r(!0)}});const p=l(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(b,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(b,{color:"green",children:"Success"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(b,{color:"green",children:c}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(b,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(b,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(b,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(b,{color:"red",children:f})}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(b,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(b,{color:"cyan",children:"Confirmation"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[E(b,{children:["Connect ",m(b,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(b,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:E(b,{children:[m(b,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(b,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(b,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(b,{color:"cyan",children:"Select Agent"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(b,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:ds.map((w,h)=>E(S,{children:[E(b,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),E(b,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(Cc,"AddMcpServerScreen");function vc(){const[s,e]=q(null),[t,n]=q([]),[i,r]=q(null);return Ae(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(vc,"useMcpStatus");function kc(){const{error:s,serverCount:e,allMcpServers:t}=vc(),n=Math.min(100,process.stdout.columns||100);return E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(b,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(b,{color:"red",children:"error reading status"}):e===0?m(b,{color:"yellow",children:"none"}):m(b,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:E(b,{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(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(S,{children:E(b,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"[a: connect an agent]"})})]})}l(kc,"Agent");const pn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function br(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(br,"truncateText");function hs({children:s}){const{state:e,logs:t}=le();return!e||e===L.NOT_INITIALIZED?E(S,{gap:1,flexDirection:"row",children:[m(no,{type:"dots"}),m(b,{children:"Initializing..."})]}):e===L.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(b,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===L.ERROR?t.slice().map((n,i)=>m(b,{color:pn(n.type),children:n.message},n.timestamp+i)):s}l(hs,"EnsureInitialized");function Sr({onExit:s,showEscOption:e=!0}){const[t,n]=q(""),{data:i,error:r,isLoading:o}=Is("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(Me((h,y)=>{y.escape&&s?.()}),u)return E(S,{children:[m(At,{}),m(b,{children:" Fetching workspaces..."})]});if(r)return E(S,{flexDirection:"column",children:[E(b,{color:"red",children:["Error: ",r.message]}),m(S,{marginTop:1,children:m(b,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,g=c?.length??0;async function w(h){const y=f.find(A=>A.id===h);if(!y)return;const{key:v,secret:k}=y;!v||!k||(await a({workspaceKey:v,workspaceSecret:k}),s?.())}return l(w,"handleSelect"),E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(b,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(S,{marginTop:1,children:[m(b,{children:"Search: "}),m(so,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(b,{children:["Showing ",p," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(io,{options:d,onChange:l(h=>{h&&w(h)},"onChange")})}),e&&m(S,{marginTop:1,children:m(b,{color:"grey",children:"Press ESC to go back"})})]})}l(Sr,"SelectWorkspace");function Tc({currentPat:s,onSubmit:e}){const[t,n]=q(""),[i,r]=q(!1),[o,a]=q(null);return E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(b,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(b,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(b,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(b,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(ro,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(S,{marginTop:1,children:E(b,{children:[m(At,{type:"dots"})," Validating token..."]})}),o&&m(b,{color:"red",children:o})]})}l(Tc,"PersonalAccessTokenInput");var Tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Tt||{});const Ec={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},ps=[Tt.Authenticate,Tt.ConnectWorkspace];function Cr({onComplete:s}){const{config:e}=le(),[t,n]=q(!1),[i,r]=q(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ni(),c=ps[i],u=i+1,f=ps.length,d=ps.map((w,h)=>{let y="pending";return h<i?y="done":h===i&&(y="current"),{id:w,label:Ec[w],status:y}});async function p(w){const h=a&&w===""?a:w,y=new si;try{await y.request("/account",{headers:{Authorization:`Bearer ${h}`}}),_o(h),r(v=>v+1)}catch(v){console.error(v)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),Me((w,h)=>{o&&h.escape&&s&&s()}),t?m(S,{children:m(b,{children:"\u2705 Setup complete. You are ready to go!"})}):E(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:E(b,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(b,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(b,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Ic,{status:w.status,label:w.label},w.id))})]}),c===Tt.Authenticate&&m(Tc,{currentPat:a,onSubmit:p}),c===Tt.ConnectWorkspace&&m(Sr,{onExit:g,showEscOption:!1})]})}l(Cr,"Setup");function Ic({status:s,label:e}){return E(S,{children:[E(S,{width:2,children:[s==="current"&&m(At,{type:"dots"}),s==="done"&&m(b,{children:"\u2705"})]}),m(b,{dimColor:s!=="current",children:e})]})}l(Ic,"StepDisplay");function ms(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(b,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(S,{children:[m(S,{width:20,children:E(b,{children:[t,":"]})}),m(b,{color:"green",children:n})]},t))})]})}l(ms,"ElementStats");const gs=5,Oc=6;function Ac(){const{logs:s}=le(),[e,t]=q(0),n=Math.min(100,process.stdout.columns||100),i=gs,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-Oc,u=e<s.length-i,f=e>0;return Me((d,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(S,{flexDirection:"column",paddingTop:1,children:[E(b,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>gs&&m(b,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>m(S,{marginLeft:1,children:m(b,{color:pn(d.type),children:br(d.message,c)})},d.timestamp+p)),s.length>gs&&E(S,{marginLeft:1,flexDirection:"row",children:[u&&m(b,{color:"grey",children:"\u2191 "}),f&&m(b,{color:"grey",children:"\u2193 "})]})]})}l(Ac,"Logs");const mn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Nc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=q(0),[r,o]=q(!1),[a,c]=q(!1);return Me((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(d=>d>0?d-1:mn.length-1):f.downArrow?i(d=>d<mn.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),mn[n].value==="sync"?e({watch:!0}):t())}}),Ae(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),E(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(b,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(b,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(ys,{isExpanded:a})}),E(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(b,{color:"white",bold:!0,children:"What would you like to do?"}),m(b,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:r?E(S,{flexDirection:"row",gap:1,children:[m(At,{type:"dots"}),m(b,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:mn.map((u,f)=>m(S,{flexDirection:"column",children:E(S,{flexDirection:"row",gap:1,children:[m(b,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(b,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(Nc,"ResolveChangesUI");const $c={[he.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[he.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[he.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ys({isExpanded:s}){const{conflicts:e}=le(),t=5,n=Mr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(S,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=$c[o][a];return E(S,{flexDirection:"column",children:[E(S,{flexDirection:"row",gap:1,children:[E(b,{color:"yellow",children:[c.label," (",r.length,")"]}),m(b,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(S,{marginLeft:2,children:E(b,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(S,{marginLeft:2,children:E(b,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(S,{marginLeft:2,children:m(b,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ys,"Conflicts");function Lc(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?br(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ae(()=>{i({watch:!0})},[]),E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:E(S,{flexDirection:"row",gap:1,children:[m(b,{bold:!0,children:"\u{1F504} Workspace"}),E(b,{color:Dc(e),children:[" [",Pc(e),"] "]})]})}),E(S,{children:[m(S,{width:12,children:m(b,{color:"grey",children:"Local:"})}),m(b,{color:"grey",children:process.cwd()})]}),E(S,{children:[m(S,{width:12,children:m(b,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(b,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(b,{children:[m(b,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(Nc,{}):E(wn,{children:[m(S,{paddingTop:1,children:m(ms,{})}),t.length>0&&m(Ac,{})]})]})}l(Lc,"Workspace");function Pc(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}l(Pc,"getStatusDisplay");function Dc(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}l(Dc,"getStatusColor");const xc="https://console.integration.app/w";function _c(){const s=Sc(),e=jr(!0),{exit:t,state:n}=le(),[i,r]=q(null),o=i??(n===L.SETTING_UP?"setup":"main");Me(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===L.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ii(s),u=`${xc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";to(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ae(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Sr,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Cc,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(Cr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(hs,{children:E(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(kc,{})}),m(Lc,{}),m(S,{paddingLeft:2,children:m(b,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(_c,"Main");const vr=_r(process.argv.slice(2)),kr=vr.cwd?Lr(vr.cwd):process.cwd(),Rc=new gr(kt.Agent,kr),Mc=l(()=>m(hn,{cwd:kr,membraneCLIService:Rc,children:m(_c,{})}),"App");function jc(){It(m(Mc,{}))}l(jc,"runAgent");function Kc(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?ut.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(Cr,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Kc,"setupInitCommand");async function Tr(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),kn.sign(n,e)}l(Tr,"generateAdminAccessToken");async function Fc(s,e){return(await Tn.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(Fc,"fetchOpenApiSchema");function Er(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(Er,"convertOpenApiSchemaToZod");function Ir(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(Ir,"extractPathParameters");function Bc(s,e,t,n,i,r,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,c=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},f={},d={};if(s.parameters){for(const g of s.parameters)if(g.in==="path")f[g.name]=Er(g.schema,!0).describe(g.description||`Path parameter: ${g.name}`);else if(g.in==="query"){const w=g.required===!0;d[g.name]=Er(g.schema,w).describe(g.description||`Query parameter: ${g.name}`)}}Object.keys(f).length>0&&(u.params=Z.object(f).describe("Path parameters")),Object.keys(d).length>0&&(u.query=Z.object(d).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=Z.any().describe("Request body"));const p=Object.keys(u).length>0?Z.object(u):Z.object({});return{name:a,description:c,parameters:p,async execute(g){try{const w=Ir(e);if(w.length>0){if(!g.params)throw new Error(`Missing required path parameters: ${w.join(", ")}`);const N=w.filter($=>!($ in g.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let h=`${n}${e}`;if(g.params)for(const[N,$]of Object.entries(g.params)){const F=`{${N}}`;h.includes(F)&&(h=h.replace(F,String($)))}const y=Ir(h);if(y.length>0)throw new Error(`Unresolved path parameters: ${y.join(", ")}`);const v=new URLSearchParams;if(g.query)for(const[N,$]of Object.entries(g.query))$!=null&&v.append(N,String($));v.toString()&&(h+=`?${v.toString()}`);const k=await Tr(i,r,o),A={method:t.toUpperCase(),headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"}};g.body&&t.toLowerCase()!=="get"&&(A.data=g.body);const O=await Tn.request({url:h,...A});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(w){return Tn.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(Bc,"createApiTool");function qc(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=Bc(u,o,c,e,t,n,i);r.push(f)}}return r}l(qc,"convertOpenApiToTools");function Uc(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=jt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||Nn,n=await Tr(e.workspaceKey,e.workspaceSecret,e.testCustomerId),i=await Fc(t,n),r=qc(i,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new co({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
141
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=fn(e),n=rt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=fn(e),n=rt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function ur(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new or||null,prettyErrors:e}}l(ur,"parseOptions");function Qa(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(sn(s,t)),a.warnings.forEach(sn(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Qa,"parseAllDocuments");function fr(s,e={}){const{lineCounter:t,prettyErrors:n}=ur(e),i=new rs(t?.addNewLine),r=new ts(e);let o=null;for(const a of r.compose(i.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new xe(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(sn(s,t)),o.warnings.forEach(sn(s,t))),o}l(fr,"parseDocument");function Xa(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=fr(s,t);if(!i)return null;if(i.warnings.forEach(r=>vi(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}l(Xa,"parse");function ec(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(s===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return $e(s)&&!n?s.toString(t):new lt(s,n,t).toString(t)}l(ec,"stringify");var tc=Object.freeze({__proto__:null,Alias:Ft,CST:Ha,Composer:ts,Document:lt,Lexer:rr,LineCounter:or,Pair:Q,Parser:rs,Scalar:D,Schema:yn,YAMLError:Hn,YAMLMap:se,YAMLParseError:xe,YAMLSeq:ve,YAMLWarning:Wi,isAlias:Ce,isCollection:J,isDocument:$e,isMap:ze,isNode:W,isPair:U,isScalar:q,isSeq:He,parse:Xa,parseAllDocuments:Qa,parseDocument:fr,stringify:ec,visit:Le,visitAsync:Kt});const ie={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},nc={ignored:Po,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class sc extends Nn{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Ve(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(x.existsSync(this.membraneDir)||x.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Xr.watch(this.membraneDir,nc),this.watcher.on("add",e=>this.handleFileSystemEvent(ie.Updated,e)).on("change",e=>this.handleFileSystemEvent(ie.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(ie.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(ie.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=j.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=j.resolve(e);return this.ignoredPaths.has(t)}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=j.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===ie.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return x.readFileSync(e,"utf8")}processFileEvent(e,t){const n=j.relative(this.membraneDir,e);let i;try{i=t?tc.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Zr.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){x.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=x.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=j.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=x.readFileSync(i,"utf8"),o=j.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}var os=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(os||{});const ic={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:5};class rc extends Nn{static{l(this,"RemoteElementWatcher")}constructor(e=ic){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;isStarted=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.clearReconnectTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{const e=await K.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.info("[remote-watcher] Subscribing to workspace events"),this.eventSource=new eo(n),this.setupEventSourceHandlers()}catch(e){b.error(`[remote-watcher] Failed to subscribe to workspace events: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.info("[remote-watcher] Connected to workspace events"),this.reconnectAttempts=0,this.emit("connected",{})},this.eventSource.onmessage=e=>{try{const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.error(`[remote-watcher] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.error(`[remote-watcher] Workspace events connection error: ${e}`),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==Br.ElementUpdate)return;const{elementId:t,elementType:n,data:i={}}=e;if(!(!t||!n)){if(n===_.Connector){const{filePath:r,eventType:o,newPath:a}=i;return b.info(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${r}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,r,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const i=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,i)}scheduleConnectorFileUpdate(e,t,n,i){const r=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(r);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(r),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:i})},this.config.debounceMs);this.debounceTimeouts.set(r,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&b.error("[remote-watcher] Max reconnect attempts reached, giving up");return}this.reconnectAttempts++;const e=Math.min(this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),3e4);b.info(`[remote-watcher] Reconnecting in ${e}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},e)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class dr{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const i=this.typeIndex.get(e.type);i&&(i.delete(t),i.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}async function oc(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await K.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>as("integration",n));for(const n of Object.keys(ne)){const i=ne[n];if(i.exportable===!1)continue;const r=[];b.info(`[connectors] Reading ${i.elements} from remote workspace`);const o=await K.withClient(a=>a[i.elements].findAll());if(r.push(...o.map(a=>as(n,a))),i.integrationSpecific)for(const a of t){const c=await K.withClient(u=>u[i.elements].findAll({integrationId:a.id}));r.push(...c.map(u=>(u.integrationKey=a.key,as(n,u))))}r.length>0&&s=="full"&&(console.table(r.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,c)=>(a||(a={}),a[c.key]||(a[c.key]={}),c.universal&&(a[c.key].universal=!0),c.integrationKey&&(a[c.key].integration?a[c.key].integration+=` ${c.integrationKey}`:a[c.key].integration=c.integrationKey),a),{})),console.groupEnd()),e[n]=r}return b.success("[connectors] Remote workspace data retrieved successfully"),e}l(oc,"getWorkspaceData");function as(s,e){return e=Lo(e),ne[s].exportCleanup?ne[s].exportCleanup(e):e}l(as,"cleanUpForExport");const Ct="connectors",ye="development",cs={};async function ac({integrations:s,allConnectors:e=!1}){const t=Mo(),n=new Set,i={};for(const r of s){const o=r.connectorId,a=r.connectorVersion;if(o&&!i[o]?.has(r.connectorVersion)){const c=await hr({connectorId:o}),f=!!c.workspaceId||e;if(!c?.key){b.error(`[connectors] Connector ${o} has no key. Skipping..`);continue}f&&(n.has(o)||(await dc({basePath:t,connector:c}),n.add(o)),i[o]||(i[o]=new Set),i[o].has(a)||(await hc({connector:c,connectorVersion:a,basePath:t}),i[o].add(a)))}}}l(ac,"pullConnectors");async function cc(){const s=await oc("minified"),t=(await K.withClient(c=>c.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const i=await K.withClient(c=>c.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=i;const r=Te(),a=(P.existsSync(r)?P.readdirSync(r):[]).filter(c=>{if(c.startsWith("."))return!1;const u=M.join(r,c);try{return P.statSync(u).isDirectory()}catch{return!1}});for(const c of a){b.info(`[connectors] Loading connector from: ${c}`);const u=P.readdirSync(M.join(r,c)),f=await ls(c);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const g=await hr({connectorId:f.id});g&&!g.workspaceId&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const g=await K.withClient(w=>w.post("connectors",{...f,workspaceId:t}));n[f.id]=g.id}}const d=u.filter(p=>P.statSync(M.join(r,c,p)).isDirectory());for(const p of d)await fc({connector:f,version:p,connectorId:n[f.id]})}return n}l(cc,"pushConnectors");function Te(){const s=Ln();return M.join(s.membraneDirPath,Ct)}l(Te,"getConnectorsPath");async function ls(s){const e=M.join(Te(),s,`${s}.yml`);if(P.existsSync(e))return Ne.load(P.readFileSync(e,"utf8"))}l(ls,"readConnector");async function lc(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=P.createWriteStream(e),r=to("zip",{zlib:{level:9}});i.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{b.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=P.readdirSync(s);for(const a of o){const c=M.join(s,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(lc,"createZipArchive");async function uc(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=so.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=M.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=M.join(e,o),u=M.dirname(c);P.mkdirSync(u,{recursive:!0});const f=P.createWriteStream(c);r.pipe(f),f.on("finish",()=>{})}}),i.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(uc,"extractZipArchive");async function fc({connector:s,version:e,connectorId:t}){const n=M.join(Te(),Ee(s),pr(e)),i=M.join(n,"src"),r=M.join(n,"src.zip"),o=P.existsSync(r);if(P.existsSync(i)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await lc(i,r)),!P.existsSync(r)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new no;if(a.append("file",P.createReadStream(r),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ye)b.info(`[connectors] Uploading connector ${t}`),await K.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await K.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await K.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&P.existsSync(r)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),P.unlinkSync(r))}}l(fc,"pushConnectorVersion");async function hr({connectorId:s}){if(cs[s])return cs[s];const e=await K.withClient(t=>t.get(`connectors/${s}`));return cs[s]=e,e}l(hr,"getConnector");async function dc({basePath:s,connector:e}){const t=Ee(e),n=M.join(s,Ct,t);P.mkdirSync(n,{recursive:!0});const i=M.join(n,`${Ee(e)}.yml`);P.writeFileSync(i,Ne.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}l(dc,"pullConnector");async function hc({connector:s,connectorVersion:e,basePath:t}){const n=Ee(s),i=pr(e),r=M.join(t,"connectors",n,i),o=await K.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));P.mkdirSync(r,{recursive:!0});const a=M.join(r,"src.zip");if(P.writeFileSync(a,o),!e){const c=M.join(r,"src");P.mkdirSync(c,{recursive:!0}),await uc(o,c)}b.info(`[connectors] Pulled connector version: ${s.name} (${i})`)}l(hc,"pullConnectorVersion");function Ee(s){return s.key}l(Ee,"getConnectorDirName");function pr(s){return s??ye}l(pr,"getConnectorVersionDirName");function pc(s){return s.match(`${Ct}/[^/]+/${ye}/src/.*`)!==null}l(pc,"isConnectorSourceFile");async function mc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=P.readFileSync(s,"utf-8");await K.withClient(a=>a.put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}l(mc,"putConnectorFile");async function gc(s){const e=s.match(`${Ct}/([^/]+)/${ye}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await ls(t);if(!i){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await K.withClient(o=>o.delete(`connectors/${r}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}l(gc,"deleteConnectorFile");async function yc(s,e){try{const t=await K.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await K.withClient(o=>o.get(`connectors/${s}/files/${e}`)),i=Ee(t),r=M.join(Te(),i,ye,"src",e);P.mkdirSync(M.dirname(r),{recursive:!0}),n!=null?(P.writeFileSync(r,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):P.existsSync(r)&&(P.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}l(yc,"pullConnectorFile");async function wc(s,e){const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);P.existsSync(i)&&(P.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(wc,"deleteLocalConnectorFile");async function bc(s,e,t){if(t&&e!==t)try{const n=await K.withClient(c=>c.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const i=Ee(n),r=M.join(Te(),i,ye,"src"),o=M.join(r,e),a=M.join(r,t);P.existsSync(o)&&(P.mkdirSync(M.dirname(a),{recursive:!0}),P.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${i}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}l(bc,"renameLocalConnectorDirectory");async function Sc(s,e){try{const t=await K.withClient(r=>r.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Ee(t),i=M.join(Te(),n,ye,"src",e);if(P.existsSync(i)){const r=M.resolve(Te());if(!M.resolve(i).startsWith(r))return;P.rmSync(i,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}l(Sc,"deleteLocalConnectorDirectory");const mr=[_.DataSource,_.FieldMapping,_.Action,_.Flow];class Et{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;constructor(){this.notifier=pe,this.localCache=new dr,this.remoteCache=new dr,this.localRepo=new Wo(this.localCache),this.remoteRepo=new Vo(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{const r=await n.putElement(e);i.put(r)}catch(r){throw b.error(`Failed to update element ${e.id}: ${r}`),r}}async deleteElement(e,t){const n=this.getHandler(t),i=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),i.remove(e)}catch(r){throw b.error(`Failed to delete element ${e.id}: ${r}`),r}}async pullConnectors(e=!1){await ac({integrations:this.remoteCache.getElementsByType(_.Integration).map(t=>t.data),allConnectors:e})}async pushConnectors(){const e=await cc();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ee.INCOMING?this.localRepo:this.remoteRepo}getCache(e){return e===ee.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new sc({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(ie.Updated,e=>this.handleLocalEvent(e,ie.Updated)),this.localWatcher.on(ie.Deleted,e=>this.handleLocalEvent(e,ie.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new rc,this.remoteWatcher.on(os.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(os.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:i})=>this.handleRemoteConnectorFileEvent(e,t,n,i)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),i=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||i){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ee.INCOMING))):void 0}return b.info(`[${this.getDirectionLabel(ee.INCOMING)}] Updated: ${n.id}`),this.localWatcher?.executeWithPathLock(n.absolutePath,()=>this.updateElement(n,ee.INCOMING))}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,i){try{switch(n){case Sn.ConnectorFileDeleted:await wc(e,t);break;case Sn.ConnectorDirectoryRenamed:await bc(e,t,i);break;case Sn.ConnectorDirectoryDeleted:await Sc(e,t);break;default:await yc(e,t);break}}catch(r){b.error(`[sync] Error handling remote connector file event: ${r}`)}}async handleLocalEvent(e,t){try{if(pc(e.filePath))switch(t){case ie.Updated:await mc(e.filePath);break;case ie.Deleted:await gc(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const i=z.idFromPath(e.filePath);if(!i||(n=this.remoteCache.get(i),!n))return}switch(b.info(`[${this.getDirectionLabel(ee.OUTGOING)}] ${$o.toSentenceCase(t)}: ${n.id}`),t){case ie.Updated:await this.updateElement(n,ee.OUTGOING);break;case ie.Deleted:await this.deleteElement(n,ee.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Et.getChanges(ee.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Et.getChanges(ee.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(i=>i.element.type===_.Integration);await Promise.all(e.map(async i=>this.resolveChange(i))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===ee.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(i=>i.element.type!==_.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(i=>!i.element.hasParent());for(const i of mr){const r=t.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(i=>i.element.hasParent());for(const i of mr){const r=n.filter(o=>o.element.type===i);b.info(`[resolver] Resolving ${i} elements`),await Promise.all(r.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case he.DELETE:return this.deleteElement(e.element,e.direction);case he.CREATE:return this.updateElement(e.element,e.direction);case he.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),d=Et.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ee.INCOMING:return"local\u2190remote";case ee.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:he.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:he.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:he.UPDATE,element:e,direction:n,isConflict:!0}:null}}const Ie=j.join(io.tmpdir(),"membrane-mcp-status"),gr=3e4;class Cc{static{l(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=dn(void 0,e),n=yr(e);t&&pe.setMcpStatus(t),await pe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function dn(s,e){try{const t=e||process.cwd();if(!s){const i=yr(t);return i.length===0?null:i[0]}const n=ds(s,t);if(x.existsSync(n)){const i=x.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>gr)return vt(s,t),null;const a=x.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>gr)return vt(s,t),null}return c}}catch{s&&e&&vt(s,e)}return null}l(dn,"getMcpStatus");function yr(s){try{const e=s||process.cwd(),t=fs(e);if(!x.existsSync(Ie))return[];const n=x.readdirSync(Ie),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=dn(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yr,"getAllMcpStatusFiles");function us(s){try{const t={...dn(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};x.existsSync(Ie)||x.mkdirSync(Ie,{recursive:!0});const n=ds(s.processId,s.cwd);x.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(us,"updateMcpStatus");function vt(s,e){try{const t=e||process.cwd();if(s){const n=ds(s,t);x.existsSync(n)&&x.unlinkSync(n)}else{const n=fs(t);if(x.existsSync(Ie)){const i=x.readdirSync(Ie);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&x.unlinkSync(j.join(Ie,r))}}}catch{}}l(vt,"clearMcpStatus");function vc(s,e){const t=dn(s,e);t&&us({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(vc,"trackToolExecution");function fs(s){return Qr("md5").update(s).digest("hex").slice(0,8)}l(fs,"getCwdHash");function ds(s,e){const t=fs(e);return j.join(Ie,`mcp-${t}-${s}.json`)}l(ds,"getStatusFilePath");const kt={Agent:"agent",Cli:"cli"},L={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class wr{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=pe,this.mcpStatusService=new Cc,this.syncService=new Et,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(L.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(L.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(L.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(L.SYNCED),e.watch&&(await this.notifier.setState(L.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(L.NOT_INITIALIZED);try{await this.loadConfig(),ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(L.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(L.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(L.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=ft.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const i=ft.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===kt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===kt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const br=Es(null);function kc({children:s,membraneCLIService:e}){const{data:t}=Os("/account"),[n,i]=B(L.NOT_INITIALIZED),[r,o]=B([]),[a,c]=B({}),[u,f]=B([]),[d,p]=B(null),w=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ae(()=>{const h=l(({state:O})=>i(O),"handleStateChanged"),y=l(({stats:O})=>c(O),"handleStatsChanged"),v=l(({log:O})=>f(N=>[...N,O]),"handleLogAdded"),k=l(({conflicts:O})=>o(O),"handleConflictsUpdated"),A=l(({config:O})=>p(O),"handleConfigChanged");return e.notifier.on(V.StateChanged,h),e.notifier.on(V.StatsChanged,y),e.notifier.on(V.LogAdded,v),e.notifier.on(V.ConflictsChanged,k),e.notifier.on(V.ConfigChanged,A),e.init(),()=>{e.notifier.off(V.StateChanged,h),e.notifier.off(V.StatsChanged,y),e.notifier.off(V.LogAdded,v),e.notifier.off(V.ConflictsChanged,k),e.notifier.off(V.ConfigChanged,A)}},[]),m(br.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:l(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:l(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:l(h=>e.pullWorkspace(h),"pull"),push:l(h=>e.pushWorkspace(h),"push"),exit:l(()=>e.shutdown(),"exit")},children:s})}l(kc,"MembraneCLIServiceProvider");function le(){const s=Is(br);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(le,"useMembraneCLIService");const Sr=Es(process.cwd());function Tc({cwd:s,children:e}){return m(Sr.Provider,{value:s,children:e})}l(Tc,"CwdProvider");function Ec(){return Is(Sr)}l(Ec,"useCwd");function hn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Tc,{cwd:n,children:m(Mr,{value:{fetcher:Fo()},children:m(kc,{membraneCLIService:t,children:e})})})}l(hn,"Layout");const hs=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=j.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(x.existsSync(s))try{t=JSON.parse(x.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return x.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const s=j.join(process.cwd(),".cursor"),e=j.join(s,"mcp.json");x.existsSync(s)||x.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(x.existsSync(e))try{n=JSON.parse(x.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return x.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Ic({onExit:s,onComplete:e}){const[t,n]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[f,d]=B("");Me((w,h)=>{if(c||f){(h.escape||w==="q"||h.return)&&e();return}if(i)h.return||w===" "?p(o):h.escape&&(r(!1),a(null));else if(h.escape)s();else if(h.upArrow||w==="k")n(Math.max(0,t-1));else if(h.downArrow||w==="j")n(Math.min(hs.length-1,t+1));else if(h.return||w===" "){const y=hs[t];a(y),r(!0)}});const p=l(w=>{try{const h=w.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"green",children:"Success"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"green",children:c}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(C,{color:"red",children:f})}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Confirmation"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",m(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(C,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:E(C,{children:[m(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Select Agent"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:hs.map((w,h)=>E(S,{children:[E(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",w.name]}),E(C,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(Ic,"AddMcpServerScreen");function Oc(){const[s,e]=B(null),[t,n]=B([]),[i,r]=B(null);return Ae(()=>{const o=l(({status:c})=>{e(c),r(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),r(null)},"handleMcpServersChanged");return pe.on(V.McpStatusChanged,o),pe.on(V.McpServersChanged,a),()=>{pe.off(V.McpStatusChanged,o),pe.off(V.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(Oc,"useMcpStatus");function Ac(){const{error:s,serverCount:e,allMcpServers:t}=Oc(),n=Math.min(100,process.stdout.columns||100);return E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(C,{color:"red",children:"error reading status"}):e===0?m(C,{color:"yellow",children:"none"}):m(C,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",m(Rr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(S,{children:E(C,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(Ac,"Agent");const pn=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Cr(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(Cr,"truncateText");function ps({children:s}){const{state:e,logs:t}=le();return!e||e===L.NOT_INITIALIZED?E(S,{gap:1,flexDirection:"row",children:[m(oo,{type:"dots"}),m(C,{children:"Initializing..."})]}):e===L.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===L.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,i)=>m(C,{color:pn(n.type),children:n.message},n.timestamp+i))}):s}l(ps,"EnsureInitialized");function vr({onExit:s,showEscOption:e=!0}){const[t,n]=B(""),{data:i,error:r,isLoading:o}=Os("/account"),{updateConfig:a}=le(),c=i?.workspaces,u=o;if(Me((h,y)=>{y.escape&&s?.()}),u)return E(S,{children:[m(At,{}),m(C,{children:" Fetching workspaces..."})]});if(r)return E(S,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",r.message]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,g=c?.length??0;async function w(h){const y=f.find(A=>A.id===h);if(!y)return;const{key:v,secret:k}=y;!v||!k||(await a({workspaceKey:v,workspaceSecret:k}),s?.())}return l(w,"handleSelect"),E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(S,{marginTop:1,children:[m(C,{children:"Search: "}),m(ao,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(C,{children:["Showing ",p," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(co,{options:d,onChange:l(h=>{h&&w(h)},"onChange")})}),e&&m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]})}l(vr,"SelectWorkspace");function Nc({currentPat:s,onSubmit:e}){const[t,n]=B(""),[i,r]=B(!1),[o,a]=B(null);return E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(C,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(lo,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(S,{marginTop:1,children:E(C,{children:[m(At,{type:"dots"})," Validating token..."]})}),o&&m(C,{color:"red",children:o})]})}l(Nc,"PersonalAccessTokenInput");var Tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Tt||{});const $c={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},ms=[Tt.Authenticate,Tt.ConnectWorkspace];function kr({onComplete:s}){const{config:e}=le(),[t,n]=B(!1),[i,r]=B(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=si(),c=ms[i],u=i+1,f=ms.length,d=ms.map((w,h)=>{let y="pending";return h<i?y="done":h===i&&(y="current"),{id:w,label:$c[w],status:y}});async function p(w){const h=a&&w===""?a:w,y=new ii;try{await y.request("/account",{headers:{Authorization:`Bearer ${h}`}}),Ko(h),r(v=>v+1)}catch(v){console.error(v)}}l(p,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),Me((w,h)=>{o&&h.escape&&s&&s()}),t?m(S,{children:m(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(C,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Lc,{status:w.status,label:w.label},w.id))})]}),c===Tt.Authenticate&&m(Nc,{currentPat:a,onSubmit:p}),c===Tt.ConnectWorkspace&&m(vr,{onExit:g,showEscOption:!1})]})}l(kr,"Setup");function Lc({status:s,label:e}){return E(S,{children:[E(S,{width:2,children:[s==="current"&&m(At,{type:"dots"}),s==="done"&&m(C,{children:"\u2705"})]}),m(C,{dimColor:s!=="current",children:e})]})}l(Lc,"StepDisplay");function gs(){const{stats:s}=le(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(C,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(S,{children:[m(S,{width:20,children:E(C,{children:[t,":"]})}),m(C,{color:"green",children:n})]},t))})]})}l(gs,"ElementStats");const ys=5,Dc=6;function Pc(){const{logs:s}=le(),[e,t]=B(0),n=Math.min(100,process.stdout.columns||100),i=ys,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-Dc,u=e<s.length-i,f=e>0;return Me((d,p)=>{if(s.length!==0)if(p.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else p.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(S,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>ys&&m(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>m(S,{marginLeft:1,children:m(C,{color:pn(d.type),children:Cr(d.message,c)})},d.timestamp+p)),s.length>ys&&E(S,{marginLeft:1,flexDirection:"row",children:[u&&m(C,{color:"grey",children:"\u2191 "}),f&&m(C,{color:"grey",children:"\u2193 "})]})]})}l(Pc,"Logs");const mn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function xc(){const{state:s,resolveConflicts:e,exit:t}=le(),[n,i]=B(0),[r,o]=B(!1),[a,c]=B(!1);return Me((u,f)=>{if(!r){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?i(d=>d>0?d-1:mn.length-1):f.downArrow?i(d=>d<mn.length-1?d+1:0):u.toLowerCase()==="y"?i(0):u.toLowerCase()==="n"?i(1):(f.return||u===" ")&&(o(!0),mn[n].value==="sync"?e({watch:!0}):t())}}),Ae(()=>{s!==L.CONFLICTS&&r&&o(!1)},[s,r]),E(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(ws,{isExpanded:a})}),E(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(C,{color:"white",bold:!0,children:"What would you like to do?"}),m(C,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:r?E(S,{flexDirection:"row",gap:1,children:[m(At,{type:"dots"}),m(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:mn.map((u,f)=>m(S,{flexDirection:"column",children:E(S,{flexDirection:"row",gap:1,children:[m(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(xc,"ResolveChangesUI");const Rc={[he.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[he.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[he.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ws({isExpanded:s}){const{conflicts:e}=le(),t=5,n=jr(()=>{const i={};return e.forEach(r=>{const o=`${r.type}-${r.direction}`;i[o]||(i[o]=[]),i[o].push(r)}),i},[e]);return m(S,{flexDirection:"column",children:Object.entries(n).map(([i,r])=>{if(r.length===0)return null;const[o,a]=i.split("-"),c=Rc[o][a];return E(S,{flexDirection:"column",children:[E(S,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[c.label," (",r.length,")"]}),m(C,{color:"white",children:c.description})]}),(s?r:r.slice(0,t)).map(u=>m(S,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",u.element.id," (",u.element.relativePath,")"]})},u.element.id)),!s&&r.length>t&&m(S,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",r.length-t," more (press Ctrl+R to show all)"]})}),s&&r.length>t&&m(S,{marginLeft:2,children:m(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ws,"Conflicts");function _c(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=le(),r=n?.name,o=r?Cr(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ae(()=>{i({watch:!0})},[]),E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:E(S,{flexDirection:"row",gap:1,children:[m(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:jc(e),children:[" [",Mc(e),"] "]})]})}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Local:"})}),m(C,{color:"grey",children:process.cwd()})]}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[m(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===L.CONFLICTS?m(xc,{}):E(wn,{children:[m(S,{paddingTop:1,children:m(gs,{})}),t.length>0&&m(Pc,{})]})]})}l(_c,"Workspace");function Mc(s){switch(s){case L.PULLING:return"pulling";case L.PUSHING:return"pushing";case L.CONFLICTS:return"conflicts";case L.SYNCED:return"synced";case L.ERROR:return"error";case L.WATCHING:return"tracking changes";case L.RESOLVING:return"resolving";case L.NOT_SYNCED:return"not synced";case L.INITIALIZED:return"initialized";case L.SETTING_UP:return"setup required";default:return"unknown"}}l(Mc,"getStatusDisplay");function jc(s){switch(s){case L.PULLING:return"yellow";case L.PUSHING:return"yellow";case L.CONFLICTS:return"red";case L.SYNCED:return"green";case L.ERROR:return"red";case L.WATCHING:return"green";case L.RESOLVING:return"yellow";case L.NOT_SYNCED:return"grey";case L.SETTING_UP:return"yellow";default:return"grey"}}l(jc,"getStatusColor");const Kc="https://console.integration.app/w";function Fc(){const s=Ec(),e=Kr(!0),{exit:t,state:n}=le(),[i,r]=B(null),o=i??(n===L.SETTING_UP?"setup":"main");Me(c=>{o==="main"&&(c==="w"&&r("workspace-selection"),c==="a"&&r("add-mcp-server"),c==="o"&&n===L.INITIALIZED&&a(),c==="s"&&r("setup"))});async function a(){try{const c=await ri(s),u=`${Kc}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ro(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),Ae(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(vr,{onExit:l(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Ic,{onExit:l(()=>r(null),"onExit"),onComplete:l(()=>r(null),"onComplete")}):o==="setup"?m(kr,{onComplete:l(()=>r(null),"onComplete")},Date.now()):m(ps,{children:E(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Ac,{})}),m(_c,{}),m(S,{paddingLeft:2,children:m(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(Fc,"Main");const Tr=_r(process.argv.slice(2)),Er=Tr.cwd?Pr(Tr.cwd):process.cwd(),qc=new wr(kt.Agent,Er),Bc=l(()=>m(hn,{cwd:Er,membraneCLIService:qc,children:m(Fc,{})}),"App");function Uc(){It(m(Bc,{}))}l(Uc,"runAgent");function Jc(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
142
+ `)).action(t=>{t.key&&t.secret?ft.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(kr,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Jc,"setupInitCommand");async function Ir(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Tn.sign(n,e)}l(Ir,"generateAdminAccessToken");async function Wc(s,e){return(await En.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(Wc,"fetchOpenApiSchema");function Or(s,e=!0){if(!s)return e?Z.string():Z.string().optional();let t;switch(s.type){case"integer":t=Z.coerce.number().int();break;case"number":t=Z.coerce.number();break;case"boolean":t=Z.coerce.boolean();break;case"string":default:t=Z.string();break}return s.format==="uuid"?t=Z.string().uuid():s.format==="email"?t=Z.string().email():s.format==="date"?t=Z.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=Z.string().datetime()),s.enum&&(t=Z.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}l(Or,"convertOpenApiSchemaToZod");function Ar(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(Ar,"extractPathParameters");function Vc(s,e,t,n,i,r,o){const a=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,c=s.description||s.summary||`${t.toUpperCase()} ${e}`,u={},f={},d={};if(s.parameters){for(const g of s.parameters)if(g.in==="path")f[g.name]=Or(g.schema,!0).describe(g.description||`Path parameter: ${g.name}`);else if(g.in==="query"){const w=g.required===!0;d[g.name]=Or(g.schema,w).describe(g.description||`Query parameter: ${g.name}`)}}Object.keys(f).length>0&&(u.params=Z.object(f).describe("Path parameters")),Object.keys(d).length>0&&(u.query=Z.object(d).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(u.body=Z.any().describe("Request body"));const p=Object.keys(u).length>0?Z.object(u):Z.object({});return{name:a,description:c,parameters:p,async execute(g){try{const w=Ar(e);if(w.length>0){if(!g.params)throw new Error(`Missing required path parameters: ${w.join(", ")}`);const N=w.filter($=>!($ in g.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let h=`${n}${e}`;if(g.params)for(const[N,$]of Object.entries(g.params)){const F=`{${N}}`;h.includes(F)&&(h=h.replace(F,String($)))}const y=Ar(h);if(y.length>0)throw new Error(`Unresolved path parameters: ${y.join(", ")}`);const v=new URLSearchParams;if(g.query)for(const[N,$]of Object.entries(g.query))$!=null&&v.append(N,String($));v.toString()&&(h+=`?${v.toString()}`);const k=await Ir(i,r,o),A={method:t.toUpperCase(),headers:{Authorization:`Bearer ${k}`,"Content-Type":"application/json"}};g.body&&t.toLowerCase()!=="get"&&(A.data=g.body);const O=await En.request({url:h,...A});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(w){return En.isAxiosError(w)?{content:[{type:"text",text:`Error: ${w.response?.data?`HTTP ${w.response.status}: ${w.response.statusText} - ${JSON.stringify(w.response.data)}`:`HTTP ${w.response?.status||"unknown"}: ${w.message}`}`}],isError:!0}:w instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${w.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(Vc,"createApiTool");function Gc(s,e,t,n,i){const r=[];if(!s.paths)return r;for(const[o,a]of Object.entries(s.paths))if(typeof a=="object"&&a!==null){for(const[c,u]of Object.entries(a))if(["get","post","put","delete","patch"].includes(c)&&u&&typeof u=="object"){const f=Vc(u,o,c,e,t,n,i);r.push(f)}}return r}l(Gc,"convertOpenApiToTools");function zc(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
143
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=jt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||$n,n=await Ir(e.workspaceKey,e.workspaceSecret,e.testCustomerId),i=await Wc(t,n),r=Gc(i,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new ho({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
143
144
  Use it for anything related to Membrane or integrations.
144
- `,version:"1.0.0"});for(const u of r){const f=u.execute;u.execute=async d=>(yc(process.pid,process.cwd()),f(d)),o.addTool(u)}ls({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(()=>{ls({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),vt(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",()=>{vt(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(Uc,"setupMcpCommand");const Jc={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Wc={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class G{static{l(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${T.gray(new Date().toISOString())} `:"",r=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=Jc[t],c=Wc[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
145
+ `,version:"1.0.0"});for(const u of r){const f=u.execute;u.execute=async d=>(vc(process.pid,process.cwd()),f(d)),o.addTool(u)}us({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(()=>{us({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),vt(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",()=>{vt(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(zc,"setupMcpCommand");const Hc={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Yc={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class G{static{l(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${T.gray(new Date().toISOString())} `:"",r=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=Hc[t],c=Yc[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
145
146
  ${T.red(t.error)}`:""):console.debug(T.gray(e),t?.error?`
146
- ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),i=e.map(r=>{const o={};return n.forEach(a=>{o[a]=r[a]}),o});console.table(i,n)}static divider(){}}function Vc(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
147
- `)).action(async()=>{try{G.header("Opening Workspace in Browser"),G.info("Loading configuration...");const e=jt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");G.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await ii(process.cwd())}`;G.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),G.success("Browser opened successfully")}catch(e){e instanceof Error&&(G.error(e.message),process.exit(1)),G.error("An unknown error occurred"),process.exit(1)}})}l(Vc,"setupOpenCommand");function Gc(s){return m(hs,{children:m(zc,{options:s})})}l(Gc,"Pull");function zc({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=le();Ae(()=>{i(s)},[]);const r=t===L.CONFLICTS;return E(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(b,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&E(wn,{children:[E(b,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(ys,{isExpanded:!1}),m(b,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(ms,{})]})}l(zc,"PullActivity");function Or(){const s=setInterval(()=>{},3e4),e=l(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}l(Or,"getWatchModeCallback");function Hc(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
148
- `)).action(async t=>{const n=t.watch?Or():()=>process.exit(0);It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(Gc,{force:t.force,watch:t.watch,allConnectors:t.allConnectors,onComplete:n})}))})}l(Hc,"setupPullCommand");function Yc(s){return m(hs,{children:m(Zc,{options:s})})}l(Yc,"Push");function Zc({options:s}){const{logs:e,state:t,conflicts:n,push:i}=le();Ae(()=>{i(s)},[]);const r=t===L.CONFLICTS;return E(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(b,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&E(wn,{children:[E(b,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(ys,{isExpanded:!1}),m(b,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(ms,{})]})}l(Zc,"PushActivity");function Qc(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
149
- `)).action(async t=>{const n=t.watch?Or():()=>process.exit(0);It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(Yc,{force:t.force,watch:t.watch,onComplete:n})}))})}l(Qc,"setupPushCommand");class Xc{static{l(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=$n(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const el="claude-sonnet-4-20250514";class vs{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=jt();if(!i)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new Os({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new lo({apiKey:i.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const f=await o.messages.create({model:el,max_tokens:u,messages:[{role:"user",content:c}]});return f.content[0].type==="text"?f.content[0].text:""},"complete")};return new vs({client:r,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),En(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=M.join(this.testsDir,this.testBasePath,this.connectionId,e);if(D.existsSync(t))return Ne.load(D.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=M.join(this.testsDir,this.testBasePath,this.connectionId,e);D.mkdirSync(M.dirname(n),{recursive:!0}),D.writeFileSync(n,Ne.dump(t,{noRefs:!0}))}writeResults(e){const t=M.join(this.testsDir,this.testBasePath,this.connectionId);D.mkdirSync(t,{recursive:!0});const n=M.join(t,"test-results.yaml");D.writeFileSync(n,Ne.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return kn.sign(n,e.workspaceSecret,i)}}fo.interpolate=/{{([\s\S]+?)}}/g;function ws(s,e){if(typeof s=="string"){const t=uo(s),n={state:e,random:{number:l(()=>lt.number.int(),"number"),alphaNumeric:l(r=>lt.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:l(()=>lt.company.name(),"name"),catchPhrase:l(()=>lt.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>lt.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(s)?s.map(t=>ws(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,ws(n,e)])):s}l(ws,"processNode");function tl(s,e){return ws(s,e)}l(tl,"handleTemplate");class nl{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${T.bold.cyan("[start]")} ${T.yellow(e.path)}`);let t=!1,n=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=tl(r,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,i=e.getResult(),Sn(this.result,e.path,i)}catch(c){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${c}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(c);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}Sn(this.result,e.path,{error:ue(c)}),t=!0,i={error:ue(c)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),En(this.result,e.getResult())}}class Oe{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(T.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(i){this.assertions.push({message:t,result:!1,details:ue(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function bs(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!Ss(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=bs(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Ss(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}l(bs,"getNotMatchingSubFields");function Ss(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}l(Ss,"softCompare");class sl extends Oe{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=Cn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=As(n),a=Ot(e.input.fields,o,{skipUnknownFields:!0}),c=Ot(r.record.fields,o),u=bs(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const i=Br(n);if(i.length>0){const r={};i.forEach(a=>{const c=qr(e.input.fields,a);typeof c<"u"&&Sn(r,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Cn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=Cn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
147
+ ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),i=e.map(r=>{const o={};return n.forEach(a=>{o[a]=r[a]}),o});console.table(i,n)}static divider(){}}function Zc(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
148
+ `)).action(async()=>{try{G.header("Opening Workspace in Browser"),G.info("Loading configuration...");const e=jt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");G.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await ri(process.cwd())}`;G.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),G.success("Browser opened successfully")}catch(e){e instanceof Error&&(G.error(e.message),process.exit(1)),G.error("An unknown error occurred"),process.exit(1)}})}l(Zc,"setupOpenCommand");function Qc(s){return m(ps,{children:m(Xc,{options:s})})}l(Qc,"Pull");function Xc({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=le();Ae(()=>{i(s)},[]);const r=t===L.CONFLICTS;return E(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(C,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&E(wn,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(ws,{isExpanded:!1}),m(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(gs,{})]})}l(Xc,"PullActivity");function Nr(){const s=setInterval(()=>{},3e4),e=l(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}l(Nr,"getWatchModeCallback");function el(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically",""].join(`
149
+ `)).action(async t=>{const n=t.watch?Nr():()=>process.exit(0);It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(Qc,{...t,onComplete:n})}))})}l(el,"setupPullCommand");function tl(s){return m(ps,{children:m(nl,{options:s})})}l(tl,"Push");function nl({options:s}){const{logs:e,state:t,conflicts:n,push:i}=le();Ae(()=>{i(s)},[]);const r=t===L.CONFLICTS;return E(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(C,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&E(wn,{children:[E(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(ws,{isExpanded:!1}),m(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===L.SYNCED&&m(gs,{})]})}l(nl,"PushActivity");function sl(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data",""].join(`
150
+ `)).action(async t=>{const n=t.watch?Nr():()=>process.exit(0);It(je.createElement(hn,{membraneCLIService:e,children:je.createElement(tl,{...t,onComplete:n})}))})}l(sl,"setupPushCommand");class il{static{l(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=Ln(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const rl="claude-sonnet-4-20250514";class ks{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=jt();if(!i)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new As({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new po({apiKey:i.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const f=await o.messages.create({model:rl,max_tokens:u,messages:[{role:"user",content:c}]});return f.content[0].type==="text"?f.content[0].text:""},"complete")};return new ks({client:r,options:n,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const n of e)await n.run(),In(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=M.join(this.testsDir,this.testBasePath,this.connectionId,e);if(P.existsSync(t))return Ne.load(P.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=M.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync(M.dirname(n),{recursive:!0}),P.writeFileSync(n,Ne.dump(t,{noRefs:!0}))}writeResults(e){const t=M.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const n=M.join(t,"test-results.yaml");P.writeFileSync(n,Ne.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${n}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",n={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Tn.sign(n,e.workspaceSecret,i)}}go.interpolate=/{{([\s\S]+?)}}/g;function bs(s,e){if(typeof s=="string"){const t=mo(s),n={state:e,random:{number:l(()=>ut.number.int(),"number"),alphaNumeric:l(r=>ut.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:l(()=>ut.company.name(),"name"),catchPhrase:l(()=>ut.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>ut.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(s)?s.map(t=>bs(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,bs(n,e)])):s}l(bs,"processNode");function ol(s,e){return bs(s,e)}l(ol,"handleTemplate");class al{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${T.bold.cyan("[start]")} ${T.yellow(e.path)}`);let t=!1,n=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=ol(r,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,i=e.getResult(),Cn(this.result,e.path,i)}catch(c){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${c}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(c);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}Cn(this.result,e.path,{error:ue(c)}),t=!0,i={error:ue(c)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),In(this.result,e.getResult())}}class Oe{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(T.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(i){this.assertions.push({message:t,result:!1,details:ue(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Ss(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!Cs(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=Ss(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Cs(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}l(Ss,"getNotMatchingSubFields");function Cs(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}l(Cs,"softCompare");class cl extends Oe{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=vn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=Ns(n),a=Ot(e.input.fields,o,{skipUnknownFields:!0}),c=Ot(r.record.fields,o),u=Ss(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const i=Ur(n);if(i.length>0){const r={};i.forEach(a=>{const c=Jr(e.input.fields,a);typeof c<"u"&&Cn(r,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=vn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=vn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
150
151
 
151
152
  ${JSON.stringify(i,null,2)}
152
153
 
@@ -186,7 +187,7 @@ ${JSON.stringify(i,null,2)}`).join(`
186
187
 
187
188
  `)}.
188
189
 
189
- 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 Ns(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=$s(i);n[r]=await this.fetchExampleRecords(i)}return n}}class il extends Oe{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to delete a record from a data collection.
190
+ 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 $s(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=Ls(i);n[r]=await this.fetchExampleRecords(i)}return n}}class ll extends Oe{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to delete a record from a data collection.
190
191
 
191
192
  I tried to delete a record with this ID:
192
193
 
@@ -206,7 +207,7 @@ Format your response as a JSON object with two fields:
206
207
  "id": "fixed id"
207
208
  }.
208
209
 
209
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class rl extends Oe{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to find a record by ID in a data collection.
210
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class ul extends Oe{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to find a record by ID in a data collection.
210
211
 
211
212
  I tried to find a record with this ID:
212
213
 
@@ -226,7 +227,7 @@ Format your response as a JSON object with two fields:
226
227
  "id": "fixed id"
227
228
  }.
228
229
 
229
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class ol extends Oe{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[n],c=r[o].fields[n];a==null||c==null||(i==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to list records from a data collection.
230
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class fl extends Oe{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[n],c=r[o].fields[n];a==null||c==null||(i==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to list records from a data collection.
230
231
 
231
232
  I tried to list records with these parameters:
232
233
 
@@ -246,7 +247,7 @@ Format your response as a JSON object with two fields:
246
247
  "input": { ... fixed parameters ... }
247
248
  }.
248
249
 
249
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class al extends Oe{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const c=r.fields[o];await this.assert(()=>Ss(c,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to match a record in a data collection.
250
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class dl extends Oe{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const c=r.fields[o];await this.assert(()=>Cs(c,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=`I'm trying to match a record in a data collection.
250
251
 
251
252
  I tried to match a record with this query:
252
253
 
@@ -266,7 +267,7 @@ Format your response as a JSON object with two fields:
266
267
  "query": { ... fixed query ... }
267
268
  }.
268
269
 
269
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class cl extends Oe{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(i=>i.id===e.expectedRecordId);n||console.debug(T.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields);if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
270
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class hl extends Oe{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(i=>i.id===e.expectedRecordId);n||console.debug(T.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields);if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
270
271
 
271
272
  Record fields:
272
273
  ${JSON.stringify(e,null,2)}
@@ -291,7 +292,7 @@ Format your response as a JSON object with two fields:
291
292
  "input": { ... fixed parameters ... }
292
293
  }.
293
294
 
294
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class ll extends Oe{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class ul extends Oe{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=vn(this.dataCollection),o=As(r),a=Ot(e.input.fields,o,{skipUnknownFields:!0}),c=Ot(i.record.fields,o),u=bs(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=vn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=vn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
295
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class pl extends Oe{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class ml extends Oe{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=kn(this.dataCollection),o=Ns(r),a=Ot(e.input.fields,o,{skipUnknownFields:!0}),c=Ot(i.record.fields,o),u=Ss(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=kn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=ue(t),i=kn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
295
296
 
296
297
  ${JSON.stringify(i,null,2)}
297
298
 
@@ -331,9 +332,9 @@ ${JSON.stringify(i,null,2)}`).join(`
331
332
 
332
333
  `)}.
333
334
 
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 Ns(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=$s(i);n[r]=await this.fetchExampleRecords(i)}return n}}const Cs={spec:{testerClass:ll},create:{testerClass:sl,operationKey:"create"},"find-by-id":{testerClass:rl,operationKey:"findById"},list:{testerClass:ol,operationKey:"list"},match:{testerClass:al,operationKey:"match"},search:{testerClass:cl,operationKey:"search"},update:{testerClass:ul,operationKey:"update"},delete:{testerClass:il,operationKey:"delete"}};class fl extends nl{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=Cs[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(Cs).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(Cs).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 dl extends Xc{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("/"),d=await vs.create({connectionId:c,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${c}/data`),w=[],h=f?f.split("/"):[];if(h.length===0||h[0]==="data"){h[0]==="data"&&h.shift();let v,k;h.length>=1&&(k=h[0],h.length>=2&&h[1].trim()!==""&&(v=h[1]));for(const A of g){if(k&&k!==A.key)continue;const O=new fl({environment:d,dataCollectionKey:A.key,testMethod:v});w.push(O)}}w.length===0&&(G.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const v of w){await v.run();const k=v.getResult();G.debug(`Suite ${v.constructor.name} result:`,{prefix:"TestRunner"}),En(y,k)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const gn=l(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
335
- `),"createExperimentalWarning");function hl(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",gn()).action(async()=>{console.warn(gn()),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",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",gn()].join(`
336
- `)).action(async(t,n)=>{try{console.warn(gn()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new dl({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(hl,"setupTestCommand");const pl=l(()=>{try{const s=oo(import.meta.url),e=Pr(s),t=Dr(e,"..","package.json");return JSON.parse(Jr(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Ar=pl();function ml(){const s=new ao().name("membrane").description("Command-line interface for Membrane Agent").version(Ar,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:l(t=>T.cyan(t.name()),"subcommandTerm"),commandUsage:l(t=>t.name()==="membrane"?`${T.cyan(t.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:l(t=>{const n=t.flags;return`${T.gray("\u25B8")} ${T.cyan(n)}`},"optionTerm"),subcommandDescription:l(t=>T.gray(t.description()),"subcommandDescription"),optionDescription:l(t=>T.gray(t.description),"optionDescription"),commandDescription:l(t=>T.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
- ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${Ar}`)}
335
+ 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 $s(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=Ls(i);n[r]=await this.fetchExampleRecords(i)}return n}}const vs={spec:{testerClass:pl},create:{testerClass:cl,operationKey:"create"},"find-by-id":{testerClass:ul,operationKey:"findById"},list:{testerClass:fl,operationKey:"list"},match:{testerClass:dl,operationKey:"match"},search:{testerClass:hl,operationKey:"search"},update:{testerClass:ml,operationKey:"update"},delete:{testerClass:ll,operationKey:"delete"}};class gl extends al{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=vs[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(vs).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(vs).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 yl extends il{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("/"),d=await ks.create({connectionId:c,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${c}/data`),w=[],h=f?f.split("/"):[];if(h.length===0||h[0]==="data"){h[0]==="data"&&h.shift();let v,k;h.length>=1&&(k=h[0],h.length>=2&&h[1].trim()!==""&&(v=h[1]));for(const A of g){if(k&&k!==A.key)continue;const O=new gl({environment:d,dataCollectionKey:A.key,testMethod:v});w.push(O)}}w.length===0&&(G.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const v of w){await v.run();const k=v.getResult();G.debug(`Suite ${v.constructor.name} result:`,{prefix:"TestRunner"}),In(y,k)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const gn=l(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
336
+ `),"createExperimentalWarning");function wl(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",gn()).action(async()=>{console.warn(gn()),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",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",gn()].join(`
337
+ `)).action(async(t,n)=>{try{console.warn(gn()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new yl({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(wl,"setupTestCommand");const bl=l(()=>{try{const s=uo(import.meta.url),e=xr(s),t=bn(e,"..","package.json");return JSON.parse(zr(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),$r=bl();function Sl(){const s=new fo().name("membrane").description("Command-line interface for Membrane Agent").version($r,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:l(t=>T.cyan(t.name()),"subcommandTerm"),commandUsage:l(t=>t.name()==="membrane"?`${T.cyan(t.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:l(t=>{const n=t.flags;return`${T.gray("\u25B8")} ${T.cyan(n)}`},"optionTerm"),subcommandDescription:l(t=>T.gray(t.description()),"subcommandDescription"),optionDescription:l(t=>T.gray(t.description),"optionDescription"),commandDescription:l(t=>T.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
338
+ ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${$r}`)}
338
339
 
339
- `);const e=new gr(kt.Cli,process.cwd());Hc(s,e),Qc(s,e),Kc(s,e),Vc(s),hl(s),Uc(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}l(ml,"runCLI");const Nr=["--cwd"];function gl(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Nr.includes(s[t-1])?!1:!Nr.includes(e))}l(gl,"hasCLIArguments"),gl()?ml():jc();
340
+ `);const e=new wr(kt.Cli,process.cwd());el(s,e),sl(s,e),Jc(s,e),Zc(s),wl(s),zc(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}l(Sl,"runCLI");const Lr=["--cwd"];function Cl(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Lr.includes(s[t-1])?!1:!Lr.includes(e))}l(Cl,"hasCLIArguments"),Cl()?Sl():Uc();