@membranehq/cli 0.9.3 → 0.9.4

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 +112 -112
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,152 +1,152 @@
1
1
  #!/usr/bin/env node
2
- var Vi=Object.defineProperty;var c=(s,e)=>Vi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as I,Fragment as Xt}from"react/jsx-runtime";import*as D from"node:path";import{resolve as Hi,dirname as Yi,join as zi}from"node:path";import{Box as b,Text as S,useInput as De,Newline as Qi,render as gt}from"ink";import Xi from"minimist";import{SWRConfig as Zi}from"swr";import Me,{createContext as Zt,useContext as en,useState as j,useEffect as ye,useCallback as rs,useMemo as er,useRef as tr}from"react";import os from"swr/immutable";import{z as B}from"zod";import*as P from"node:fs";import{readFileSync as nr}from"node:fs";import de from"js-yaml";import as from"os";import U from"path";import sr from"conf";import{exec as ir}from"node:child_process";import{EventEmitter as rr}from"events";import{IntegrationAppClient as cs,WorkspaceElementType as _,extractIntegrationAppErrorData as te,WorkspaceElementSpecs as we,setValueAtLocator as tn,getDataCollectionCreateFields as nn,excludeWriteOnlyFieldsFromSchema as ls,valueToSchema as yt,getRequiredFieldsFromSchema as or,getValueAtLocator as ar,walkSchema as us,makeDataLocationPath as fs,getDataCollectionUpdateFields as sn}from"@membranehq/sdk";import rn from"jsonwebtoken";import{TextInput as cr,Select as lr}from"@inkjs/ui";import wt from"ink-spinner";import ur from"ink-text-input";import*as fr from"node:crypto";import{createHash as hr}from"node:crypto";import*as dr from"node:os";import M from"fs";import pr from"archiver";import mr from"form-data";import gr from"unzipper";import yr from"lodash/isEqual.js";import wr from"chokidar";import{fileURLToPath as br}from"node:url";import k from"chalk";import{Command as Sr}from"commander";import on from"axios";import{FastMCP as Cr}from"fastmcp";import an from"lodash/merge.js";import kr from"@anthropic-ai/sdk";import{faker as Ze}from"@faker-js/faker";import vr from"lodash/template.js";import Er from"lodash/templateSettings.js";const hs=Zt(process.cwd());function Ir({cwd:s,children:e}){return m(hs.Provider,{value:s,children:e})}c(Ir,"CwdProvider");function ds(){return en(hs)}c(ds,"useCwd");const ps="membrane.config.yml",ms=B.object({workspaceKey:B.string().optional(),workspaceSecret:B.string().optional(),apiUri:B.string().optional(),testCustomerId:B.string().optional(),anthropicApiKey:B.string().optional()});class Ye{static{c(this,"ConfigLoader")}static instance=null;cachedConfig=null;lastCwd=null;constructor(){}static getInstance(){return Ye.instance||(Ye.instance=new Ye),Ye.instance}loadConfig(e){const t=e??process.cwd();if(this.cachedConfig&&this.lastCwd===t)return this.cachedConfig;const n=this.loadFromFile(t),i=this.loadFromEnv(),r={...n,...i},o=ms.safeParse(r);return o.success?(this.cachedConfig=o.data,this.lastCwd=t,o.data):null}clearCache(){this.cachedConfig=null,this.lastCwd=null}loadFromFile(e){const t=D.join(e,ps);try{const n=P.readFileSync(t,"utf8"),i=de.load(n),r=ms.safeParse(i);return r.success?r.data:{}}catch{return{}}}loadFromEnv(){const e={};return process.env.MEMBRANE_WORKSPACE_KEY&&(e.workspaceKey=process.env.MEMBRANE_WORKSPACE_KEY),process.env.MEMBRANE_WORKSPACE_SECRET&&(e.workspaceSecret=process.env.MEMBRANE_WORKSPACE_SECRET),process.env.MEMBRANE_API_URI&&(e.apiUri=process.env.MEMBRANE_API_URI),e}saveToFile(e,t){const n=t??process.cwd(),i=D.join(n,ps),o={...this.loadFromFile(n),...e},a=this.loadFromEnv();for(const l of Object.keys(a))a[l]===o[l]&&delete o[l];try{return P.writeFileSync(i,de.dump(o)),this.clearCache(),!0}catch{return!1}}}const cn=Ye.getInstance();function Te(s){return cn.loadConfig(s)}c(Te,"readProjectConfig"),B.enum(["pull"]);const gs=Zt(void 0);function Tr({children:s}){const e=ds(),[t,n]=j(null),[i,r]=j(!0);ye(()=>{const u=Te(e);n(u),r(!1)},[e]);const o=rs(u=>{({...Te(e)??{},...u});const h=cn.saveToFile(u,e);if(h){const f=Te(e);n(f)}return h},[e]),a=rs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),l={config:t,isLoading:i,updateConfig:o,validateConfig:a};return m(gs.Provider,{value:l,children:s})}c(Tr,"ProjectConfigProvider");function et(){const s=en(gs);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}c(et,"useProjectConfig");const Y={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged"},x={INIT:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},ys=Zt(null);function Nr({children:s,membraneCLIService:e}){const{config:t}=et(),{data:n}=os("/account"),[i,r]=j(x.NOT_SYNCED),[o,a]=j([]),[l,u]=j({}),[p,h]=j([]),g=n?.workspaces?.find(y=>y.key===t?.workspaceKey)||null,w=t?.workspaceKey&&t?.workspaceSecret,d=e.initialized&&w;return ye(()=>{const y=c(({state:E})=>r(E),"handleStateChanged"),C=c(({stats:E})=>u(E),"handleStatsChanged"),v=c(({log:E})=>h(O=>[...O,E]),"handleLogAdded"),A=c(({conflicts:E})=>a(E),"handleConflictsUpdated");return e.notifications.on(Y.StateChanged,y),e.notifications.on(Y.StatsChanged,C),e.notifications.on(Y.LogAdded,v),e.notifications.on(Y.ConflictsChanged,A),()=>{e.notifications.off(Y.StateChanged,y),e.notifications.off(Y.StatsChanged,C),e.notifications.off(Y.LogAdded,v),e.notifications.off(Y.ConflictsChanged,A)}},[]),w?d?m(ys.Provider,{value:{state:i,stats:l,logs:p,currentWorkspace:g,conflicts:o,resolveConflicts:c(y=>e.syncWorkspaces(y),"resolveConflicts"),pull:c(y=>e.pullWorkspace(y),"pull"),push:c(y=>e.pushWorkspace(y),"push"),exit:c(()=>e.shutdown(),"exit")},children:s}):m(b,{children:m(S,{children:"Initializing..."})}):m(b,{children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})})}c(Nr,"WorkspaceServiceProvider");function be(){const s=en(ys);if(!s)throw new Error("useWorkspaceService must be used within WorkspaceServiceProvider");return s}c(be,"useWorkspaceService");const Ar="membrane",Or="membrane.config.yml",ln="https://api.integration.app";function un(){const s=process.cwd(),e=D.join(s,Ar),t=D.join(s,Or),n=e,i=D.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(un,"getPaths");function $r(){return un().membraneDirPath}c($r,"getBasePath");const Lr={pat:{type:"string"},workspace:{type:"object"}},ws=new sr({schema:Lr,configName:"config",cwd:U.join(as.homedir(),".membrane")}),Pr=c(s=>{ws.set("pat",s)},"setPat"),bs=c(()=>ws.get("pat"),"getPat");class Ss{static{c(this,"AccountApiClient")}constructor(e=ln){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=bs();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 xr=c(s=>{const e=new Ss(ln);return t=>e.get(t)},"createAccountApiFetcher");function bt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ir,{cwd:n,children:m(Tr,{children:m(Zi,{value:{fetcher:xr()},children:m(Nr,{membraneCLIService:t,children:e})})})})}c(bt,"Layout");const fn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=D.join(process.cwd(),".cursor"),e=D.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Dr({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,h]=j("");De((w,d)=>{if(l||p){(d.escape||w==="q"||d.return)&&e();return}if(i)d.return||w===" "?f(o):d.escape&&(r(!1),a(null));else if(d.escape)s();else if(d.upArrow||w==="k")n(Math.max(0,t-1));else if(d.downArrow||w==="j")n(Math.min(fn.length-1,t+1));else if(d.return||w===" "){const y=fn[t];a(y),r(!0)}});const f=c(w=>{try{const d=w.addConfig();u(d)}catch(d){h(`Failed to write configuration: ${d.message||d}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[I(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:I(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),I(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:fn.map((w,d)=>I(b,{children:[I(S,{color:t===d?"cyan":"white",children:[t===d?"\u25B6 ":" ",w.name]}),I(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Dr,"AddMcpServerScreen");class Cs extends rr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class Mr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return rn.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=Te(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 cs({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: 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}getCurrentConfigInfo(){return this.currentConfig}}const ce=new Mr;async function ks(s){const e=await ce.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(ks,"getWorkspaceId");class Rr extends Cs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Y.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Y.ConflictsChanged,{conflicts:e})}setStats(e){this.emit(Y.StatsChanged,{stats:e})}addLog(e){this.emit(Y.LogAdded,{log:e})}setMcpStatus(e){this.emit(Y.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Y.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await ce.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){const t=await(await ce.getClient(process.cwd())).post("/local-clients",{hostname:as.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await ce.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await ce.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const le=new Rr({heartbeatIntervalMs:15e3});function Kr(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return ye(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return le.on(Y.McpStatusChanged,o),le.on(Y.McpServersChanged,a),()=>{le.off(Y.McpStatusChanged,o),le.off(Y.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}}c(Kr,"useMcpStatus");function _r(){const{error:s,serverCount:e,allMcpServers:t}=Kr(),n=Math.min(100,process.stdout.columns||100);return I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:I(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Qi,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:I(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(_r,"Agent");function vs({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=os("/account"),{updateConfig:a,isLoading:l}=et(),u=i?.workspaces,p=o||l;if(De((y,C)=>{C.escape&&s?.()}),p)return I(b,{children:[m(wt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return I(b,{flexDirection:"column",children:[I(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const h=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],f=h.map(y=>({label:y.name,value:y.id})),g=f.length,w=u?.length??0;async function d(y){const C=h.find(E=>E.id===y);if(!C)return;const{key:v,secret:A}=C;!v||!A||(await a({workspaceKey:v,workspaceSecret:A}),s?.())}return c(d,"handleSelect"),I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),I(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(cr,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&I(S,{children:["Showing ",g," of ",w," workspaces."]}),m(b,{marginTop:1,children:m(lr,{options:f,onChange:c(y=>{y&&d(y)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(vs,"SelectWorkspace");function jr({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(null);return I(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(ur,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:I(S,{children:[m(wt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(jr,"PersonalAccessTokenInput");var tt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(tt||{});const Fr={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Es=c(()=>{const{config:s}=et(),e=!!(s?.workspaceKey&&s?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),hn=[tt.Authenticate,tt.ConnectWorkspace];function Is({onComplete:s}){const[e,t]=j(!1),[n,i]=j(0),{isSetupComplete:r}=Es(),o=bs(),a=hn[n],l=n+1,u=hn.length,p=hn.map((g,w)=>{let d="pending";return w<n?d="done":w===n&&(d="current"),{id:g,label:Fr[g],status:d}});async function h(g){const w=o&&g===""?o:g,d=new Ss;try{await d.request("/account",{headers:{Authorization:`Bearer ${w}`}}),Pr(w),i(y=>y+1)}catch(y){console.error(y)}}c(h,"handlePatSubmit");function f(){t(!0),s&&s()}return c(f,"handleWorkspaceSelected"),De((g,w)=>{r&&w.escape&&s&&s()}),e?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):I(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:I(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(S,{color:"cyan",children:["Step ",l," of ",u]}),r&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:p.map(g=>m(Br,{status:g.status,label:g.label},g.id))})]}),a===tt.Authenticate&&m(jr,{currentPat:o,onSubmit:h}),a===tt.ConnectWorkspace&&m(vs,{onExit:f,showEscOption:!1})]})}c(Is,"Setup");function Br({status:s,label:e}){return I(b,{children:[I(b,{width:2,children:[s==="current"&&m(wt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Br,"StepDisplay");function dn(){const{stats:s}=be(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:I(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>I(b,{children:[m(b,{width:20,children:I(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(dn,"ElementStats");const pn=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ts(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ts,"truncateText");const mn=5,Ur=6;function qr(){const{logs:s}=be(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=mn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-Ur,u=e<s.length-i,p=e>0;return De((h,f)=>{if(s.length!==0)if(f.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else f.downArrow?t(g=>Math.max(0,g-1)):(h==="G"||h==="g")&&t(0)}),I(b,{flexDirection:"column",paddingTop:1,children:[I(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>mn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((h,f)=>m(b,{marginLeft:1,children:m(S,{color:pn(h.type),children:Ts(h.message,l)})},h.timestamp+f)),s.length>mn&&I(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(qr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},ue={INCOMING:"incoming",OUTGOING:"outgoing"},St=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Wr(){const{state:s,resolveConflicts:e,exit:t}=be(),[n,i]=j(0),[r,o]=j(!1);return De((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:St.length-1):l.downArrow?i(u=>u<St.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),St[n].value==="sync"?e({watch:!0}):t()))}),ye(()=>{s!==x.CONFLICTS&&r&&o(!1)},[s,r]),I(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(gn,{})}),I(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?I(b,{flexDirection:"row",gap:1,children:[m(wt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:St.map((a,l)=>m(b,{flexDirection:"column",children:I(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(Wr,"ResolveChangesUI");const Jr={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function gn(){const{conflicts:s}=be(),e=er(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=Jr[i][r];return I(b,{flexDirection:"column",children:[I(b,{flexDirection:"row",gap:1,children:[I(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:I(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(gn,"Conflicts");function Gr(){const{config:s}=et(),{state:e,logs:t,currentWorkspace:n,pull:i}=be(),r=n?.name,o=r?Ts(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ye(()=>{i({watch:!0})},[]),I(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:I(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),I(S,{color:Hr(e),children:[" [",Vr(e),"] "]})]})}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),I(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?I(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):I(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?m(Wr,{}):I(Xt,{children:[m(b,{paddingTop:1,children:m(dn,{})}),t.length>0&&m(qr,{})]})]})}c(Gr,"Workspace");function Vr(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INIT:return"initializing";default:return"unknown"}}c(Vr,"getStatusDisplay");function Hr(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";default:return"grey"}}c(Hr,"getStatusColor");const Yr=c(()=>{const{isSetupComplete:s}=Es(),{config:e}=et();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e}},"useStatus");function zr(){const s=ds(),{isSetupComplete:e,workspaceKey:t,config:n}=Yr(),{exit:i}=be(),[r,o]=j(null),a=tr(!0),l=r??(e?"main":"setup");return De(u=>{l==="main"&&(u==="w"&&o("workspace-selection"),u==="a"&&o("add-mcp-server"),u==="o"&&t&&n?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await ks(s)}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ir(`${f} "${h}"`)}catch(p){console.error("Failed to open workspace:",p),i()}})(),u==="s"&&o("setup"))}),ye(()=>(a.current=!0,()=>{a.current=!1}),[]),l==="workspace-selection"?m(vs,{onExit:c(()=>o(null),"onExit")}):l==="add-mcp-server"?m(Dr,{onExit:c(()=>o(null),"onExit"),onComplete:c(()=>o(null),"onComplete")}):l==="setup"?m(Is,{onComplete:c(()=>o(null),"onComplete")},Date.now()):I(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(_r,{})}),m(Gr,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})}c(zr,"Main");class Qr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=le}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new Qr,Se=D.join(dr.tmpdir(),"membrane-mcp-status"),Ns=3e4;class Xr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=Ct(void 0,e),n=As(e);t&&le.setMcpStatus(t),await le.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function Ct(s,e){try{const t=e||process.cwd();if(!s){const i=As(t);return i.length===0?null:i[0]}const n=bn(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ns)return nt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>Ns)return nt(s,t),null}return l}}catch{s&&e&&nt(s,e)}return null}c(Ct,"getMcpStatus");function As(s){try{const e=s||process.cwd(),t=wn(e);if(!P.existsSync(Se))return[];const n=P.readdirSync(Se),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=Ct(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(As,"getAllMcpStatusFiles");function yn(s){try{const t={...Ct(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};P.existsSync(Se)||P.mkdirSync(Se,{recursive:!0});const n=bn(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(yn,"updateMcpStatus");function nt(s,e){try{const t=e||process.cwd();if(s){const n=bn(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=wn(t);if(P.existsSync(Se)){const i=P.readdirSync(Se);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(D.join(Se,r))}}}catch{}}c(nt,"clearMcpStatus");function Zr(s,e){const t=Ct(s,e);t&&yn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(Zr,"trackToolExecution");function wn(s){return hr("md5").update(s).digest("hex").slice(0,8)}c(wn,"getCwdHash");function bn(s,e){const t=wn(e);return D.join(Se,`mcp-${t}-${s}.json`)}c(bn,"getStatusFilePath");const se={[_.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[_.Connector]:{element:"connector",elements:"connectors",exportable:!1},[_.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(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:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[_.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function eo(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(eo,"baseExportCleanup");class Os{static{c(this,"ElementsCache")}elements=new Map;typeIndex=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)}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))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}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()}getAllIds(){return new Set(this.elements.keys())}}class $s{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new Os,this.handler=e}async refresh(){try{const e=new Os,t=await this.handler.getIntegrations();e.addAll(t);const n=[_.Integration,_.Connector],i=Object.keys(se),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function to(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>Sn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>Sn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,Sn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return T.success("[connectors] Remote workspace data retrieved successfully"),t}c(to,"getWorkspaceData");function Sn(s,e){return e=eo(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(Sn,"cleanUpForExport");const st="connectors",it="development",Cn={};async function no({integrations:s,allConnectors:e=!1}){const t=$r(),n=await ce.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Ls({client:n,connectorId:a}),h=!!u.workspaceId||e;if(!u?.key){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}h&&(i.has(a)||(await ao({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await co({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(no,"pullConnectors");async function so(){const s=await ce.getClient(process.cwd()),e=await to(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=kn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const h=U.join(a,p);try{return M.statSync(h).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const h=M.readdirSync(U.join(a,p)),f=await vn(p);if("baseUri"in f&&delete f.baseUri,f.uuid&&e.connector?.find(w=>w.uuid==f.uuid))i[f.id]=e.connector.find(w=>w.uuid==f.uuid).id,T.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!i[f.id]){let w=!1;try{const d=await Ls({client:s,connectorId:f.id});d&&!d.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const d=await r.post("connectors",{...f,workspaceId:n});i[f.id]=d.id}}const g=h.filter(w=>M.statSync(U.join(a,p,w)).isDirectory());for(const w of g)await oo({client:s,connector:f,version:w,connectorId:i[f.id]})}return i}c(so,"pushConnectors");function kn(){const s=un();return U.join(s.membraneDirPath,st)}c(kn,"getConnectorsPath");async function vn(s){return de.load(M.readFileSync(U.join(kn(),s,`${s}.yml`),"utf8"))}c(vn,"readConnector");async function io(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=pr("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const l=U.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(io,"createZipArchive");async function ro(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=gr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=U.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(ro,"extractZipArchive");async function oo({client:s,connector:e,version:t,connectorId:n}){const i=U.join(kn(),kt(e),Ps(t)),r=U.join(i,"src"),o=U.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await io(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new mr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==it)T.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(oo,"pushConnectorVersion");async function Ls({client:s,connectorId:e}){if(Cn[e])return Cn[e];const t=await s.get(`connectors/${e}`);return Cn[e]=t,t}c(Ls,"getConnector");async function ao({basePath:s,connector:e}){const t=kt(e),n=U.join(s,st,t);M.mkdirSync(n,{recursive:!0});const i=U.join(n,`${kt(e)}.yml`);M.writeFileSync(i,de.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(ao,"pullConnector");async function co({client:s,connector:e,connectorVersion:t,basePath:n}){const i=kt(e),r=Ps(t),o=U.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=U.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=U.join(o,"src");M.mkdirSync(u,{recursive:!0}),await ro(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(co,"pullConnectorVersion");function kt(s){return s.key}c(kt,"getConnectorDirName");function Ps(s){return s??it}c(Ps,"getConnectorVersionDirName");function lo(s){return s.match(`${st}/[^/]+/${it}/src/.*`)!==null}c(lo,"isConnectorSourceFile");async function uo(s){const e=s.match(`${st}/([^/]+)/${it}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await vn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await ce.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(uo,"putConnectorFile");async function fo(s){const e=s.match(`${st}/([^/]+)/${it}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await vn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await ce.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(fo,"deleteConnectorFile");const ho="membrane",po=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function vt(s){return D.join(s,ho)}c(vt,"getMembraneDir");const mo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],xs=[_.Action,_.FieldMapping,_.Flow,_.DataSource];class G{static{c(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||G.extractIntegrationKey(i)}get id(){return G.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[_.Integration].apiPath;return D.join(t,this.integrationKey,e,this.key)}return D.join(e,this.key)}get path(){return D.join(this.dirPath,"spec.yaml")}get relativePath(){return D.relative(vt(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return yr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return mo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new G(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 G(e,t.key,n,t)}static fromPathAndData(e,t){const n=G.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?G.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new G(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=G.parsePath(e);if(t)return G.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===_.Integration?`${e}:${t}`:G.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(we).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,h=this.getElementTypeFromPath(u);if(h)return{type:h,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(_).find(t=>we[t].apiPath===e)}static getRelativePath(e){return D.relative(vt(process.cwd()),e)}static isIntegrationSpecific(e){return xs.includes(e)}static canBeIntegrationSpecific(e){return xs.includes(e)}}class go{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=vt(process.cwd())}async getElementsByType(e,t){const n=[],i=D.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=D.join(this.basePath,we[_.Integration].apiPath,o.key,we[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(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=D.join(this.basePath,t.dirPath),i=D.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,de.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=D.join(this.basePath,e.path),n=D.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=D.join(this.basePath,we[_.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=de.load(t);if(n)return G.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=D.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(D.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class yo{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!G.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return G.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=G.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=G.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>G.fromData(_.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),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(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===_.Integration).map(r=>r.key).join(", ")}`)}if(e.type===_.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===_.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>G.fromData(e,r))}async getClient(){return this.client||(this.client=await ce.getClient(process.cwd())),this.client}}const En=Symbol.for("yaml.alias"),In=Symbol.for("yaml.document"),Ce=Symbol.for("yaml.map"),Ds=Symbol.for("yaml.pair"),fe=Symbol.for("yaml.scalar"),Re=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),ke=c(s=>!!s&&typeof s=="object"&&s[ie]===En,"isAlias"),Ne=c(s=>!!s&&typeof s=="object"&&s[ie]===In,"isDocument"),Ke=c(s=>!!s&&typeof s=="object"&&s[ie]===Ce,"isMap"),F=c(s=>!!s&&typeof s=="object"&&s[ie]===Ds,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[ie]===fe,"isScalar$1"),_e=c(s=>!!s&&typeof s=="object"&&s[ie]===Re,"isSeq");function q(s){if(s&&typeof s=="object")switch(s[ie]){case Ce:case Re:return!0}return!1}c(q,"isCollection$1");function W(s){if(s&&typeof s=="object")switch(s[ie]){case En:case Ce:case fe:case Re:return!0}return!1}c(W,"isNode");const Ms=c(s=>(R(s)||q(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Rs=Symbol("skip children"),he=Symbol("remove node");function Ae(s,e){const t=Ks(e);Ne(s)?je(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):je(null,s,t,Object.freeze([]))}c(Ae,"visit$1"),Ae.BREAK=ee,Ae.SKIP=Rs,Ae.REMOVE=he;function je(s,e,t,n){const i=_s(s,e,t,n);if(W(i)||F(i))return js(s,n,i),je(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=je(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===he&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=je("key",e.key,t,n);if(r===ee)return ee;r===he&&(e.key=null);const o=je("value",e.value,t,n);if(o===ee)return ee;o===he&&(e.value=null)}}return i}c(je,"visit_");async function Et(s,e){const t=Ks(e);Ne(s)?await Fe(null,s.contents,t,Object.freeze([s]))===he&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(Et,"visitAsync"),Et.BREAK=ee,Et.SKIP=Rs,Et.REMOVE=he;async function Fe(s,e,t,n){const i=await _s(s,e,t,n);if(W(i)||F(i))return js(s,n,i),Fe(s,i,t,n);if(typeof i!="symbol"){if(q(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Fe(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===he&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===ee)return ee;r===he&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===ee)return ee;o===he&&(e.value=null)}}return i}c(Fe,"visitAsync_");function Ks(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(Ks,"initVisitor");function _s(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Ke(e))return t.Map?.(s,e,n);if(_e(e))return t.Seq?.(s,e,n);if(F(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(ke(e))return t.Alias?.(s,e,n)}c(_s,"callVisitor");function js(s,e,t){const n=e[e.length-1];if(q(n))n.items[s]=t;else if(F(n))s==="key"?n.key=t:n.value=t;else if(Ne(n))n.contents=t;else{const i=ke(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(js,"replaceNode");const wo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},bo=c(s=>s.replace(/[!,[\]{}]/g,e=>wo[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.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+bo(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let i;if(e&&n.length>0&&W(e.contents)){const r={};Ae(e.contents,(o,a)=>{W(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of n)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
- `)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function Fs(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(Fs,"anchorIsValid");function Bs(s){const e=new Set;return Ae(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Bs,"anchorNames");function Us(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Us,"findNewAnchor");function So(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Bs(s));const o=Us(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(R(o.node)||q(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}}c(So,"createNodeAnchors");function Be(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=Be(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=Be(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=Be(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=Be(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(Be,"applyReviver");function re(s,e,t){if(Array.isArray(s))return s.map((n,i)=>re(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!Ms(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}c(re,"toJS");class Tn{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,ie,{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(!Ne(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=re(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?Be(r,{"":a},"",a):a}}class It extends Tn{static{c(this,"Alias")}constructor(e){super(En),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Ae(e,{Node:c((r,o)=>{(ke(o)||Ms(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 l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(re(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Tt(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(Fs(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 Tt(s,e,t){if(ke(e)){const n=e.resolve(s),i=t&&n&&t.get(n);return i?i.count*i.aliasCount:0}else if(q(e)){let n=0;for(const i of e.items){const r=Tt(s,i,t);r>n&&(n=r)}return n}else if(F(e)){const n=Tt(s,e.key,t),i=Tt(s,e.value,t);return Math.max(n,i)}return 1}c(Tt,"getAliasCount");const qs=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends Tn{static{c(this,"Scalar")}constructor(e){super(fe),this.value=e}toJSON(e,t){return t?.keep?this.value:re(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const Co="tag:yaml.org,2002:";function ko(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)}c(ko,"findTagObject");function rt(s,e,t){if(Ne(s)&&(s=s.contents),W(s))return s;if(F(s)){const h=t.schema[Ce].createNode?.(t.schema,null,t);return h.items.push(s),h}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new It(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Co+e.slice(2));let u=ko(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const h=new L(s);return l&&(l.node=h),h}u=s instanceof Map?o[Ce]:Symbol.iterator in Object(s)?o[Re]:o[Ce]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new L(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(rt,"createNode");function Nt(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 rt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(Nt,"collectionFromPath");const ot=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Ws extends Tn{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>W(n)||F(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(ot(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Nt(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(q(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&&R(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F(t))return!1;const n=t.value;return n==null||e&&R(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 q(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(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Nt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const vo=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function pe(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(pe,"indentComment");const Oe=c((s,e,t)=>s.endsWith(`
4
- `)?pe(t,e):t.includes(`
2
+ var qi=Object.defineProperty;var c=(s,e)=>qi(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as E,Fragment as en}from"react/jsx-runtime";import*as x from"node:path";import{resolve as Wi,dirname as Ji,join as Gi}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Vi,render as mt}from"ink";import Hi from"minimist";import{SWRConfig as Yi}from"swr";import xe,{createContext as ss,useState as j,useEffect as Ie,useContext as is,useMemo as zi,useRef as Qi}from"react";import rs from"swr/immutable";import os from"os";import B from"path";import Xi from"conf";import{exec as Zi}from"node:child_process";import*as P from"node:fs";import{readFileSync as er}from"node:fs";import{EventEmitter as tr}from"events";import{IntegrationAppClient as as,WorkspaceElementType as K,extractIntegrationAppErrorData as te,WorkspaceElementSpecs as we,setValueAtLocator as tn,getDataCollectionCreateFields as nn,excludeWriteOnlyFieldsFromSchema as cs,valueToSchema as gt,getRequiredFieldsFromSchema as nr,getValueAtLocator as sr,walkSchema as ls,makeDataLocationPath as us,getDataCollectionUpdateFields as sn}from"@membranehq/sdk";import rn from"jsonwebtoken";import pe from"js-yaml";import{z as W}from"zod";import{Spinner as ir,TextInput as rr,Select as or}from"@inkjs/ui";import yt from"ink-spinner";import ar from"ink-text-input";import*as cr from"node:crypto";import{createHash as lr}from"node:crypto";import*as ur from"node:os";import M from"fs";import fr from"archiver";import hr from"form-data";import dr from"unzipper";import pr from"lodash/isEqual.js";import mr from"chokidar";import{fileURLToPath as gr}from"node:url";import k from"chalk";import{Command as yr}from"commander";import on from"axios";import{FastMCP as wr}from"fastmcp";import an from"lodash/merge.js";import br from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import Sr from"lodash/template.js";import Cr from"lodash/templateSettings.js";const J={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"},D={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"},fs=ss(null);function kr({children:s,membraneCLIService:e}){const{data:t}=rs("/account"),[n,i]=j(D.NOT_INITIALIZED),[r,o]=j([]),[a,l]=j({}),[u,p]=j([]),[d,h]=j(null),w=t?.workspaces?.find(f=>f.workspaceKey===d?.workspaceKey)||null;return Ie(()=>{const f=c(({state:I})=>i(I),"handleStateChanged"),y=c(({stats:I})=>l(I),"handleStatsChanged"),C=c(({log:I})=>p(O=>[...O,I]),"handleLogAdded"),v=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=c(({config:I})=>h(I),"handleConfigChanged");return e.notifications.on(J.StateChanged,f),e.notifications.on(J.StatsChanged,y),e.notifications.on(J.LogAdded,C),e.notifications.on(J.ConflictsChanged,v),e.notifications.on(J.ConfigChanged,A),e.init(),()=>{e.notifications.off(J.StateChanged,f),e.notifications.off(J.StatsChanged,y),e.notifications.off(J.LogAdded,C),e.notifications.off(J.ConflictsChanged,v),e.notifications.off(J.ConfigChanged,A)}},[]),m(fs.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:r,config:d,updateConfig:c(f=>e.updateConfig(f),"updateConfig"),resolveConflicts:c(f=>e.syncWorkspaces(f),"resolveConflicts"),pull:c(f=>e.pullWorkspace(f),"pull"),push:c(f=>e.pushWorkspace(f),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(kr,"MembraneCLIServiceProvider");function oe(){const s=is(fs);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(oe,"useMembraneCLIService");const vr="membrane",Er="membrane.config.yml",cn="https://api.integration.app";function ln(){const s=process.cwd(),e=x.join(s,vr),t=x.join(s,Er),n=e,i=x.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}c(ln,"getPaths");function Ir(){return ln().membraneDirPath}c(Ir,"getBasePath");const Tr={pat:{type:"string"},workspace:{type:"object"}},hs=new Xi({schema:Tr,configName:"config",cwd:B.join(os.homedir(),".membrane")}),Nr=c(s=>{hs.set("pat",s)},"setPat"),ds=c(()=>hs.get("pat"),"getPat");class ps{static{c(this,"AccountApiClient")}constructor(e=cn){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=ds();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 Ar=c(s=>{const e=new ps(cn);return t=>e.get(t)},"createAccountApiFetcher"),ms=ss(process.cwd());function Or({cwd:s,children:e}){return m(ms.Provider,{value:s,children:e})}c(Or,"CwdProvider");function $r(){return is(ms)}c($r,"useCwd");function wt({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Or,{cwd:n,children:m(Yi,{value:{fetcher:Ar()},children:m(kr,{membraneCLIService:t,children:e})})})}c(wt,"Layout");const un=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=x.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(P.existsSync(s))try{t=JSON.parse(P.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return P.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=x.join(process.cwd(),".cursor"),e=x.join(s,"mcp.json");P.existsSync(s)||P.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(P.existsSync(e))try{n=JSON.parse(P.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return P.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Lr({onExit:s,onComplete:e}){const[t,n]=j(0),[i,r]=j(!1),[o,a]=j(null),[l,u]=j(""),[p,d]=j("");Pe((w,f)=>{if(l||p){(f.escape||w==="q"||f.return)&&e();return}if(i)f.return||w===" "?h(o):f.escape&&(r(!1),a(null));else if(f.escape)s();else if(f.upArrow||w==="k")n(Math.max(0,t-1));else if(f.downArrow||w==="j")n(Math.min(un.length-1,t+1));else if(f.return||w===" "){const y=un[t];a(y),r(!0)}});const h=c(w=>{try{const f=w.addConfig();u(f)}catch(f){d(`Failed to write configuration: ${f.message||f}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"green",children:l}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(b,{marginTop:1,paddingLeft:2,children:m(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):p?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"red",children:"Error"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:m(S,{color:"red",children:p})}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",m(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,children:m(S,{color:"yellow",bold:!0,children:o.actionDescription})}),m(b,{marginTop:2,marginBottom:1,children:E(S,{children:[m(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[m(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(b,{marginTop:1,flexDirection:"column",children:un.map((w,f)=>E(b,{children:[E(S,{color:t===f?"cyan":"white",children:[t===f?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Lr,"AddMcpServerScreen");class gs extends tr{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const ys="membrane.config.yml",bt=W.object({workspaceKey:W.string(),workspaceSecret:W.string(),apiUri:W.string().optional(),testCustomerId:W.string().optional(),anthropicApiKey:W.string().optional()});class He{static{c(this,"ConfigLoader")}static instance=null;cachedConfig=null;lastCwd=null;constructor(){}static getInstance(){return He.instance||(He.instance=new He),He.instance}loadConfig(e){const t=e??process.cwd();if(this.cachedConfig&&this.lastCwd===t)return this.cachedConfig;this.lastCwd=t;const n=this.loadFromFile(t),i=this.loadFromEnv(),r={...n,...i},o=bt.safeParse(r);return o.success?(this.cachedConfig=o.data,o.data):(this.cachedConfig=null,null)}clearCache(){this.cachedConfig=null,this.lastCwd=null}updateConfig(e){const t={...this.cachedConfig??{},...e},n=bt.safeParse(t),i=this.lastCwd??process.cwd();return this.saveToFile(e,i),n.success?(this.cachedConfig=n.data,this.cachedConfig):(this.cachedConfig=null,null)}isCacheDefined(e){return bt.safeParse(e).success}loadFromFile(e){const t=x.join(e,ys);try{const n=P.readFileSync(t,"utf8"),i=pe.load(n),r=bt.safeParse(i);return r.success?r.data:{}}catch{return{}}}loadFromEnv(){const e={};return process.env.MEMBRANE_WORKSPACE_KEY&&(e.workspaceKey=process.env.MEMBRANE_WORKSPACE_KEY),process.env.MEMBRANE_WORKSPACE_SECRET&&(e.workspaceSecret=process.env.MEMBRANE_WORKSPACE_SECRET),process.env.MEMBRANE_API_URI&&(e.apiUri=process.env.MEMBRANE_API_URI),e}saveToFile(e,t){const n=t??process.cwd(),i=x.join(n,ys),o={...this.loadFromFile(n),...e},a=this.loadFromEnv();for(const l of Object.keys(a))a[l]===o[l]&&delete o[l];try{return P.writeFileSync(i,pe.dump(o)),!0}catch{return!1}}}const Ze=He.getInstance();function St(s){return Ze.loadConfig(s)}c(St,"readProjectConfig");class Dr{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return rn.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=St(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 IntegrationAppClient: 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}getCurrentConfigInfo(){return this.currentConfig}}const le=new Dr;async function ws(s){const e=await le.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(ws,"getWorkspaceId");class Pr extends gs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(J.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(J.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(J.ConfigChanged,{config:e})}setStats(e){this.emit(J.StatsChanged,{stats:e})}addLog(e){this.emit(J.LogAdded,{log:e})}setMcpStatus(e){this.emit(J.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(J.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){if(!(!this.clientId||this.isCleaningUp)){this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0);try{await(await le.getClient(process.cwd())).delete(`/local-clients/${this.clientId}`)}catch{}this.clientId=void 0}}async registerWithRemoteServer(){if(this.clientId)return;const t=await(await le.getClient(process.cwd())).post("/local-clients",{hostname:os.hostname(),workingDirectory:process.cwd()});this.clientId=t.id}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){if(!this.clientId)return;await(await le.getClient(process.cwd())).post(`/local-clients/${this.clientId}/keep-alive`,{})}async emitRemote(e){if(!this.clientId)return;await(await le.getClient(process.cwd())).patch(`/local-clients/${this.clientId}`,e)}}const ue=new Pr({heartbeatIntervalMs:15e3});function xr(){const[s,e]=j(null),[t,n]=j([]),[i,r]=j(null);return Ie(()=>{const o=c(({status:l})=>{e(l),r(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),r(null)},"handleMcpServersChanged");return ue.on(J.McpStatusChanged,o),ue.on(J.McpServersChanged,a),()=>{ue.off(J.McpStatusChanged,o),ue.off(J.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}}c(xr,"useMcpStatus");function Mr(){const{error:s,serverCount:e,allMcpServers:t}=xr(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(S,{color:"red",children:"error reading status"}):e===0?m(S,{color:"yellow",children:"none"}):m(S,{color:"green",children:e})]})}),!s&&e===0&&m(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",m(Vi,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>m(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"[a: connect an agent]"})})]})}c(Mr,"Agent");const Ct=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function bs(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(bs,"truncateText");function fn({children:s}){const{state:e,logs:t}=oe();if(!e||e===D.NOT_INITIALIZED)return E(b,{gap:1,flexDirection:"row",children:[m(ir,{type:"dots"}),m(S,{children:"Initializing..."})]});if(e===D.SETTING_UP)return m(b,{gap:1,flexDirection:"row",children:m(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})});if(e===D.ERROR){const n=t.filter(i=>i.type==="error");return m(b,{gap:1,flexDirection:"row",children:n.slice().map((i,r)=>m(S,{color:Ct(i.type),children:i.message},i.timestamp+r))})}return s}c(fn,"EnsureInitialized");function Ss({onExit:s,showEscOption:e=!0}){const[t,n]=j(""),{data:i,error:r,isLoading:o}=rs("/account"),{updateConfig:a}=oe(),l=i?.workspaces,u=o;if(Pe((f,y)=>{y.escape&&s?.()}),u)return E(b,{children:[m(yt,{}),m(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]});const p=l?.filter(f=>f.name.toLowerCase().includes(t.toLowerCase()))??[],d=p.map(f=>({label:f.name,value:f.id})),h=d.length,g=l?.length??0;async function w(f){const y=p.find(A=>A.id===f);if(!y)return;const{workspaceKey:C,workspaceSecret:v}=y;!C||!v||(await a({workspaceKey:C,workspaceSecret:v}),s?.())}return c(w,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,children:m(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[m(S,{children:"Search: "}),m(rr,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(S,{children:["Showing ",h," of ",g," workspaces."]}),m(b,{marginTop:1,children:m(or,{options:d,onChange:c(f=>{f&&w(f)},"onChange")})}),e&&m(b,{marginTop:1,children:m(S,{color:"grey",children:"Press ESC to go back"})})]})}c(Ss,"SelectWorkspace");function Rr({currentPat:s,onSubmit:e}){const[t,n]=j(""),[i,r]=j(!1),[o,a]=j(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(b,{marginTop:-1,marginBottom:1,children:m(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(S,{children:"Please provide your Personal Access Token. You can find it here:"}),m(b,{marginTop:1,marginBottom:1,children:m(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(ar,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&m(b,{marginTop:1,children:E(S,{children:[m(yt,{type:"dots"})," Validating token..."]})}),o&&m(S,{color:"red",children:o})]})}c(Rr,"PersonalAccessTokenInput");var et=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(et||{});const _r={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hn=[et.Authenticate,et.ConnectWorkspace];function Cs({onComplete:s}){const{config:e}=oe(),[t,n]=j(!1),[i,r]=j(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=ds(),l=hn[i],u=i+1,p=hn.length,d=hn.map((w,f)=>{let y="pending";return f<i?y="done":f===i&&(y="current"),{id:w,label:_r[w],status:y}});async function h(w){const f=a&&w===""?a:w,y=new ps;try{await y.request("/account",{headers:{Authorization:`Bearer ${f}`}}),Nr(f),r(C=>C+1)}catch(C){console.error(C)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Pe((w,f)=>{o&&f.escape&&s&&s()}),t?m(b,{children:m(S,{children:"\u2705 Setup complete. You are ready to go!"})}):E(b,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",u," of ",p]}),o&&m(S,{color:"grey",children:" [esc: go back]"})]})}),m(b,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Kr,{status:w.status,label:w.label},w.id))})]}),l===et.Authenticate&&m(Rr,{currentPat:a,onSubmit:h}),l===et.ConnectWorkspace&&m(Ss,{onExit:g,showEscOption:!1})]})}c(Cs,"Setup");function Kr({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&m(yt,{type:"dots"}),s==="done"&&m(S,{children:"\u2705"})]}),m(S,{dimColor:s!=="current",children:e})]})}c(Kr,"StepDisplay");function dn(){const{stats:s}=oe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",children:[m(b,{children:m(b,{width:12,children:m(S,{color:"grey",children:"Elements:"})})}),m(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[m(b,{width:20,children:E(S,{children:[t,":"]})}),m(S,{color:"green",children:n})]},t))})]})}c(dn,"ElementStats");const pn=5,Fr=6;function jr(){const{logs:s}=oe(),[e,t]=j(0),n=Math.min(100,process.stdout.columns||100),i=pn,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),l=n-Fr,u=e<s.length-i,p=e>0;return Pe((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-i);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(b,{flexDirection:"column",paddingTop:1,children:[E(S,{color:"grey",children:["Recent Activity (",r+1,"-",o," of ",s.length,"):",s.length>pn&&m(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(b,{marginLeft:1,children:m(S,{color:Ct(d.type),children:bs(d.message,l)})},d.timestamp+h)),s.length>pn&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&m(S,{color:"grey",children:"\u2191 "}),p&&m(S,{color:"grey",children:"\u2193 "})]})]})}c(jr,"Logs");const X={UPDATE:"update",DELETE:"delete",CREATE:"create"},fe={INCOMING:"incoming",OUTGOING:"outgoing"},kt=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Br(){const{state:s,resolveConflicts:e,exit:t}=oe(),[n,i]=j(0),[r,o]=j(!1);return Pe((a,l)=>{r||(l.upArrow?i(u=>u>0?u-1:kt.length-1):l.downArrow?i(u=>u<kt.length-1?u+1:0):a.toLowerCase()==="y"?i(0):a.toLowerCase()==="n"?i(1):(l.return||a===" ")&&(o(!0),kt[n].value==="sync"?e({watch:!0}):t()))}),Ie(()=>{s!==D.CONFLICTS&&r&&o(!1)},[s,r]),E(b,{flexDirection:"column",paddingTop:1,children:[m(b,{children:m(b,{flexDirection:"row",gap:2,children:m(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(b,{children:m(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(b,{marginTop:1,marginLeft:2,children:m(mn,{})}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[m(S,{color:"white",bold:!0,children:"What would you like to do?"}),m(S,{color:"grey",children:"[up/down, enter]"})]}),m(b,{children:r?E(b,{flexDirection:"row",gap:1,children:[m(yt,{type:"dots"}),m(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(b,{flexDirection:"column",children:kt.map((a,l)=>m(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[m(S,{color:n===l?"cyan":"grey",children:n===l?"\u25B6":" "}),m(S,{color:n===l?"cyan":"grey",bold:n===l,children:a.label})]})},a.value))})})]})}c(Br,"ResolveChangesUI");const Ur={[X.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[X.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[X.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function mn(){const{conflicts:s}=oe(),e=zi(()=>{const t={};return s.forEach(n=>{const i=`${n.type}-${n.direction}`;t[i]||(t[i]=[]),t[i].push(n)}),t},[s]);return m(b,{flexDirection:"column",children:Object.entries(e).map(([t,n])=>{if(n.length===0)return null;const[i,r]=t.split("-"),o=Ur[i][r];return E(b,{flexDirection:"column",children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",children:[o.label," (",n.length,")"]}),m(S,{color:"white",children:o.description})]}),n.map(a=>m(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",a.element.id," (",a.element.relativePath,")"]})},a.element.id))]},t)})})}c(mn,"Conflicts");function qr(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:i}=oe(),r=n?.name,o=r?bs(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ie(()=>{i({watch:!0})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[m(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:Jr(e),children:[" [",Wr(e),"] "]})]})}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Local:"})}),m(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[m(b,{width:12,children:m(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[m(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===D.CONFLICTS?m(Br,{}):E(en,{children:[m(b,{paddingTop:1,children:m(dn,{})}),t.length>0&&m(jr,{})]})]})}c(qr,"Workspace");function Wr(s){switch(s){case D.PULLING:return"pulling";case D.PUSHING:return"pushing";case D.CONFLICTS:return"conflicts";case D.SYNCED:return"synced";case D.ERROR:return"error";case D.WATCHING:return"tracking changes";case D.RESOLVING:return"resolving";case D.NOT_SYNCED:return"not synced";case D.INITIALIZED:return"initialized";case D.SETTING_UP:return"setup required";default:return"unknown"}}c(Wr,"getStatusDisplay");function Jr(s){switch(s){case D.PULLING:return"yellow";case D.PUSHING:return"yellow";case D.CONFLICTS:return"red";case D.SYNCED:return"green";case D.ERROR:return"red";case D.WATCHING:return"green";case D.RESOLVING:return"yellow";case D.NOT_SYNCED:return"grey";case D.SETTING_UP:return"yellow";default:return"grey"}}c(Jr,"getStatusColor");const Gr="https://console.integration.app/w";function Vr(){const s=$r(),e=Qi(!0),{exit:t,state:n}=oe(),[i,r]=j(null),o=i??(n===D.SETTING_UP?"setup":"main");Pe(l=>{o==="main"&&(l==="w"&&r("workspace-selection"),l==="a"&&r("add-mcp-server"),l==="o"&&n===D.INITIALIZED&&a(),l==="s"&&r("setup"))});async function a(){try{const l=await ws(s),u=`${Gr}/${l}`,p=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Zi(`${p} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ie(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ss,{onExit:c(()=>r(null),"onExit")}):o==="add-mcp-server"?m(Lr,{onExit:c(()=>r(null),"onExit"),onComplete:c(()=>r(null),"onComplete")}):o==="setup"?m(Cs,{onComplete:c(()=>r(null),"onComplete")},Date.now()):m(fn,{children:E(b,{flexDirection:"column",children:[m(b,{flexGrow:1,children:m(Mr,{})}),m(qr,{}),m(b,{paddingLeft:2,children:m(S,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Vr,"Main");class Hr{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;constructor(){this._logs=[],this.workspaceNotifications=ue}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}clear(){this._logs=[]}}const T=new Hr,be=x.join(ur.tmpdir(),"membrane-mcp-status"),ks=3e4;class Yr{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=vt(void 0,e),n=vs(e);t&&ue.setMcpStatus(t),await ue.setMcpServers(n)}catch{T.error("Failed to check MCP status")}}}function vt(s,e){try{const t=e||process.cwd();if(!s){const i=vs(t);return i.length===0?null:i[0]}const n=wn(s,t);if(P.existsSync(n)){const i=P.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>ks)return tt(s,t),null;const a=P.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(r.getTime()-u>ks)return tt(s,t),null}return l}}catch{s&&e&&tt(s,e)}return null}c(vt,"getMcpStatus");function vs(s){try{const e=s||process.cwd(),t=yn(e);if(!P.existsSync(be))return[];const n=P.readdirSync(be),i=[];for(const r of n){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=vt(a,e);l&&i.push(l)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}c(vs,"getAllMcpStatusFiles");function gn(s){try{const t={...vt(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};P.existsSync(be)||P.mkdirSync(be,{recursive:!0});const n=wn(s.processId,s.cwd);P.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(gn,"updateMcpStatus");function tt(s,e){try{const t=e||process.cwd();if(s){const n=wn(s,t);P.existsSync(n)&&P.unlinkSync(n)}else{const n=yn(t);if(P.existsSync(be)){const i=P.readdirSync(be);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&P.unlinkSync(x.join(be,r))}}}catch{}}c(tt,"clearMcpStatus");function zr(s,e){const t=vt(s,e);t&&gn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(zr,"trackToolExecution");function yn(s){return lr("md5").update(s).digest("hex").slice(0,8)}c(yn,"getCwdHash");function wn(s,e){const t=yn(e);return x.join(be,`mcp-${t}-${s}.json`)}c(wn,"getStatusFilePath");const se={[K.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[K.Connector]:{element:"connector",elements:"connectors",exportable:!1},[K.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[K.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[K.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[K.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[K.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[K.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[K.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function Qr(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Qr,"baseExportCleanup");class Es{static{c(this,"ElementsCache")}elements=new Map;typeIndex=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)}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))}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}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()}getAllIds(){return new Set(this.elements.keys())}}class Is{static{c(this,"ElementsManager")}cache;handler;connectorsMapping;constructor(e){this.cache=new Es,this.handler=e}async refresh(){try{const e=new Es,t=await this.handler.getIntegrations();e.addAll(t);const n=[K.Integration,K.Connector],i=Object.keys(se),r=await Promise.all(i.filter(o=>!n.includes(o)).map(async o=>this.handler.getElementsByType(o,t)));for(const o of r)e.addAll(o);this.cache.clear(),this.cache.addAll(e.getAll())}catch(e){throw T.error(`Failed to refresh elements: ${te(e)?.message??"Unknown error"}`),e}}async putElement(e){let t,n=this.cache.get(e.id);try{e.data.id&&n?(t="update",n=await this.handler.updateElement(e,n,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})):(t="create",n=await this.handler.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping})),this.cache.put(n)}catch(i){T.error(`Failed to ${t} element ${e.type}/${e.key} ${e.integrationKey?`for integration ${e.integrationKey}`:""} (${e.id}): ${i instanceof Error?i.message:"Unknown error"}`)}}async deleteElement(e){try{await this.handler.deleteElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping}),this.cache.remove(e)}catch(t){T.error(`Failed to delete element: ${t instanceof Error?t.message:"Unknown error"}`)}}setConnectorsMapping(e){this.connectorsMapping=e}}async function Xr(s,e="full"){const t={};T.info("[connectors] Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>bn("integration",i));for(const i of Object.keys(se)){const r=se[i];if(r.exportable===!1)continue;const o=[];T.info(`[connectors] Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(l=>bn(i,l))),r.integrationSpecific)for(const l of n){const u=await s[r.elements].findAll({integrationId:l.id});o.push(...u.map(p=>(p.integrationKey=l.key,bn(i,p))))}o.length>0&&e=="full"&&(console.table(o.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[i]=o}return T.success("[connectors] Remote workspace data retrieved successfully"),t}c(Xr,"getWorkspaceData");function bn(s,e){return e=Qr(e),se[s].exportCleanup?se[s].exportCleanup(e):e}c(bn,"cleanUpForExport");const nt="connectors",st="development",Sn={};async function Zr({integrations:s,allConnectors:e=!1}){const t=Ir(),n=await le.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,l=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await Ts({client:n,connectorId:a}),d=!!u.workspaceId||e;if(!u?.key){T.error(`[connectors] Connector ${a} has no key. Skipping..`);continue}d&&(i.has(a)||(await io({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(l)||(await ro({client:n,connector:u,connectorVersion:l,basePath:t}),r[a].add(l)))}}}c(Zr,"pullConnectors");async function eo(){const s=await le.getClient(process.cwd()),e=await Xr(s,"minified"),n=(await s.get("org-workspace-id")).id,i={};T.info("[connectors] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);T.info("[connectors] Loading public connectors"),e.connector=o;const a=Cn(),u=(M.existsSync(a)?M.readdirSync(a):[]).filter(p=>{if(p.startsWith("."))return!1;const d=B.join(a,p);try{return M.statSync(d).isDirectory()}catch{return!1}});for(const p of u){T.info(`[connectors] Loading connector from: ${p}`);const d=M.readdirSync(B.join(a,p)),h=await kn(p);if("baseUri"in h&&delete h.baseUri,h.uuid&&e.connector?.find(w=>w.uuid==h.uuid))i[h.id]=e.connector.find(w=>w.uuid==h.uuid).id,T.info(`[connectors] Matched ${h.name} uuid: ${h.uuid}`);else if(!i[h.id]){let w=!1;try{const f=await Ts({client:s,connectorId:h.id});f&&!f.workspaceId&&(w=!0)}catch{}if(!w){T.info(`[connectors] Creating custom connector ${h.name} (${h.key})`);const f=await r.post("connectors",{...h,workspaceId:n});i[h.id]=f.id}}const g=d.filter(w=>M.statSync(B.join(a,p,w)).isDirectory());for(const w of g)await so({client:s,connector:h,version:w,connectorId:i[h.id]})}return i}c(eo,"pushConnectors");function Cn(){const s=ln();return B.join(s.membraneDirPath,nt)}c(Cn,"getConnectorsPath");async function kn(s){return pe.load(M.readFileSync(B.join(Cn(),s,`${s}.yml`),"utf8"))}c(kn,"readConnector");async function to(s,e){return T.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=M.createWriteStream(e),r=fr("zip",{zlib:{level:9}});i.on("close",()=>{T.success(`[connectors] Successfully created ${e}`),t()}),i.on("end",()=>{T.info("[connectors] Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=M.readdirSync(s);for(const a of o){const l=B.join(s,a),u=M.statSync(l);u.isFile()?r.file(l,{name:a}):u.isDirectory()&&r.directory(l,a)}r.finalize()})}c(to,"createZipArchive");async function no(s,e){return T.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const i=dr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const l=B.join(e,o);M.mkdirSync(l,{recursive:!0}),r.autodrain()}else{const l=B.join(e,o),u=B.dirname(l);M.mkdirSync(u,{recursive:!0});const p=M.createWriteStream(l);r.pipe(p),p.on("finish",()=>{})}}),i.on("end",()=>{T.success(`[connectors] Successfully extracted to ${e}`),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}c(no,"extractZipArchive");async function so({client:s,connector:e,version:t,connectorId:n}){const i=B.join(Cn(),Et(e),Ns(t)),r=B.join(i,"src"),o=B.join(i,"src.zip"),a=M.existsSync(o);if(M.existsSync(r)&&(T.info(`[connectors] Archiving source code for ${e.name} version ${t}`),await to(r,o)),!M.existsSync(o)){T.warning(`[connectors] No source code found for ${e.name} version ${t}`);return}try{const l=new hr;if(l.append("file",M.createReadStream(o),"file.zip"),T.info(`[connectors] Pushing connector version ${t} for ${e.name}`),t==st)T.info(`[connectors] Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,l,{headers:{...l.getHeaders()}});else{if(l.append("version",t),l.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(p=>p.version==t)){T.info(`[connectors] Version ${t} already published`);return}T.info(`[connectors] Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,l,{headers:{...l.getHeaders()}})}T.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(l){T.error(`Error pushing connector version ${t} for ${e.name}: ${l}`)}finally{!a&&M.existsSync(o)&&(T.info(`[connectors] Cleaning up temporary zip file for ${e.name} version ${t}`),M.unlinkSync(o))}}c(so,"pushConnectorVersion");async function Ts({client:s,connectorId:e}){if(Sn[e])return Sn[e];const t=await s.get(`connectors/${e}`);return Sn[e]=t,t}c(Ts,"getConnector");async function io({basePath:s,connector:e}){const t=Et(e),n=B.join(s,nt,t);M.mkdirSync(n,{recursive:!0});const i=B.join(n,`${Et(e)}.yml`);M.writeFileSync(i,pe.dump(e)),T.info(`[connectors] Pulled connector ${e.name}`)}c(io,"pullConnector");async function ro({client:s,connector:e,connectorVersion:t,basePath:n}){const i=Et(e),r=Ns(t),o=B.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});M.mkdirSync(o,{recursive:!0});const l=B.join(o,"src.zip");if(M.writeFileSync(l,a),!t){const u=B.join(o,"src");M.mkdirSync(u,{recursive:!0}),await no(a,u)}T.info(`[connectors] Pulled connector version: ${e.name} (${r})`)}c(ro,"pullConnectorVersion");function Et(s){return s.key}c(Et,"getConnectorDirName");function Ns(s){return s??st}c(Ns,"getConnectorVersionDirName");function oo(s){return s.match(`${nt}/[^/]+/${st}/src/.*`)!==null}c(oo,"isConnectorSourceFile");async function ao(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id,o=M.readFileSync(s,"utf-8");await(await le.getClient()).put(`connectors/${r}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}}),T.info(`[connectors] Pushed file ${n} for connector ${i.name}`)}c(ao,"putConnectorFile");async function co(s){const e=s.match(`${nt}/([^/]+)/${st}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],i=await kn(t);if(!i){T.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const r=i.id;await(await le.getClient()).delete(`connectors/${r}/files/${n}`),T.info(`[connectors] Deleted file ${n} for connector ${i.name}`)}c(co,"deleteConnectorFile");const lo="membrane",uo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function It(s){return x.join(s,lo)}c(It,"getMembraneDir");const fo=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt","baseUri","state"],As=[K.Action,K.FieldMapping,K.Flow,K.DataSource];class V{static{c(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||V.extractIntegrationKey(i)}get id(){return V.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=we[this.type].apiPath;if(this.integrationKey){const t=we[K.Integration].apiPath;return x.join(t,this.integrationKey,e,this.key)}return x.join(e,this.key)}get path(){return x.join(this.dirPath,"spec.yaml")}get relativePath(){return x.relative(It(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return pr(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return fo.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return se?.[this.type]?.parentKey&&(e=se?.[this.type]?.parentKey),e}static new(e,t,n,i){return new V(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 V(e,t.key,n,t)}static fromPathAndData(e,t){const n=V.parsePath(e);if(!t)return;const i=t?.key||n?.key;return n?V.new(n.type,i,n.integrationKey,t):void 0}static fromElement(e){return new V(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=V.parsePath(e);if(t)return V.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===K.Integration?`${e}:${t}`:V.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(we).map(l=>l.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:l,elementKey:u}=r.groups,p=this.getElementTypeFromPath(l);if(p)return{type:p,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:p}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:p,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(K).find(t=>we[t].apiPath===e)}static getRelativePath(e){return x.relative(It(process.cwd()),e)}static isIntegrationSpecific(e){return As.includes(e)}static canBeIntegrationSpecific(e){return As.includes(e)}}class ho{static{c(this,"LocalElementsHandler")}basePath;constructor(){this.basePath=It(process.cwd())}async getElementsByType(e,t){const n=[],i=x.join(this.basePath,we[e].apiPath),r=await this.readElementsInDir(i);n.push(...r);for(const o of t){const a=x.join(this.basePath,we[K.Integration].apiPath,o.key,we[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&T.success(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(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=x.join(this.basePath,t.dirPath),i=x.join(this.basePath,t.path);return P.existsSync(n)||P.mkdirSync(n,{recursive:!0}),P.writeFileSync(i,pe.dump(e.data)),T.info(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=x.join(this.basePath,e.path),n=x.join(this.basePath,e.dirPath);P.existsSync(t)&&P.rmSync(t,{force:!0}),this.pruneEmptyDir(n),T.info(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=x.join(this.basePath,we[K.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){if(!P.existsSync(e))return;const t=P.readFileSync(e,"utf8"),n=pe.load(t);if(n)return V.fromPathAndData(e,n)}async readElementsInDir(e){const t=[];if(!P.existsSync(e))return t;const n=P.readdirSync(e);if(n.length===0)return t;const i=n.map(async o=>{const a=x.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||!P.existsSync(e)||P.readdirSync(e).length>0)return;P.rmdirSync(e),this.pruneEmptyDir(x.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class po{static{c(this,"RemoteElementsHandler")}client;async getElementsByType(e,t){const n=await this.findAll(e);if(!V.canBeIntegrationSpecific(e))return n;for(const i of t){const r=i.key,o=i.data.id,a=await this.findAll(e,{integrationKey:r,integrationId:o});n.push(...a)}return n.length>0&&T.success(`[remote] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async fetchElement(e){const n=await(await this.getClient())[se[e.type].element](e.data.id).get();return V.fromData(e.type,n)}async createElement(e,t){const n=e.clean(),i=await this.getClient();this.transformElementForCreate(e,n,t),e.key==="download-document-by-id"&&T.info(`CREATE ${e.id}:`+JSON.stringify(n));const r=await i[se[e.type].elements].create(n),o=V.fromData(e.type,r);return T.info(`[remote] Created ${o.id}`),o}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");const i=e.clean(),r=await this.getClient();this.transformElementForUpdate(e,i,n);const o=await r[se[e.type].element](t.data.id).put(i),a=V.fromData(t.type,o);return T.info(`[remote] Updated ${t.id}`),a}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await(await this.getClient())[se[e.type].element](e.data.id).archive(),T.info(`[remote] Deleted ${e.id}`)}async getIntegrations(){const n=(await(await this.getClient()).integrations.findAll()).map(i=>V.fromData(K.Integration,i));return n.length>0&&T.success(`[remote] Fetched ${n.length} integrations`),n}transformElementForCreate(e,t,n){if(e.integrationKey){const i=n.elements.find(r=>r.type===K.Integration&&r.key===e.integrationKey);if(i)t.integrationId=i.data.id;else throw new Error(`Integration ${e.integrationKey} not found. Integrations: ${n.elements.filter(r=>r.type===K.Integration).map(r=>r.key).join(", ")}`)}if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}transformElementForUpdate(e,t,n){if(e.type===K.Integration){const i=n.connectorsMapping?.[t.connectorId];i&&(t.connectorId=i)}}async findAll(e,t={}){return(await(await this.getClient())[se[e].elements].findAll(t)).filter(r=>r.key).map(r=>V.fromData(e,r))}async getClient(){return this.client||(this.client=await le.getClient(process.cwd())),this.client}}const vn=Symbol.for("yaml.alias"),En=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),Os=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),Me=Symbol.for("yaml.seq"),ie=Symbol.for("yaml.node.type"),Ce=c(s=>!!s&&typeof s=="object"&&s[ie]===vn,"isAlias"),Te=c(s=>!!s&&typeof s=="object"&&s[ie]===En,"isDocument"),Re=c(s=>!!s&&typeof s=="object"&&s[ie]===Se,"isMap"),F=c(s=>!!s&&typeof s=="object"&&s[ie]===Os,"isPair"),R=c(s=>!!s&&typeof s=="object"&&s[ie]===he,"isScalar$1"),_e=c(s=>!!s&&typeof s=="object"&&s[ie]===Me,"isSeq");function U(s){if(s&&typeof s=="object")switch(s[ie]){case Se:case Me:return!0}return!1}c(U,"isCollection$1");function q(s){if(s&&typeof s=="object")switch(s[ie]){case vn:case Se:case he:case Me:return!0}return!1}c(q,"isNode");const $s=c(s=>(R(s)||U(s))&&!!s.anchor,"hasAnchor"),ee=Symbol("break visit"),Ls=Symbol("skip children"),de=Symbol("remove node");function Ne(s,e){const t=Ds(e);Te(s)?Ke(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):Ke(null,s,t,Object.freeze([]))}c(Ne,"visit$1"),Ne.BREAK=ee,Ne.SKIP=Ls,Ne.REMOVE=de;function Ke(s,e,t,n){const i=Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Ke(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=Ke(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=Ke("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=Ke("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Ke,"visit_");async function Tt(s,e){const t=Ds(e);Te(s)?await Fe(null,s.contents,t,Object.freeze([s]))===de&&(s.contents=null):await Fe(null,s,t,Object.freeze([]))}c(Tt,"visitAsync"),Tt.BREAK=ee,Tt.SKIP=Ls,Tt.REMOVE=de;async function Fe(s,e,t,n){const i=await Ps(s,e,t,n);if(q(i)||F(i))return xs(s,n,i),Fe(s,i,t,n);if(typeof i!="symbol"){if(U(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Fe(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ee)return ee;o===de&&(e.items.splice(r,1),r-=1)}}}else if(F(e)){n=Object.freeze(n.concat(e));const r=await Fe("key",e.key,t,n);if(r===ee)return ee;r===de&&(e.key=null);const o=await Fe("value",e.value,t,n);if(o===ee)return ee;o===de&&(e.value=null)}}return i}c(Fe,"visitAsync_");function Ds(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(Ds,"initVisitor");function Ps(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(Re(e))return t.Map?.(s,e,n);if(_e(e))return t.Seq?.(s,e,n);if(F(e))return t.Pair?.(s,e,n);if(R(e))return t.Scalar?.(s,e,n);if(Ce(e))return t.Alias?.(s,e,n)}c(Ps,"callVisitor");function xs(s,e,t){const n=e[e.length-1];if(U(n))n.items[s]=t;else if(F(n))s==="key"?n.key=t:n.value=t;else if(Te(n))n.contents=t;else{const i=Ce(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}c(xs,"replaceNode");const mo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},go=c(s=>s.replace(/[!,[\]{}]/g,e=>mo[e]),"escapeTagName");class Z{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Z.defaultYaml,e),this.tags=Object.assign({},Z.defaultTags,t)}clone(){const e=new Z(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Z(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Z.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Z.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Z.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Z.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+go(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&&q(e.contents)){const r={};Ne(e.contents,(o,a)=>{q(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
+ `)}}Z.defaultYaml={explicit:!1,version:"1.2"},Z.defaultTags={"!!":"tag:yaml.org,2002:"};function Ms(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(Ms,"anchorIsValid");function Rs(s){const e=new Set;return Ne(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(Rs,"anchorNames");function _s(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(_s,"findNewAnchor");function yo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:c(r=>{t.push(r),i??(i=Rs(s));const o=_s(e,i);return i.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(R(o.node)||U(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}}c(yo,"createNodeAnchors");function je(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=je(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=je(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=je(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=je(s,n,i,r);o===void 0?delete n[i]:o!==r&&(n[i]=o)}return s.call(e,t,n)}c(je,"applyReviver");function re(s,e,t){if(Array.isArray(s))return s.map((n,i)=>re(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!$s(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}c(re,"toJS");class In{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,ie,{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(!Te(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=re(this,"",o);if(typeof i=="function")for(const{count:l,res:u}of o.anchors.values())i(u,l);return typeof r=="function"?je(r,{"":a},"",a):a}}class Nt extends In{static{c(this,"Alias")}constructor(e){super(vn),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=[],Ne(e,{Node:c((r,o)=>{(Ce(o)||$s(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 l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(re(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=At(i,o,n)),a.count*a.aliasCount>r)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(Ms(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 At(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(U(e)){let n=0;for(const i of e.items){const r=At(s,i,t);r>n&&(n=r)}return n}else if(F(e)){const n=At(s,e.key,t),i=At(s,e.value,t);return Math.max(n,i)}return 1}c(At,"getAliasCount");const Ks=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends In{static{c(this,"Scalar")}constructor(e){super(he),this.value=e}toJSON(e,t){return t?.keep?this.value:re(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const wo="tag:yaml.org,2002:";function bo(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)}c(bo,"findTagObject");function it(s,e,t){if(Te(s)&&(s=s.contents),q(s))return s;if(F(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 l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=i(s)),new Nt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=wo+e.slice(2));let u=bo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new L(s);return l&&(l.node=d),d}u=s instanceof Map?o[Se]:Symbol.iterator in Object(s)?o[Me]:o[Se]}r&&(r(u),delete t.onTagObj);const p=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new L(s);return e?p.tag=e:u.default||(p.tag=u.tag),l&&(l.node=p),p}c(it,"createNode");function Ot(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 it(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(Ot,"collectionFromPath");const rt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Fs extends In{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>q(n)||F(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(rt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(U(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ot(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(U(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&&R(r)?r.value:r:U(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!F(t))return!1;const n=t.value;return n==null||e&&R(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 U(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(U(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Ot(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const So=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function me(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(me,"indentComment");const Ae=c((s,e,t)=>s.endsWith(`
4
+ `)?me(t,e):t.includes(`
5
5
  `)?`
6
- `+pe(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Js="flow",Nn="block",At="quoted";function Ot(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 l=Math.max(1+r,1+i-e.length);if(s.length<=l)return s;const u=[],p={};let h=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):h=i-n);let f,g,w=!1,d=-1,y=-1,C=-1;t===Nn&&(d=Gs(s,d,e.length),d!==-1&&(h=d+l));for(let A;A=s[d+=1];){if(t===At&&A==="\\"){switch(y=d,s[d+1]){case"x":d+=3;break;case"u":d+=5;break;case"U":d+=9;break;default:d+=1}C=d}if(A===`
7
- `)t===Nn&&(d=Gs(s,d,e.length)),h=d+e.length+l,f=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
8
- `&&g!==" "){const E=s[d+1];E&&E!==" "&&E!==`
9
- `&&E!==" "&&(f=d)}if(d>=h)if(f)u.push(f),h=f+l,f=void 0;else if(t===At){for(;g===" "||g===" ";)g=A,A=s[d+=1],w=!0;const E=d>C+1?d-2:y-1;if(p[E])return s;u.push(E),p[E]=!0,h=E+l,f=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let v=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const E=u[A],O=u[A+1]||s.length;E===0?v=`
10
- ${e}${s.slice(0,O)}`:(t===At&&p[E]&&(v+=`${s[E]}\\`),v+=`
11
- ${e}${s.slice(E+1,O)}`)}return v}c(Ot,"foldFlowLines");function Gs(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}c(Gs,"consumeMoreIndentedLines");const $t=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Lt=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Eo(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}c(Eo,"lineLengthOverLimit");function at(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Lt(s)?" ":"");let o="",a=0;for(let l=0,u=t[l];u;u=t[++l])if(u===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,u="\\"),u==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);const p=t.substr(l+2,4);switch(p){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:p.substr(0,2)==="00"?o+="\\x"+p.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<i)l+=1;else{for(o+=t.slice(a,l)+`
6
+ `+me(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),js="flow",Tn="block",$t="quoted";function Lt(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 l=Math.max(1+r,1+i-e.length);if(s.length<=l)return s;const u=[],p={};let d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let h,g,w=!1,f=-1,y=-1,C=-1;t===Tn&&(f=Bs(s,f,e.length),f!==-1&&(d=f+l));for(let A;A=s[f+=1];){if(t===$t&&A==="\\"){switch(y=f,s[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}C=f}if(A===`
7
+ `)t===Tn&&(f=Bs(s,f,e.length)),d=f+e.length+l,h=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
8
+ `&&g!==" "){const I=s[f+1];I&&I!==" "&&I!==`
9
+ `&&I!==" "&&(h=f)}if(f>=d)if(h)u.push(h),d=h+l,h=void 0;else if(t===$t){for(;g===" "||g===" ";)g=A,A=s[f+=1],w=!0;const I=f>C+1?f-2:y-1;if(p[I])return s;u.push(I),p[I]=!0,d=I+l,h=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let v=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const I=u[A],O=u[A+1]||s.length;I===0?v=`
10
+ ${e}${s.slice(0,O)}`:(t===$t&&p[I]&&(v+=`${s[I]}\\`),v+=`
11
+ ${e}${s.slice(I+1,O)}`)}return v}c(Lt,"foldFlowLines");function Bs(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}c(Bs,"consumeMoreIndentedLines");const Dt=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Pt=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Co(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}c(Co,"lineLengthOverLimit");function ot(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Pt(s)?" ":"");let o="",a=0;for(let l=0,u=t[l];u;u=t[++l])if(u===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,u="\\"),u==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);const p=t.substr(l+2,4);switch(p){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:p.substr(0,2)==="00"?o+="\\x"+p.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<i)l+=1;else{for(o+=t.slice(a,l)+`
14
14
 
15
15
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
16
- `,l+=2;o+=r,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:Ot(o,r,At,$t(e,!1))}c(at,"doubleQuotedString");function An(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
- `)||/[ \t]\n|\n[ \t]/.test(s))return at(s,e);const t=e.indent||(Lt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${t}`)+"'";return e.implicitKey?n:Ot(n,t,Js,$t(e,!1))}c(An,"singleQuotedString");function Ue(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=at;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=An:r&&!i?n=at:n=t?An:at}return n(s,e)}c(Ue,"quotedString");let On;try{On=new RegExp(`(^|(?<!
16
+ `,l+=2;o+=r,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:Lt(o,r,$t,Dt(e,!1))}c(ot,"doubleQuotedString");function Nn(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(s))return ot(s,e);const t=e.indent||(Pt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${t}`)+"'";return e.implicitKey?n:Lt(n,t,js,Dt(e,!1))}c(Nn,"singleQuotedString");function Be(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=ot;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=Nn:r&&!i?n=ot:n=t?Nn:ot}return n(s,e)}c(Be,"quotedString");let An;try{An=new RegExp(`(^|(?<!
19
19
  ))
20
20
  +(?!
21
- |$)`,"g")}catch{On=/\n+(?!\n|$)/g}function Pt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Ue(t,n);const u=n.indent||(n.forceBlockIndent||Lt(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===L.BLOCK_FOLDED?!1:e===L.BLOCK_LITERAL?!0:!Eo(t,l,u.length);if(!t)return p?`|
21
+ |$)`,"g")}catch{An=/\n+(?!\n|$)/g}function xt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Be(t,n);const u=n.indent||(n.forceBlockIndent||Pt(t)?" ":""),p=o==="literal"?!0:o==="folded"||e===L.BLOCK_FOLDED?!1:e===L.BLOCK_LITERAL?!0:!Co(t,l,u.length);if(!t)return p?`|
22
22
  `:`>
23
- `;let h,f;for(f=t.length;f>0;--f){const O=t[f-1];if(O!==`
24
- `&&O!==" "&&O!==" ")break}let g=t.substring(f);const w=g.indexOf(`
25
- `);w===-1?h="-":t===g||w!==g.length-1?(h="+",r&&r()):h="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
26
- `&&(g=g.slice(0,-1)),g=g.replace(On,`$&${u}`));let d=!1,y,C=-1;for(y=0;y<t.length;++y){const O=t[y];if(O===" ")d=!0;else if(O===`
27
- `)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let E=(d?u?"2":"1":"")+h;if(s&&(E+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!p){const O=t.replace(/\n+/g,`
28
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const K=$t(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(K.onOverflow=()=>{$=!0});const N=Ot(`${v}${O}${g}`,u,Nn,K);if(!$)return`>${E}
29
- ${u}${N}`}return t=t.replace(/\n+/g,`$&${u}`),`|${E}
30
- ${u}${v}${t}${g}`}c(Pt,"blockString");function Io(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:p}=e;if(a&&r.includes(`
31
- `)||p&&/[[\]{},]/.test(r))return Ue(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
32
- `)?Ue(r,e):Pt(s,e,t,n);if(!a&&!p&&i!==L.PLAIN&&r.includes(`
33
- `))return Pt(s,e,t,n);if(Lt(r)){if(l==="")return e.forceBlockIndent=!0,Pt(s,e,t,n);if(a&&l===u)return Ue(r,e)}const h=r.replace(/\n+/g,`$&
34
- ${l}`);if(o){const f=c(d=>d.default&&d.tag!=="tag:yaml.org,2002:str"&&d.test?.test(h),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(f)||g?.some(f))return Ue(r,e)}return a?h:Ot(h,l,Js,$t(e,!1))}c(Io,"plainString");function ct(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const l=c(p=>{switch(p){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?Ue(o.value,e):Pt(o,e,t,n);case L.QUOTE_DOUBLE:return at(o.value,e);case L.QUOTE_SINGLE:return An(o.value,e);case L.PLAIN:return Io(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:h}=e.options,f=i&&p||h;if(u=l(f),u===null)throw new Error(`Unsupported default string type ${f}`)}return u}c(ct,"stringifyString");function Vs(s,e){const t=Object.assign({blockQuote:!0,commentString:vo,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}c(Vs,"createStringifyContext");function To(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(R(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}c(To,"getTagObject");function No(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(R(s)||q(s))&&s.anchor;r&&Fs(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(" ")}c(No,"stringifyProps");function qe(s,e,t,n){if(F(s))return s.toString(e,t,n);if(ke(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:c(l=>i=l,"onTagObj")});i??(i=To(e.doc.schema.tags,r));const o=No(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):R(r)?ct(r,e,t,n):r.toString(e,t,n);return o?R(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
- ${e.indent}${a}`:a}c(qe,"stringify$2");function Ao({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:p,simpleKeys:h}}=t;let f=W(s)&&s.comment||null;if(h){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(q(s)||!W(s)&&typeof s=="object"){const K="With simple keys, collection cannot be used as a key value";throw new Error(K)}}let g=!h&&(!s||f&&e==null&&!t.inFlow||q(s)||(R(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(h||!r),indent:a+l});let w=!1,d=!1,y=qe(s,t,()=>w=!0,()=>d=!0);if(!g&&!t.inFlow&&y.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(r&&!h||e==null&&g)return y=`? ${y}`,f&&!w?y+=Oe(y,t.indent,u(f)):d&&i&&i(),y;w&&(f=null),g?(f&&(y+=Oe(y,t.indent,u(f))),y=`? ${y}
36
- ${a}:`):(y=`${y}:`,f&&(y+=Oe(y,t.indent,u(f))));let C,v,A;W(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!f&&R(e)&&(t.indentAtStart=y.length+1),d=!1,!p&&l.length>=2&&!t.inFlow&&!g&&_e(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let E=!1;const O=qe(e,t,()=>E=!0,()=>d=!0);let $=" ";if(f||C||v){if($=C?`
37
- `:"",v){const K=u(v);$+=`
38
- ${pe(K,t.indent)}`}O===""&&!t.inFlow?$===`
23
+ `;let d,h;for(h=t.length;h>0;--h){const O=t[h-1];if(O!==`
24
+ `&&O!==" "&&O!==" ")break}let g=t.substring(h);const w=g.indexOf(`
25
+ `);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(An,`$&${u}`));let f=!1,y,C=-1;for(y=0;y<t.length;++y){const O=t[y];if(O===" ")f=!0;else if(O===`
27
+ `)C=y;else break}let v=t.substring(0,C<y?C+1:y);v&&(t=t.substring(v.length),v=v.replace(/\n+/g,`$&${u}`));let I=(f?u?"2":"1":"")+d;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!p){const O=t.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const _=Dt(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(_.onOverflow=()=>{$=!0});const N=Lt(`${v}${O}${g}`,u,Tn,_);if(!$)return`>${I}
29
+ ${u}${N}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
30
+ ${u}${v}${t}${g}`}c(xt,"blockString");function ko(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:p}=e;if(a&&r.includes(`
31
+ `)||p&&/[[\]{},]/.test(r))return Be(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||p||!r.includes(`
32
+ `)?Be(r,e):xt(s,e,t,n);if(!a&&!p&&i!==L.PLAIN&&r.includes(`
33
+ `))return xt(s,e,t,n);if(Pt(r)){if(l==="")return e.forceBlockIndent=!0,xt(s,e,t,n);if(a&&l===u)return Be(r,e)}const d=r.replace(/\n+/g,`$&
34
+ ${l}`);if(o){const h=c(f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return Be(r,e)}return a?d:Lt(d,l,js,Dt(e,!1))}c(ko,"plainString");function at(s,e,t,n){const{implicitKey:i,inFlow:r}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const l=c(p=>{switch(p){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return i||r?Be(o.value,e):xt(o,e,t,n);case L.QUOTE_DOUBLE:return ot(o.value,e);case L.QUOTE_SINGLE:return Nn(o.value,e);case L.PLAIN:return ko(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:p,defaultStringType:d}=e.options,h=i&&p||d;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(at,"stringifyString");function Us(s,e){const t=Object.assign({blockQuote:!0,commentString:So,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}}c(Us,"createStringifyContext");function vo(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(R(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}c(vo,"getTagObject");function Eo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(R(s)||U(s))&&s.anchor;r&&Ms(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(" ")}c(Eo,"stringifyProps");function Ue(s,e,t,n){if(F(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=q(s)?s:e.doc.createNode(s,{onTagObj:c(l=>i=l,"onTagObj")});i??(i=vo(e.doc.schema.tags,r));const o=Eo(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):R(r)?at(r,e,t,n):r.toString(e,t,n);return o?R(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
+ ${e.indent}${a}`:a}c(Ue,"stringify$2");function Io({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:p,simpleKeys:d}}=t;let h=q(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(U(s)||!q(s)&&typeof s=="object"){const _="With simple keys, collection cannot be used as a key value";throw new Error(_)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||U(s)||(R(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!r),indent:a+l});let w=!1,f=!1,y=Ue(s,t,()=>w=!0,()=>f=!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}`,h&&!w?y+=Ae(y,t.indent,u(h)):f&&i&&i(),y;w&&(h=null),g?(h&&(y+=Ae(y,t.indent,u(h))),y=`? ${y}
36
+ ${a}:`):(y=`${y}:`,h&&(y+=Ae(y,t.indent,u(h))));let C,v,A;q(e)?(C=!!e.spaceBefore,v=e.commentBefore,A=e.comment):(C=!1,v=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&R(e)&&(t.indentAtStart=y.length+1),f=!1,!p&&l.length>=2&&!t.inFlow&&!g&&_e(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const O=Ue(e,t,()=>I=!0,()=>f=!0);let $=" ";if(h||C||v){if($=C?`
37
+ `:"",v){const _=u(v);$+=`
38
+ ${me(_,t.indent)}`}O===""&&!t.inFlow?$===`
39
39
  `&&($=`
40
40
 
41
41
  `):$+=`
42
- ${t.indent}`}else if(!g&&q(e)){const K=O[0],N=O.indexOf(`
43
- `),V=N!==-1,ge=t.inFlow??e.flow??e.items.length===0;if(V||!ge){let xe=!1;if(V&&(K==="&"||K==="!")){let H=O.indexOf(" ");K==="&"&&H!==-1&&H<N&&O[H+1]==="!"&&(H=O.indexOf(" ",H+1)),(H===-1||N<H)&&(xe=!0)}xe||($=`
42
+ ${t.indent}`}else if(!g&&U(e)){const _=O[0],N=O.indexOf(`
43
+ `),H=N!==-1,ye=t.inFlow??e.flow??e.items.length===0;if(H||!ye){let De=!1;if(H&&(_==="&"||_==="!")){let Y=O.indexOf(" ");_==="&"&&Y!==-1&&Y<N&&O[Y+1]==="!"&&(Y=O.indexOf(" ",Y+1)),(Y===-1||N<Y)&&(De=!0)}De||($=`
44
44
  ${t.indent}`)}}else(O===""||O[0]===`
45
- `)&&($="");return y+=$+O,t.inFlow?E&&n&&n():A&&!E?y+=Oe(y,t.indent,u(A)):d&&i&&i(),y}c(Ao,"stringifyPair");function Hs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Hs,"warn");const xt="<<",me={identify:c(s=>s===xt||typeof s=="symbol"&&s.description===xt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new L(Symbol(xt)),{addToJSMap:Ys}),"resolve"),stringify:c(()=>xt,"stringify")},Oo=c((s,e)=>(me.identify(e)||R(e)&&(!e.type||e.type===L.PLAIN)&&me.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===me.tag&&t.default),"isMergeKey");function Ys(s,e,t){if(t=s&&ke(t)?t.resolve(s.doc):t,_e(t))for(const n of t.items)$n(s,e,n);else if(Array.isArray(t))for(const n of t)$n(s,e,n);else $n(s,e,t)}c(Ys,"addMergeToJSMap");function $n(s,e,t){const n=s&&ke(t)?t.resolve(s.doc):t;if(!Ke(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}c($n,"mergeValue");function zs(s,e,{key:t,value:n}){if(W(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Oo(s,t))Ys(s,e,n);else{const i=re(t,"",s);if(e instanceof Map)e.set(i,re(n,i,s));else if(e instanceof Set)e.add(i);else{const r=$o(t,i,s),o=re(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}c(zs,"addPairToJSMap");function $o(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(W(s)&&t?.doc){const n=Vs(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)+'..."'),Hs(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)}c($o,"stringifyKey");function Ln(s,e,t){const n=rt(s,void 0,t),i=rt(e,void 0,t);return new Q(n,i)}c(Ln,"createPair");class Q{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,ie,{value:Ds}),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 zs(t,n,this)}toString(e,t,n){return e?.doc?Ao(this,e,t,n):JSON.stringify(this)}}function Qs(s,e,t){return(e.inFlow??s.flow?Po:Lo)(s,e,t)}c(Qs,"stringifyCollection");function Lo({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,p=Object.assign({},t,{indent:r,type:null});let h=!1;const f=[];for(let w=0;w<e.length;++w){const d=e[w];let y=null;if(W(d))!h&&d.spaceBefore&&f.push(""),Dt(t,f,d.commentBefore,h),d.comment&&(y=d.comment);else if(F(d)){const v=W(d.key)?d.key:null;v&&(!h&&v.spaceBefore&&f.push(""),Dt(t,f,v.commentBefore,h))}h=!1;let C=qe(d,p,()=>y=null,()=>h=!0);y&&(C+=Oe(C,r,u(y))),h&&y&&(h=!1),f.push(n+C)}let g;if(f.length===0)g=i.start+i.end;else{g=f[0];for(let w=1;w<f.length;++w){const d=f[w];g+=d?`
46
- ${l}${d}`:`
45
+ `)&&($="");return y+=$+O,t.inFlow?I&&n&&n():A&&!I?y+=Ae(y,t.indent,u(A)):f&&i&&i(),y}c(Io,"stringifyPair");function qs(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(qs,"warn");const Mt="<<",ge={identify:c(s=>s===Mt||typeof s=="symbol"&&s.description===Mt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new L(Symbol(Mt)),{addToJSMap:Ws}),"resolve"),stringify:c(()=>Mt,"stringify")},To=c((s,e)=>(ge.identify(e)||R(e)&&(!e.type||e.type===L.PLAIN)&&ge.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ge.tag&&t.default),"isMergeKey");function Ws(s,e,t){if(t=s&&Ce(t)?t.resolve(s.doc):t,_e(t))for(const n of t.items)On(s,e,n);else if(Array.isArray(t))for(const n of t)On(s,e,n);else On(s,e,t)}c(Ws,"addMergeToJSMap");function On(s,e,t){const n=s&&Ce(t)?t.resolve(s.doc):t;if(!Re(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}c(On,"mergeValue");function Js(s,e,{key:t,value:n}){if(q(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(To(s,t))Ws(s,e,n);else{const i=re(t,"",s);if(e instanceof Map)e.set(i,re(n,i,s));else if(e instanceof Set)e.add(i);else{const r=No(t,i,s),o=re(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}c(Js,"addPairToJSMap");function No(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(q(s)&&t?.doc){const n=Us(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)+'..."'),qs(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)}c(No,"stringifyKey");function $n(s,e,t){const n=it(s,void 0,t),i=it(e,void 0,t);return new Q(n,i)}c($n,"createPair");class Q{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,ie,{value:Os}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return q(t)&&(t=t.clone(e)),q(n)&&(n=n.clone(e)),new Q(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Js(t,n,this)}toString(e,t,n){return e?.doc?Io(this,e,t,n):JSON.stringify(this)}}function Gs(s,e,t){return(e.inFlow??s.flow?Oo:Ao)(s,e,t)}c(Gs,"stringifyCollection");function Ao({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,p=Object.assign({},t,{indent:r,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const f=e[w];let y=null;if(q(f))!d&&f.spaceBefore&&h.push(""),Rt(t,h,f.commentBefore,d),f.comment&&(y=f.comment);else if(F(f)){const v=q(f.key)?f.key:null;v&&(!d&&v.spaceBefore&&h.push(""),Rt(t,h,v.commentBefore,d))}d=!1;let C=Ue(f,p,()=>y=null,()=>d=!0);y&&(C+=Ae(C,r,u(y))),d&&y&&(d=!1),h.push(n+C)}let g;if(h.length===0)g=i.start+i.end;else{g=h[0];for(let w=1;w<h.length;++w){const f=h[w];g+=f?`
46
+ ${l}${f}`:`
47
47
  `}}return s?(g+=`
48
- `+pe(u(s),l),a&&a()):h&&o&&o(),g}c(Lo,"stringifyBlockCollection");function Po({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,p=0;const h=[];for(let w=0;w<s.length;++w){const d=s[w];let y=null;if(W(d))d.spaceBefore&&h.push(""),Dt(e,h,d.commentBefore,!1),d.comment&&(y=d.comment);else if(F(d)){const v=W(d.key)?d.key:null;v&&(v.spaceBefore&&h.push(""),Dt(e,h,v.commentBefore,!1),v.comment&&(u=!0));const A=W(d.value)?d.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):d.value==null&&v?.comment&&(y=v.comment)}y&&(u=!0);let C=qe(d,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Oe(C,n,a(y))),!u&&(h.length>p||C.includes(`
49
- `))&&(u=!0),h.push(C),p=h.length}const{start:f,end:g}=t;if(h.length===0)return f+g;if(!u){const w=h.reduce((d,y)=>d+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=f;for(const d of h)w+=d?`
50
- ${r}${i}${d}`:`
48
+ `+me(u(s),l),a&&a()):d&&o&&o(),g}c(Ao,"stringifyBlockCollection");function Oo({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,p=0;const d=[];for(let w=0;w<s.length;++w){const f=s[w];let y=null;if(q(f))f.spaceBefore&&d.push(""),Rt(e,d,f.commentBefore,!1),f.comment&&(y=f.comment);else if(F(f)){const v=q(f.key)?f.key:null;v&&(v.spaceBefore&&d.push(""),Rt(e,d,v.commentBefore,!1),v.comment&&(u=!0));const A=q(f.value)?f.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):f.value==null&&v?.comment&&(y=v.comment)}y&&(u=!0);let C=Ue(f,l,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ae(C,n,a(y))),!u&&(d.length>p||C.includes(`
49
+ `))&&(u=!0),d.push(C),p=d.length}const{start:h,end:g}=t;if(d.length===0)return h+g;if(!u){const w=d.reduce((f,y)=>f+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=h;for(const f of d)w+=f?`
50
+ ${r}${i}${f}`:`
51
51
  `;return`${w}
52
- ${i}${g}`}else return`${f}${o}${h.join(" ")}${o}${g}`}c(Po,"stringifyFlowCollection");function Dt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=pe(e(n),s);t.push(r.trimStart())}}c(Dt,"addCommentBefore");function $e(s,e){const t=R(e)?e.value:e;for(const n of s)if(F(n)&&(n.key===e||n.key===t||R(n.key)&&n.key.value===t))return n}c($e,"findPair");class ne extends Ws{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ce,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=c((l,u)=>{if(typeof r=="function")u=r.call(t,l,u);else if(Array.isArray(r)&&!r.includes(l))return;(u!==void 0||i)&&o.items.push(Ln(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;F(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Q(e,e?.value):n=new Q(e.key,e.value);const i=$e(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);R(i.value)&&qs(n.value)?i.value.value=n.value:i.value=n.value}else if(r){const o=this.items.findIndex(a=>r(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=$e(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=$e(this.items,e)?.value;return(!t&&R(i)?i.value:i)??void 0}has(e){return!!$e(this.items,e)}set(e,t){this.add(new Q(e,t),!0)}toJSON(e,t,n){const i=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)zs(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!F(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})),Qs(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const We={collection:"map",default:!0,nodeClass:ne,tag:"tag:yaml.org,2002:map",resolve(s,e){return Ke(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ne.from(s,e,t),"createNode")};class ve extends Ws{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Re,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Mt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Mt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&R(i)?i.value:i}has(e){const t=Mt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Mt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];R(i)&&qs(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(re(r,String(i++),t));return n}toString(e,t,n){return e?Qs(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 l=t instanceof Set?a:String(o++);a=i.call(t,l,a)}r.items.push(rt(a,void 0,n))}}return r}}function Mt(s){let e=R(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Mt,"asItemIndex");const Je={collection:"seq",default:!0,nodeClass:ve,tag:"tag:yaml.org,2002:seq",resolve(s,e){return _e(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>ve.from(s,e,t),"createNode")},Rt={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),ct(s,e,t,n)}},Kt={identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new L(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Kt.test.test(s)?s:e.options.nullStr,"stringify")},Pn={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Pn.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 oe({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}c(oe,"stringifyNumber");const Xs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:oe},Zs={identify:c(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:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():oe(s)}},ei={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:oe},_t=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),xn=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function ti(s,e,t){const{value:n}=s;return _t(n)&&n>=0?t+n.toString(e):oe(s)}c(ti,"intStringify$1");const ni={identify:c(s=>_t(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>xn(s,2,8,t),"resolve"),stringify:c(s=>ti(s,8,"0o"),"stringify")},si={identify:_t,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>xn(s,0,10,t),"resolve"),stringify:oe},ii={identify:c(s=>_t(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>xn(s,2,16,t),"resolve"),stringify:c(s=>ti(s,16,"0x"),"stringify")},xo=[We,Je,Rt,Kt,Pn,ni,si,ii,Xs,Zs,ei];function ri(s){return typeof s=="bigint"||Number.isInteger(s)}c(ri,"intIdentify$1");const jt=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Do=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:jt},{identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:jt},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:jt},{identify:ri,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>ri(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(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:c(s=>parseFloat(s),"resolve"),stringify:jt}],Mo={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Ro=[We,Je].concat(Do,Mo),Dn={identify:c(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 l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),p=new Array(u);for(let h=0,f=0;h<u;++h,f+=l)p[h]=a.substr(f,l);a=p.join(e===L.BLOCK_LITERAL?`
53
- `:" ")}return ct({comment:s,type:e,value:a},n,i,r)}};function oi(s,e){if(_e(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!F(n)){if(Ke(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
52
+ ${i}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}c(Oo,"stringifyFlowCollection");function Rt({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())}}c(Rt,"addCommentBefore");function Oe(s,e){const t=R(e)?e.value:e;for(const n of s)if(F(n)&&(n.key===e||n.key===t||R(n.key)&&n.key.value===t))return n}c(Oe,"findPair");class ne extends Fs{static{c(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=c((l,u)=>{if(typeof r=="function")u=r.call(t,l,u);else if(Array.isArray(r)&&!r.includes(l))return;(u!==void 0||i)&&o.items.push($n(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;F(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=Oe(this.items,n.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${n.key} already set`);R(i.value)&&Ks(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=Oe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=Oe(this.items,e)?.value;return(!t&&R(i)?i.value:i)??void 0}has(e){return!!Oe(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)Js(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!F(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})),Gs(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const qe={collection:"map",default:!0,nodeClass:ne,tag:"tag:yaml.org,2002:map",resolve(s,e){return Re(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ne.from(s,e,t),"createNode")};class ke extends Fs{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Me,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=_t(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=_t(e);if(typeof n!="number")return;const i=this.items[n];return!t&&R(i)?i.value:i}has(e){const t=_t(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=_t(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];R(i)&&Ks(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(re(r,String(i++),t));return n}toString(e,t,n){return e?Gs(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 l=t instanceof Set?a:String(o++);a=i.call(t,l,a)}r.items.push(it(a,void 0,n))}}return r}}function _t(s){let e=R(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(_t,"asItemIndex");const We={collection:"seq",default:!0,nodeClass:ke,tag:"tag:yaml.org,2002:seq",resolve(s,e){return _e(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>ke.from(s,e,t),"createNode")},Kt={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),at(s,e,t,n)}},Ft={identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new L(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Ft.test.test(s)?s:e.options.nullStr,"stringify")},Ln={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Ln.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}c(ae,"stringifyNumber");const Vs={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},Hs={identify:c(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:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Ys={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ae},jt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Dn=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function zs(s,e,t){const{value:n}=s;return jt(n)&&n>=0?t+n.toString(e):ae(s)}c(zs,"intStringify$1");const Qs={identify:c(s=>jt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>Dn(s,2,8,t),"resolve"),stringify:c(s=>zs(s,8,"0o"),"stringify")},Xs={identify:jt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>Dn(s,0,10,t),"resolve"),stringify:ae},Zs={identify:c(s=>jt(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>Dn(s,2,16,t),"resolve"),stringify:c(s=>zs(s,16,"0x"),"stringify")},$o=[qe,We,Kt,Ft,Ln,Qs,Xs,Zs,Vs,Hs,Ys];function ei(s){return typeof s=="bigint"||Number.isInteger(s)}c(ei,"intIdentify$1");const Bt=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Lo=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Bt},{identify:c(s=>s==null,"identify"),createNode:c(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Bt},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:Bt},{identify:ei,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>ei(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(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:c(s=>parseFloat(s),"resolve"),stringify:Bt}],Do={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Po=[qe,We].concat(Lo,Do),Pn={identify:c(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 l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),p=new Array(u);for(let d=0,h=0;d<u;++d,h+=l)p[d]=a.substr(h,l);a=p.join(e===L.BLOCK_LITERAL?`
53
+ `:" ")}return at({comment:s,type:e,value:a},n,i,r)}};function ti(s,e){if(_e(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!F(n)){if(Re(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Q(new L(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
54
54
  ${i.key.commentBefore}`:n.commentBefore),n.comment){const r=i.value??i.key;r.comment=r.comment?`${n.comment}
55
- ${r.comment}`:n.comment}n=i}s.items[t]=F(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}c(oi,"resolvePairs");function ai(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,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=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],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(Ln(a,l,t))}return i}c(ai,"createPairs");const Mn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:oi,createNode:ai};class ze extends ve{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ne.prototype.add.bind(this),this.delete=ne.prototype.delete.bind(this),this.get=ne.prototype.get.bind(this),this.has=ne.prototype.has.bind(this),this.set=ne.prototype.set.bind(this),this.tag=ze.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(F(i)?(r=re(i.key,"",t),o=re(i.value,r,t)):r=re(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=ai(e,t,n),r=new this;return r.items=i.items,r}}ze.tag="tag:yaml.org,2002:omap";const Rn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=oi(s,e),n=[];for(const{key:i}of t.items)R(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new ze,t)},createNode:c((s,e,t)=>ze.from(s,e,t),"createNode")};function ci({value:s,source:e},t){return e&&(s?li:ui).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(ci,"boolStringify");const li={identify:c(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:c(()=>new L(!0),"resolve"),stringify:ci},ui={identify:c(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:c(()=>new L(!1),"resolve"),stringify:ci},Ko={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:oe},_o={identify:c(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:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():oe(s)}},jo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:oe},lt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Ft(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}c(Ft,"intResolve");function Kn(s,e,t){const{value:n}=s;if(lt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return oe(s)}c(Kn,"intStringify");const Fo={identify:lt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Ft(s,2,2,t),"resolve"),stringify:c(s=>Kn(s,2,"0b"),"stringify")},Bo={identify:lt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Ft(s,1,8,t),"resolve"),stringify:c(s=>Kn(s,8,"0"),"stringify")},Uo={identify:lt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Ft(s,0,10,t),"resolve"),stringify:oe},qo={identify:lt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Ft(s,2,16,t),"resolve"),stringify:c(s=>Kn(s,16,"0x"),"stringify")};class Qe extends ne{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Qe.tag}add(e){let t;F(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Q(e.key,null):t=new Q(e,null),$e(this.items,t.key)||this.items.push(t)}get(e,t){const n=$e(this.items,e);return!t&&F(n)?R(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=$e(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Q(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw new Error("Set items must all have null values")}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(Ln(o,null,n));return r}}Qe.tag="tag:yaml.org,2002:set";const _n={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Qe,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Qe.from(s,e,t),"createNode"),resolve(s,e){if(Ke(s)){if(s.hasAllNullValues(!0))return Object.assign(new Qe,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function jn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(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}c(jn,"parseSexagesimal");function fi(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return oe(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*$/,"")}c(fi,"stringifySexagesimal");const hi={identify:c(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:c((s,e,{intAsBigInt:t})=>jn(s,t),"resolve"),stringify:fi},di={identify:c(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:c(s=>jn(s,!1),"resolve"),stringify:fi},Bt={identify:c(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(Bt.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),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let h=jn(p,!1);Math.abs(h)<30&&(h*=60),u-=6e4*h}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},pi=[We,Je,Rt,Kt,li,ui,Fo,Bo,Uo,qo,Ko,_o,jo,Dn,me,Rn,Mn,_n,hi,di,Bt],mi=new Map([["core",xo],["failsafe",[We,Je,Rt]],["json",Ro],["yaml11",pi],["yaml-1.1",pi]]),gi={binary:Dn,bool:Pn,float:ei,floatExp:Zs,floatNaN:Xs,floatTime:di,int:si,intHex:ii,intOct:ni,intTime:hi,map:We,merge:me,null:Kt,omap:Rn,pairs:Mn,seq:Je,set:_n,timestamp:Bt},Wo={"tag:yaml.org,2002:binary":Dn,"tag:yaml.org,2002:merge":me,"tag:yaml.org,2002:omap":Rn,"tag:yaml.org,2002:pairs":Mn,"tag:yaml.org,2002:set":_n,"tag:yaml.org,2002:timestamp":Bt};function Fn(s,e,t){const n=mi.get(e);if(n&&!s)return t&&!n.includes(me)?n.concat(me):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(mi.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(me)),i.reduce((r,o)=>{const a=typeof o=="string"?gi[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(gi).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(Fn,"getTags");const Jo=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Qt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Fn(e,"compat"):e?Fn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?Wo:{},this.tags=Fn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ce,{value:We}),Object.defineProperty(this,fe,{value:Rt}),Object.defineProperty(this,Re,{value:Je}),this.sortMapEntries=typeof o=="function"?o:o===!0?Jo:null}clone(){const e=Object.create(Qt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Go(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Vs(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(pe(l,""))}let o=!1,a=null;if(s.contents){if(W(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(pe(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=qe(s.contents,i,()=>a=null,l);a&&(u+=Oe(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(qe(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
56
- `)?(t.push("..."),t.push(pe(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(pe(r(l),"")))}return t.join(`
55
+ ${r.comment}`:n.comment}n=i}s.items[t]=F(n)?n:new Q(n)}}else e("Expected a sequence for this tag");return s}c(ti,"resolvePairs");function ni(s,e,t){const{replacer:n}=t,i=new ke(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,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=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],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push($n(a,l,t))}return i}c(ni,"createPairs");const xn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:ti,createNode:ni};class Ye extends ke{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ne.prototype.add.bind(this),this.delete=ne.prototype.delete.bind(this),this.get=ne.prototype.get.bind(this),this.has=ne.prototype.has.bind(this),this.set=ne.prototype.set.bind(this),this.tag=Ye.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(F(i)?(r=re(i.key,"",t),o=re(i.value,r,t)):r=re(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=ni(e,t,n),r=new this;return r.items=i.items,r}}Ye.tag="tag:yaml.org,2002:omap";const Mn={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=ti(s,e),n=[];for(const{key:i}of t.items)R(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new Ye,t)},createNode:c((s,e,t)=>Ye.from(s,e,t),"createNode")};function si({value:s,source:e},t){return e&&(s?ii:ri).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(si,"boolStringify");const ii={identify:c(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:c(()=>new L(!0),"resolve"),stringify:si},ri={identify:c(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:c(()=>new L(!1),"resolve"),stringify:si},xo={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ae},Mo={identify:c(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:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ae(s)}},Ro={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ae},ct=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Ut(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}c(Ut,"intResolve");function Rn(s,e,t){const{value:n}=s;if(ct(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return ae(s)}c(Rn,"intStringify");const _o={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Ut(s,2,2,t),"resolve"),stringify:c(s=>Rn(s,2,"0b"),"stringify")},Ko={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Ut(s,1,8,t),"resolve"),stringify:c(s=>Rn(s,8,"0"),"stringify")},Fo={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Ut(s,0,10,t),"resolve"),stringify:ae},jo={identify:ct,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Ut(s,2,16,t),"resolve"),stringify:c(s=>Rn(s,16,"0x"),"stringify")};class ze extends ne{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=ze.tag}add(e){let t;F(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),Oe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Oe(this.items,e);return!t&&F(n)?R(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=Oe(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($n(o,null,n));return r}}ze.tag="tag:yaml.org,2002:set";const _n={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>ze.from(s,e,t),"createNode"),resolve(s,e){if(Re(s)){if(s.hasAllNullValues(!0))return Object.assign(new ze,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Kn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=c(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}c(Kn,"parseSexagesimal");function oi(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(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*$/,"")}c(oi,"stringifySexagesimal");const ai={identify:c(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:c((s,e,{intAsBigInt:t})=>Kn(s,t),"resolve"),stringify:oi},ci={identify:c(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:c(s=>Kn(s,!1),"resolve"),stringify:oi},qt={identify:c(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(qt.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),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,l);const p=e[8];if(p&&p!=="Z"){let d=Kn(p,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},li=[qe,We,Kt,Ft,ii,ri,_o,Ko,Fo,jo,xo,Mo,Ro,Pn,ge,Mn,xn,_n,ai,ci,qt],ui=new Map([["core",$o],["failsafe",[qe,We,Kt]],["json",Po],["yaml11",li],["yaml-1.1",li]]),fi={binary:Pn,bool:Ln,float:Ys,floatExp:Hs,floatNaN:Vs,floatTime:ci,int:Xs,intHex:Zs,intOct:Qs,intTime:ai,map:qe,merge:ge,null:Ft,omap:Mn,pairs:xn,seq:We,set:_n,timestamp:qt},Bo={"tag:yaml.org,2002:binary":Pn,"tag:yaml.org,2002:merge":ge,"tag:yaml.org,2002:omap":Mn,"tag:yaml.org,2002:pairs":xn,"tag:yaml.org,2002:set":_n,"tag:yaml.org,2002:timestamp":qt};function Fn(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"?fi[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(fi).map(p=>JSON.stringify(p)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}c(Fn,"getTags");const Uo=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Zt{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Fn(e,"compat"):e?Fn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?Bo:{},this.tags=Fn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:qe}),Object.defineProperty(this,he,{value:Kt}),Object.defineProperty(this,Me,{value:We}),this.sortMapEntries=typeof o=="function"?o:o===!0?Uo:null}clone(){const e=Object.create(Zt.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function qo(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=Us(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=r(s.commentBefore);t.unshift(me(l,""))}let o=!1,a=null;if(s.contents){if(q(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const p=r(s.contents.commentBefore);t.push(me(p,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=Ue(s.contents,i,()=>a=null,l);a&&(u+=Ae(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(s.contents,i));if(s.directives?.docEnd)if(s.comment){const l=r(s.comment);l.includes(`
56
+ `)?(t.push("..."),t.push(me(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(me(r(l),"")))}return t.join(`
57
57
  `)+`
58
- `}c(Go,"stringifyDocument");class Xe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:In});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 Z({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Xe.prototype,{[ie]:{value:In}});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){Ge(this.contents)&&this.contents.add(e)}addIn(e,t){Ge(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Bs(this);e.anchor=!t||n.has(t)?Us(t||"a",n):t}return new It(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=c(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:h,setAnchors:f,sourceObjects:g}=So(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:h,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},d=rt(e,p,w);return a&&q(d)&&(d.flow=!0),f(),d}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Q(i,r)}delete(e){return Ge(this.contents)?this.contents.delete(e):!1}deleteIn(e){return ot(e)?this.contents==null?!1:(this.contents=null,!0):Ge(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return q(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return ot(e)?!t&&R(this.contents)?this.contents.value:this.contents:q(this.contents)?this.contents.getIn(e,t):void 0}has(e){return q(this.contents)?this.contents.has(e):!1}hasIn(e){return ot(e)?this.contents!==void 0:q(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Nt(this.schema,[e],t):Ge(this.contents)&&this.contents.set(e,t)}setIn(e,t){ot(e)?this.contents=t:this.contents==null?this.contents=Nt(this.schema,Array.from(e),t):Ge(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 Z({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 Z({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 Qt(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},l=re(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:p}of a.anchors.values())r(p,u);return typeof o=="function"?Be(o,{"":l},"",l):l}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 Go(this,e)}}function Ge(s){if(q(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Ge,"assertCollection");class Bn extends Error{static{c(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class Le extends Bn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class yi extends Bn{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Ut=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
58
+ `}c(qo,"stringifyDocument");class Qe{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ie,{value:En});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 Z({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(Qe.prototype,{[ie]:{value:En}});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=q(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Je(this.contents)&&this.contents.add(e)}addIn(e,t){Je(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Rs(this);e.anchor=!t||n.has(t)?_s(t||"a",n):t}return new Nt(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=c(v=>typeof v=="number"||v instanceof String||v instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:p}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=yo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:g},f=it(e,p,w);return a&&U(f)&&(f.flow=!0),h(),f}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 Je(this.contents)?this.contents.delete(e):!1}deleteIn(e){return rt(e)?this.contents==null?!1:(this.contents=null,!0):Je(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return U(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return rt(e)?!t&&R(this.contents)?this.contents.value:this.contents:U(this.contents)?this.contents.getIn(e,t):void 0}has(e){return U(this.contents)?this.contents.has(e):!1}hasIn(e){return rt(e)?this.contents!==void 0:U(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ot(this.schema,[e],t):Je(this.contents)&&this.contents.set(e,t)}setIn(e,t){rt(e)?this.contents=t:this.contents==null?this.contents=Ot(this.schema,Array.from(e),t):Je(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 Z({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 Z({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 Zt(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},l=re(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:p}of a.anchors.values())r(p,u);return typeof o=="function"?je(o,{"":l},"",l):l}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 qo(this,e)}}function Je(s){if(U(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Je,"assertCollection");class jn extends Error{static{c(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class $e extends jn{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class hi extends jn{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Wt=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
59
  `),o=a+o}if(/[^ ]/.test(o)){let a=1;const l=t.linePos[1];l&&l.line===n&&l.col>i&&(a=Math.max(1,Math.min(l.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
60
60
 
61
61
  ${o}
62
62
  ${u}
63
- `}},"prettifyError");function Ve(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let l=!1,u=a,p=a,h="",f="",g=!1,w=!1,d=null,y=null,C=null,v=null,A=null,E=null,O=null;for(const N of s)switch(w&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&r(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),d&&(u&&N.type!=="comment"&&N.type!=="newline"&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),d=null),N.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&N.source.includes(" ")&&(d=N),p=!0;break;case"comment":{p||r(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const V=N.source.substring(1)||" ";h?h+=f+V:h=V,f="",u=!1;break}case"newline":u?h?h+=N.source:(!E||t!=="seq-item-ind")&&(l=!0):f+=N.source,u=!0,g=!0,(y||C)&&(v=N),p=!0;break;case"anchor":y&&r(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&r(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=N,O??(O=N.offset),u=!1,p=!1,w=!0;break;case"tag":{C&&r(N,"MULTIPLE_TAGS","A node can have at most one tag"),C=N,O??(O=N.offset),u=!1,p=!1,w=!0;break}case t:(y||C)&&r(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),E&&r(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),E=N,u=t==="seq-item-ind"||t==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&r(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=N,u=!1,p=!1;break}default:r(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),u=!1,p=!1}const $=s[s.length-1],K=$?$.offset+$.source.length:i;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&r(n.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),d&&(u&&d.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(d,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:E,spaceBefore:l,comment:h,hasNewline:g,anchor:y,tag:C,newlineAfterProp:v,end:K,start:O??K}}c(Ve,"resolveProps");function ut(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(ut(e.key)||ut(e.value))return!0}return!1;default:return!0}}c(ut,"containsNewline");function Un(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&ut(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Un,"flowIndentCheck");function wi(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||R(r)&&R(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}c(wi,"mapIncludes");const bi="All mapping items must start at the same column";function Vo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ne,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const p of n.items){const{start:h,key:f,sep:g,value:w}=p,d=Ve(h,{indicator:"explicit-key-ind",next:f??g?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!d.found;if(y){if(f&&(f.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==n.indent&&i(l,"BAD_INDENT",bi)),!d.anchor&&!d.tag&&!g){u=d.end,d.comment&&(a.comment?a.comment+=`
65
- `+d.comment:a.comment=d.comment);continue}(d.newlineAfterProp||ut(f))&&i(f??h[h.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else d.found?.indent!==n.indent&&i(l,"BAD_INDENT",bi);t.atKey=!0;const C=d.end,v=f?s(t,f,d,i):e(t,C,h,null,d,i);t.schema.compat&&Un(n.indent,f,i),t.atKey=!1,wi(t,a.items,v)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=Ve(g??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&d.start<A.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const E=w?s(t,w,A,i):e(t,l,g,null,A,i);t.schema.compat&&Un(n.indent,w,i),l=E.range[2];const O=new Q(v,E);t.options.keepSourceTokens&&(O.srcToken=p),a.items.push(O)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(v.comment?v.comment+=`
66
- `+A.comment:v.comment=A.comment);const E=new Q(v);t.options.keepSourceTokens&&(E.srcToken=p),a.items.push(E)}}return u&&u<l&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Vo,"resolveBlockMap");function Ho({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 l=n.offset,u=null;for(const{start:p,value:h}of n.items){const f=Ve(p,{indicator:"seq-item-ind",next:h,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||h)h&&h.type==="block-seq"?i(f.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{u=f.end,f.comment&&(a.comment=f.comment);continue}const g=h?s(t,h,f,i):e(t,f.end,p,null,f,i);t.schema.compat&&Un(n.indent,h,i),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Ho,"resolveBlockSeq");function ft(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:l,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 p=l.substring(1)||" ";i?i+=o+p:i=p,o="";break}case"newline":i&&(o+=l),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:i,offset:e}}c(ft,"resolveEnd");const qn="Block collections are not allowed within flow collections",Wn=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Yo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=r?.nodeClass??(o?ne:ve),u=new l(t.schema);u.flow=!0;const p=t.atRoot;p&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let h=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:v,key:A,sep:E,value:O}=C,$=Ve(v,{flow:a,indicator:"explicit-key-ind",next:A??E?.[0],offset:h,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!E&&!O){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
- `+$.comment:u.comment=$.comment),h=$.end;continue}!o&&t.options.strict&&ut(A)&&i(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let K="";e:for(const N of v)switch(N.type){case"comma":case"space":break;case"comment":K=N.source.substring(1);break e;default:break e}if(K){let N=u.items[u.items.length-1];F(N)&&(N=N.value??N.key),N.comment?N.comment+=`
68
- `+K:N.comment=K,$.comment=$.comment.substring(K.length+1)}}if(!o&&!E&&!$.found){const K=O?s(t,O,$,i):e(t,$.end,E,null,$,i);u.items.push(K),h=K.range[2],Wn(O)&&i(K.range,"BLOCK_IN_FLOW",qn)}else{t.atKey=!0;const K=$.end,N=A?s(t,A,$,i):e(t,K,v,null,$,i);Wn(A)&&i(N.range,"BLOCK_IN_FLOW",qn),t.atKey=!1;const V=Ve(E??[],{flow:a,indicator:"map-value-ind",next:O,offset:N.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(V.found){if(!o&&!$.found&&t.options.strict){if(E)for(const H of E){if(H===V.found)break;if(H.type==="newline"){i(H,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<V.found.offset-1024&&i(V.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else O&&("source"in O&&O.source&&O.source[0]===":"?i(O,"MISSING_CHAR",`Missing space after : in ${a}`):i(V.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ge=O?s(t,O,V,i):V.found?e(t,V.end,E,null,V,i):null;ge?Wn(O)&&i(ge.range,"BLOCK_IN_FLOW",qn):V.comment&&(N.comment?N.comment+=`
69
- `+V.comment:N.comment=V.comment);const xe=new Q(N,ge);if(t.options.keepSourceTokens&&(xe.srcToken=C),o){const H=u;wi(t,H.items,N)&&i(K,"DUPLICATE_KEY","Map keys must be unique"),H.items.push(xe)}else{const H=new ne(t.schema);H.flow=!0,H.items.push(xe);const is=(ge??N).range;H.range=[N.range[0],is[1],is[2]],u.items.push(H)}h=ge?ge.range[2]:V.end}}const f=o?"}":"]",[g,...w]=n.end;let d=h;if(g&&g.source===f)d=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=p?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;i(h,p?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=ft(w,d,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
- `+y.comment:u.comment=y.comment),u.range=[n.offset,d,y.offset]}else u.range=[n.offset,d,d];return u}c(Yo,"resolveFlowCollection");function Jn(s,e,t,n,i,r){const o=t.type==="block-map"?Vo(s,e,t,n,r):t.type==="block-seq"?Ho(s,e,t,n,r):Yo(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}c(Jn,"resolveCollection");function zo(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,f=>i(r,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){const{anchor:f,newlineAfterProp:g}=n,w=f&&r?f.offset>r.offset?f:r:f??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===ne.tagName&&a==="map"||o===ve.tagName&&a==="seq")return Jn(s,e,t,i,o);let l=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!l){const f=e.schema.knownTags[o];if(f&&f.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?i(r,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Jn(s,e,t,i,o)}const u=Jn(s,e,t,i,o,l),p=l.resolve?.(u,f=>i(r,"TAG_RESOLVE_FAILED",f),e.options)??u,h=W(p)?p:new L(p);return h.range=u.range,h.tag=o,l?.format&&(h.format=l.format),h}c(zo,"composeCollection");function Si(s,e,t){const n=e.offset,i=Qo(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?Xo(e.source):[];let a=o.length;for(let d=o.length-1;d>=0;--d){const y=o[d][1];if(y===""||y==="\r")a=d;else break}if(a===0){const d=i.chomp==="+"&&o.length>0?`
71
- `.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:d,type:r,comment:i.comment,range:[n,y,y]}}let l=e.indent+i.indent,u=e.offset+i.length,p=0;for(let d=0;d<a;++d){const[y,C]=o[d];if(C===""||C==="\r")i.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=y.length),p=d,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+C.length+1}for(let d=o.length-1;d>=a;--d)o[d][0].length>l&&(a=d+1);let h="",f="",g=!1;for(let d=0;d<p;++d)h+=o[d][0].slice(l)+`
72
- `;for(let d=p;d<a;++d){let[y,C]=o[d];u+=y.length+C.length+1;const v=C[C.length-1]==="\r";if(v&&(C=C.slice(0,-1)),C&&y.length<l){const E=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(v?2:1),"BAD_INDENT",E),y=""}r===L.BLOCK_LITERAL?(h+=f+y.slice(l)+C,f=`
73
- `):y.length>l||C[0]===" "?(f===" "?f=`
74
- `:!g&&f===`
75
- `&&(f=`
76
-
77
- `),h+=f+y.slice(l)+C,f=`
78
- `,g=!0):C===""?f===`
79
- `?h+=`
80
- `:f=`
81
- `:(h+=f+C,f=" ",g=!1)}switch(i.chomp){case"-":break;case"+":for(let d=a;d<o.length;++d)h+=`
82
- `+o[d][0].slice(l);h[h.length-1]!==`
83
- `&&(h+=`
84
- `);break;default:h+=`
85
- `}const w=n+i.length+e.source.length;return{value:h,type:r,comment:i.comment,range:[n,w,w]}}c(Si,"resolveBlockScalar");function Qo({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="",l=-1;for(let f=1;f<i.length;++f){const g=i[f];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:l===-1&&(l=s+f)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,p="",h=i.length;for(let f=1;f<e.length;++f){const g=e[f];switch(g.type){case"space":u=!0;case"newline":h+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),h+=g.source.length,p=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),h+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const d=g.source;d&&typeof d=="string"&&(h+=d.length)}}}return{mode:r,indent:o,chomp:a,comment:p,length:h}}c(Qo,"parseBlockScalarHeader");function Xo(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}c(Xo,"splitLines");function Ci(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,l;const u=c((f,g,w)=>t(n+f,g,w),"_onError");switch(i){case"scalar":a=L.PLAIN,l=Zo(r,u);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,l=ea(r,u);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,l=ta(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 p=n+r.length,h=ft(o,p,e,t);return{value:l,type:a,comment:h.comment,range:[n,p,h.offset]}}c(Ci,"resolveFlowScalar");function Zo(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}`),ki(s)}c(Zo,"plainValue");function ea(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),ki(s.slice(1,-1)).replace(/''/g,"'")}c(ea,"singleQuotedValue");function ki(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
63
+ `}},"prettifyError");function Ge(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let l=!1,u=a,p=a,d="",h="",g=!1,w=!1,f=null,y=null,C=null,v=null,A=null,I=null,O=null;for(const N of s)switch(w&&(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma"&&r(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),f&&(u&&N.type!=="comment"&&N.type!=="newline"&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),N.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&N.source.includes(" ")&&(f=N),p=!0;break;case"comment":{p||r(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const H=N.source.substring(1)||" ";d?d+=h+H:d=H,h="",u=!1;break}case"newline":u?d?d+=N.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=N.source,u=!0,g=!0,(y||C)&&(v=N),p=!0;break;case"anchor":y&&r(N,"MULTIPLE_ANCHORS","A node can have at most one anchor"),N.source.endsWith(":")&&r(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=N,O??(O=N.offset),u=!1,p=!1,w=!0;break;case"tag":{C&&r(N,"MULTIPLE_TAGS","A node can have at most one tag"),C=N,O??(O=N.offset),u=!1,p=!1,w=!0;break}case t:(y||C)&&r(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`),I&&r(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${e??"collection"}`),I=N,u=t==="seq-item-ind"||t==="explicit-key-ind",p=!1;break;case"comma":if(e){A&&r(N,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=N,u=!1,p=!1;break}default:r(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),u=!1,p=!1}const $=s[s.length-1],_=$?$.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"),f&&(u&&f.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:I,spaceBefore:l,comment:d,hasNewline:g,anchor:y,tag:C,newlineAfterProp:v,end:_,start:O??_}}c(Ge,"resolveProps");function lt(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(lt(e.key)||lt(e.value))return!0}return!1;default:return!0}}c(lt,"containsNewline");function Bn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&lt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Bn,"flowIndentCheck");function di(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||R(r)&&R(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}c(di,"mapIncludes");const pi="All mapping items must start at the same column";function Wo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ne,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const p of n.items){const{start:d,key:h,sep:g,value:w}=p,f=Ge(d,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?i(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&i(l,"BAD_INDENT",pi)),!f.anchor&&!f.tag&&!g){u=f.end,f.comment&&(a.comment?a.comment+=`
65
+ `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||lt(h))&&i(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==n.indent&&i(l,"BAD_INDENT",pi);t.atKey=!0;const C=f.end,v=h?s(t,h,f,i):e(t,C,d,null,f,i);t.schema.compat&&Bn(n.indent,h,i),t.atKey=!1,di(t,a.items,v)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const A=Ge(g??[],{indicator:"map-value-ind",next:w,offset:v.range[2],onError:i,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&i(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<A.found.offset-1024&&i(v.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=w?s(t,w,A,i):e(t,l,g,null,A,i);t.schema.compat&&Bn(n.indent,w,i),l=I.range[2];const O=new Q(v,I);t.options.keepSourceTokens&&(O.srcToken=p),a.items.push(O)}else{y&&i(v.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(v.comment?v.comment+=`
66
+ `+A.comment:v.comment=A.comment);const I=new Q(v);t.options.keepSourceTokens&&(I.srcToken=p),a.items.push(I)}}return u&&u<l&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(Wo,"resolveBlockMap");function Jo({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??ke,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:p,value:d}of n.items){const h=Ge(p,{indicator:"seq-item-ind",next:d,offset:l,onError:i,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d&&d.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=d?s(t,d,h,i):e(t,h.end,p,null,h,i);t.schema.compat&&Bn(n.indent,d,i),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Jo,"resolveBlockSeq");function ut(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:l,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 p=l.substring(1)||" ";i?i+=o+p:i=p,o="";break}case"newline":i&&(o+=l),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:i,offset:e}}c(ut,"resolveEnd");const Un="Block collections are not allowed within flow collections",qn=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Go({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=r?.nodeClass??(o?ne:ke),u=new l(t.schema);u.flow=!0;const p=t.atRoot;p&&(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 C=n.items[y],{start:v,key:A,sep:I,value:O}=C,$=Ge(v,{flow:a,indicator:"explicit-key-ind",next:A??I?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!I&&!O){y===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
+ `+$.comment:u.comment=$.comment),d=$.end;continue}!o&&t.options.strict&&lt(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 _="";e:for(const N of v)switch(N.type){case"comma":case"space":break;case"comment":_=N.source.substring(1);break e;default:break e}if(_){let N=u.items[u.items.length-1];F(N)&&(N=N.value??N.key),N.comment?N.comment+=`
68
+ `+_:N.comment=_,$.comment=$.comment.substring(_.length+1)}}if(!o&&!I&&!$.found){const _=O?s(t,O,$,i):e(t,$.end,I,null,$,i);u.items.push(_),d=_.range[2],qn(O)&&i(_.range,"BLOCK_IN_FLOW",Un)}else{t.atKey=!0;const _=$.end,N=A?s(t,A,$,i):e(t,_,v,null,$,i);qn(A)&&i(N.range,"BLOCK_IN_FLOW",Un),t.atKey=!1;const H=Ge(I??[],{flow:a,indicator:"map-value-ind",next:O,offset:N.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(H.found){if(!o&&!$.found&&t.options.strict){if(I)for(const Y of I){if(Y===H.found)break;if(Y.type==="newline"){i(Y,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<H.found.offset-1024&&i(H.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else O&&("source"in O&&O.source&&O.source[0]===":"?i(O,"MISSING_CHAR",`Missing space after : in ${a}`):i(H.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ye=O?s(t,O,H,i):H.found?e(t,H.end,I,null,H,i):null;ye?qn(O)&&i(ye.range,"BLOCK_IN_FLOW",Un):H.comment&&(N.comment?N.comment+=`
69
+ `+H.comment:N.comment=H.comment);const De=new Q(N,ye);if(t.options.keepSourceTokens&&(De.srcToken=C),o){const Y=u;di(t,Y.items,N)&&i(_,"DUPLICATE_KEY","Map keys must be unique"),Y.items.push(De)}else{const Y=new ne(t.schema);Y.flow=!0,Y.items.push(De);const ns=(ye??N).range;Y.range=[N.range[0],ns[1],ns[2]],u.items.push(Y)}d=ye?ye.range[2]:H.end}}const h=o?"}":"]",[g,...w]=n.end;let f=d;if(g&&g.source===h)f=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=p?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;i(d,p?"MISSING_CHAR":"BAD_INDENT",C),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=ut(w,f,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
+ `+y.comment:u.comment=y.comment),u.range=[n.offset,f,y.offset]}else u.range=[n.offset,f,f];return u}c(Go,"resolveFlowCollection");function Wn(s,e,t,n,i,r){const o=t.type==="block-map"?Wo(s,e,t,n,r):t.type==="block-seq"?Jo(s,e,t,n,r):Go(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}c(Wn,"resolveCollection");function Vo(s,e,t,n,i){const r=n.tag,o=r?e.directives.tagName(r.source,h=>i(r,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,w=h&&r?h.offset>r.offset?h:r:h??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===ne.tagName&&a==="map"||o===ke.tagName&&a==="seq")return Wn(s,e,t,i,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?i(r,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Wn(s,e,t,i,o)}const u=Wn(s,e,t,i,o,l),p=l.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,d=q(p)?p:new L(p);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(Vo,"composeCollection");function mi(s,e,t){const n=e.offset,i=Ho(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?Yo(e.source):[];let a=o.length;for(let f=o.length-1;f>=0;--f){const y=o[f][1];if(y===""||y==="\r")a=f;else break}if(a===0){const f=i.chomp==="+"&&o.length>0?`
71
+ `.repeat(Math.max(1,o.length-1)):"";let y=n+i.length;return e.source&&(y+=e.source.length),{value:f,type:r,comment:i.comment,range:[n,y,y]}}let l=e.indent+i.indent,u=e.offset+i.length,p=0;for(let f=0;f<a;++f){const[y,C]=o[f];if(C===""||C==="\r")i.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(l=y.length),p=f,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+C.length+1}for(let f=o.length-1;f>=a;--f)o[f][0].length>l&&(a=f+1);let d="",h="",g=!1;for(let f=0;f<p;++f)d+=o[f][0].slice(l)+`
72
+ `;for(let f=p;f<a;++f){let[y,C]=o[f];u+=y.length+C.length+1;const v=C[C.length-1]==="\r";if(v&&(C=C.slice(0,-1)),C&&y.length<l){const I=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(v?2:1),"BAD_INDENT",I),y=""}r===L.BLOCK_LITERAL?(d+=h+y.slice(l)+C,h=`
73
+ `):y.length>l||C[0]===" "?(h===" "?h=`
74
+ `:!g&&h===`
75
+ `&&(h=`
76
+
77
+ `),d+=h+y.slice(l)+C,h=`
78
+ `,g=!0):C===""?h===`
79
+ `?d+=`
80
+ `:h=`
81
+ `:(d+=h+C,h=" ",g=!1)}switch(i.chomp){case"-":break;case"+":for(let f=a;f<o.length;++f)d+=`
82
+ `+o[f][0].slice(l);d[d.length-1]!==`
83
+ `&&(d+=`
84
+ `);break;default:d+=`
85
+ `}const w=n+i.length+e.source.length;return{value:d,type:r,comment:i.comment,range:[n,w,w]}}c(mi,"resolveBlockScalar");function Ho({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="",l=-1;for(let h=1;h<i.length;++h){const g=i[h];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,p="",d=i.length;for(let h=1;h<e.length;++h){const g=e[h];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,p=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 f=g.source;f&&typeof f=="string"&&(d+=f.length)}}}return{mode:r,indent:o,chomp:a,comment:p,length:d}}c(Ho,"parseBlockScalarHeader");function Yo(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}c(Yo,"splitLines");function gi(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,l;const u=c((h,g,w)=>t(n+h,g,w),"_onError");switch(i){case"scalar":a=L.PLAIN,l=zo(r,u);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,l=Qo(r,u);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,l=Xo(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 p=n+r.length,d=ut(o,p,e,t);return{value:l,type:a,comment:d.comment,range:[n,p,d.offset]}}c(gi,"resolveFlowScalar");function zo(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)}c(zo,"plainValue");function Qo(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,"'")}c(Qo,"singleQuotedValue");function yi(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
86
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
87
87
  `,"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
88
  `?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]??"")}c(ki,"foldLines");function ta(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
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]??"")}c(yi,"foldLines");function Xo(s,e){let t="";for(let n=1;n<s.length-1;++n){const i=s[n];if(!(i==="\r"&&s[n+1]===`
90
90
  `))if(i===`
91
- `){const{fold:r,offset:o}=na(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=sa[r];if(o)t+=o;else if(r===`
91
+ `){const{fold:r,offset:o}=Zo(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=ea[r];if(o)t+=o;else if(r===`
92
92
  `)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+=ia(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!==`
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+=ta(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
94
  `&&!(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}c(ta,"doubleQuotedValue");function na(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
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}c(Xo,"doubleQuotedValue");function Zo(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
96
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
97
97
  `);)n===`
98
98
  `&&(t+=`
99
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(na,"foldNewline");const sa={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 ia(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)}c(ia,"parseCharCode");function vi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Si(s,e,n):Ci(e,s.options.strict,n),l=t?s.directives.tagName(t.source,h=>n(t,"TAG_RESOLVE_FAILED",h)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[fe]:l?u=ra(s.schema,i,l,t,n):e.type==="scalar"?u=oa(s,i,e,n):u=s.schema[fe];let p;try{const h=u.resolve(i,f=>n(t??e,"TAG_RESOLVE_FAILED",f),s.options);p=R(h)?h:new L(h)}catch(h){const f=h instanceof Error?h.message:String(h);n(t??e,"TAG_RESOLVE_FAILED",f),p=new L(i)}return p.range=a,p.source=i,r&&(p.type=r),l&&(p.tag=l),u.format&&(p.format=u.format),o&&(p.comment=o),p}c(vi,"composeScalar");function ra(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])}c(ra,"findScalarTagByName");function oa({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(l=>l.default&&l.test?.test(n))??t[fe];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${l} or ${u}`;r(i,"TAG_RESOLVE_FAILED",p,!0)}}return o}c(oa,"findScalarTagByTest");function aa(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}c(aa,"emptyScalarPosition");const ca={composeNode:Ei,composeEmptyNode:Gn};function Ei(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:l}=t;let u,p=!0;switch(e.type){case"alias":u=la(s,e,n),(a||l)&&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=vi(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=zo(ca,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const h=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",h),u=Gn(s,e.offset,void 0,null,t,n),p=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!R(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(l??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&&p&&(u.srcToken=e),u}c(Ei,"composeNode");function Gn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:l},u){const p={type:"scalar",offset:aa(e,t,n),indent:-1,source:""},h=vi(s,p,a,u);return o&&(h.anchor=o.source.substring(1),h.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(h.spaceBefore=!0),r&&(h.comment=r,h.range[2]=l),h}c(Gn,"composeEmptyNode");function la({options:s},{offset:e,source:t,end:n},i){const r=new It(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=ft(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}c(la,"composeAlias");function ua(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),l=new Xe(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},p=Ve(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!p.hasNewline&&o(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?Ei(u,i,p,o):Gn(u,p.end,n,null,p,o);const h=l.contents.range[2],f=ft(r,h,!1,o);return f.comment&&(l.comment=f.comment),l.range=[t,h,f.offset],l}c(ua,"composeDoc");function ht(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)]}c(ht,"getErrorPos");function Ii(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?`
99
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(Zo,"foldNewline");const ea={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 ta(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)}c(ta,"parseCharCode");function wi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?mi(s,e,n):gi(e,s.options.strict,n),l=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[he]:l?u=na(s.schema,i,l,t,n):e.type==="scalar"?u=sa(s,i,e,n):u=s.schema[he];let p;try{const d=u.resolve(i,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);p=R(d)?d:new L(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),p=new L(i)}return p.range=a,p.source=i,r&&(p.type=r),l&&(p.tag=l),u.format&&(p.format=u.format),o&&(p.comment=o),p}c(wi,"composeScalar");function na(s,e,t,n,i){if(t==="!")return s[he];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[he])}c(na,"findScalarTagByName");function sa({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[he];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[he];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),p=`Value may be parsed as either ${l} or ${u}`;r(i,"TAG_RESOLVE_FAILED",p,!0)}}return o}c(sa,"findScalarTagByTest");function ia(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}c(ia,"emptyScalarPosition");const ra={composeNode:bi,composeEmptyNode:Jn};function bi(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:l}=t;let u,p=!0;switch(e.type){case"alias":u=oa(s,e,n),(a||l)&&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=wi(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Vo(ra,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=Jn(s,e.offset,void 0,null,t,n),p=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!R(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(l??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&&p&&(u.srcToken=e),u}c(bi,"composeNode");function Jn(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:l},u){const p={type:"scalar",offset:ia(e,t,n),indent:-1,source:""},d=wi(s,p,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]=l),d}c(Jn,"composeEmptyNode");function oa({options:s},{offset:e,source:t,end:n},i){const r=new Nt(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=ut(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}c(oa,"composeAlias");function aa(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),l=new Qe(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},p=Ge(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});p.found&&(l.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!p.hasNewline&&o(p.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=i?bi(u,i,p,o):Jn(u,p.end,n,null,p,o);const d=l.contents.range[2],h=ut(r,d,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,d,h.offset],l}c(aa,"composeDoc");function ft(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)]}c(ft,"getErrorPos");function Si(s){let e="",t=!1,n=!1;for(let i=0;i<s.length;++i){const r=s[i];switch(r[0]){case"#":e+=(e===""?"":n?`
101
101
 
102
102
  `:`
103
- `)+(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}}c(Ii,"parsePrelude");class Vn{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=ht(t);r?this.warnings.push(new yi(o,n,i)):this.errors.push(new Le(o,n,i))},this.directives=new Z({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Ii(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
- ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(q(r)&&!r.flow&&r.items.length>0){let o=r.items[0];F(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
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}}c(Si,"parsePrelude");class Gn{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=ft(t);r?this.warnings.push(new hi(o,n,i)):this.errors.push(new $e(o,n,i))},this.directives=new Z({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Si(this.prelude);if(n){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ ${n}`:n;else if(i||e.directives.docStart||!r)e.commentBefore=n;else if(U(r)&&!r.flow&&r.items.length>0){let o=r.items[0];F(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
105
105
  ${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:Ii(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=ht(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=ua(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 Le(ht(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 Le(ht(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=ft(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 Le(ht(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 Xe(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=c((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 Le([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ci(s,e,n);case"block-scalar":return Si({options:{strict:e}},s,n)}}return null}c(fa,"resolveAsScalar");function ha(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=ct({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
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:Si(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=ft(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=aa(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 $e(ft(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 $e(ft(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=ut(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 $e(ft(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 Qe(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 ca(s,e=!0,t){if(s){const n=c((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 $e([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 mi({options:{strict:e}},s,n)}}return null}c(ca,"resolveAsScalar");function la(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=at({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
108
108
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
109
- `),p=a.substring(0,u),h=a.substring(u+1)+`
110
- `,f=[{type:"block-scalar-header",offset:r,indent:n,source:p}];return Ti(f,l)||f.push({type:"newline",offset:-1,indent:n,source:`
111
- `}),{type:"block-scalar",offset:r,indent:n,props:f,source:h}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:l};default:return{type:"scalar",offset:r,indent:n,source:a,end:l}}}c(ha,"createScalarToken");function da(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 l=ct({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":pa(s,l);break;case'"':Hn(s,l,"double-quoted-scalar");break;case"'":Hn(s,l,"single-quoted-scalar");break;default:Hn(s,l,"scalar")}}c(da,"setScalarValue");function pa(s,e){const t=e.indexOf(`
109
+ `),p=a.substring(0,u),d=a.substring(u+1)+`
110
+ `,h=[{type:"block-scalar-header",offset:r,indent:n,source:p}];return Ci(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
111
+ `}),{type:"block-scalar",offset:r,indent:n,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:r,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:l};default:return{type:"scalar",offset:r,indent:n,source:a,end:l}}}c(la,"createScalarToken");function ua(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 l=at({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":fa(s,l);break;case'"':Vn(s,l,"double-quoted-scalar");break;case"'":Vn(s,l,"single-quoted-scalar");break;default:Vn(s,l,"scalar")}}c(ua,"setScalarValue");function fa(s,e){const t=e.indexOf(`
112
112
  `),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}];Ti(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
- `});for(const l of Object.keys(s))l!=="type"&&l!=="offset"&&delete s[l];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}c(pa,"setBlockScalarValue");function Ti(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}c(Ti,"addEndtoBlockProps");function Hn(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})}}}c(Hn,"setFlowScalarValue");const ma=c(s=>"type"in s?qt(s):Wt(s),"stringify$1");function qt(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=qt(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Wt(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Wt(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Wt(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}}}c(qt,"stringifyToken");function Wt({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=qt(e)),t)for(const r of t)i+=r.source;return n&&(i+=qt(n)),i}c(Wt,"stringifyItem");const Yn=Symbol("break visit"),ga=Symbol("skip children"),Ni=Symbol("remove item");function Pe(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Ai(Object.freeze([]),s,e)}c(Pe,"visit"),Pe.BREAK=Yn,Pe.SKIP=ga,Pe.REMOVE=Ni,Pe.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},Pe.parentCollection=(s,e)=>{const t=Pe.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 Ai(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=Ai(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Yn)return Yn;a===Ni&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(Ai,"_visit");const Jt="\uFEFF",Gt="",Vt="",dt="",ya=c(s=>!!s&&"items"in s,"isCollection"),wa=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function ba(s){switch(s){case Jt:return"<BOM>";case Gt:return"<DOC>";case Vt:return"<FLOW_END>";case dt:return"<SCALAR>";default:return JSON.stringify(s)}}c(ba,"prettyToken");function Oi(s){switch(s){case Jt:return"byte-order-mark";case Gt:return"doc-mode";case Vt:return"flow-error-end";case dt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
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}];Ci(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
+ `});for(const l of Object.keys(s))l!=="type"&&l!=="offset"&&delete s[l];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}c(fa,"setBlockScalarValue");function Ci(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}c(Ci,"addEndtoBlockProps");function Vn(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})}}}c(Vn,"setFlowScalarValue");const ha=c(s=>"type"in s?Jt(s):Gt(s),"stringify$1");function Jt(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Jt(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Gt(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Gt(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Gt(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}}}c(Jt,"stringifyToken");function Gt({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=Jt(e)),t)for(const r of t)i+=r.source;return n&&(i+=Jt(n)),i}c(Gt,"stringifyItem");const Hn=Symbol("break visit"),da=Symbol("skip children"),ki=Symbol("remove item");function Le(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),vi(Object.freeze([]),s,e)}c(Le,"visit"),Le.BREAK=Hn,Le.SKIP=da,Le.REMOVE=ki,Le.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},Le.parentCollection=(s,e)=>{const t=Le.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 vi(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=vi(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Hn)return Hn;a===ki&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(vi,"_visit");const Vt="\uFEFF",Ht="",Yt="",ht="",pa=c(s=>!!s&&"items"in s,"isCollection"),ma=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function ga(s){switch(s){case Vt:return"<BOM>";case Ht:return"<DOC>";case Yt:return"<FLOW_END>";case ht:return"<SCALAR>";default:return JSON.stringify(s)}}c(ga,"prettyToken");function Ei(s){switch(s){case Vt:return"byte-order-mark";case Ht:return"doc-mode";case Yt:return"flow-error-end";case ht:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
116
116
  `: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}c(Oi,"tokenType");var Sa=Object.freeze({__proto__:null,BOM:Jt,DOCUMENT:Gt,FLOW_END:Vt,SCALAR:dt,createScalarToken:ha,isCollection:ya,isScalar:wa,prettyToken:ba,resolveAsScalar:fa,setScalarValue:da,stringify:ma,tokenType:Oi,visit:Pe});function ae(s){switch(s){case void 0:case" ":case`
118
- `:case"\r":case" ":return!0;default:return!1}}c(ae,"isEmpty");const $i=new Set("0123456789ABCDEFabcdef"),Ca=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ht=new Set(",[]{}"),ka=new Set(` ,[]{}
119
- \r `),zn=c(s=>!s||ka.has(s),"isNotAnchorChar");class Li{static{c(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===`
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}c(Ei,"tokenType");var ya=Object.freeze({__proto__:null,BOM:Vt,DOCUMENT:Ht,FLOW_END:Yt,SCALAR:ht,createScalarToken:la,isCollection:pa,isScalar:ma,prettyToken:ga,resolveAsScalar:ca,setScalarValue:ua,stringify:ha,tokenType:Ei,visit:Le});function ce(s){switch(s){case void 0:case" ":case`
118
+ `:case"\r":case" ":return!0;default:return!1}}c(ce,"isEmpty");const Ii=new Set("0123456789ABCDEFabcdef"),wa=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),zt=new Set(",[]{}"),ba=new Set(` ,[]{}
119
+ \r `),Yn=c(s=>!s||ba.has(s),"isNotAnchorChar");class Ti{static{c(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
120
  `?!0:t==="\r"?this.buffer[e+1]===`
121
121
  `:!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
122
  `||!i&&!this.atEnd)return e+n+1}return t===`
123
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&ae(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]===Jt&&(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 Gt,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==="...")&&ae(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&&!ae(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===":")&&ae(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(zn),"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("..."))&&ae(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Vt,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(zn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ae(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(`
123
+ `||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]===Vt&&(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 Ht,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(Yn),"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 Yt,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(Yn),"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
125
  `,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=n.indexOf(`
126
- `,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=>ae(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`
126
+ `,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
127
  `:e=r,t=0;break;case"\r":{const o=this.buffer[r+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
128
128
  `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{const r=this.continueScalar(e+1);if(r===-1)break;e=this.buffer.indexOf(`
129
129
  `,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(n=this.buffer[i];n===" ";)n=this.buffer[++i];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
130
130
  `;)n=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let r=e-1,o=this.buffer[r];o==="\r"&&(o=this.buffer[--r]);const a=r;for(;o===" ";)o=this.buffer[--r];if(o===`
131
- `&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield dt,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(ae(r)||e&&Ht.has(r))break;t=n}else if(ae(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
131
+ `&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield ht,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&&zt.has(r))break;t=n}else if(ce(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
132
132
  `?(n+=1,i=`
133
- `,r=this.buffer[n+1]):t=n),r==="#"||e&&Ht.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&&Ht.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield dt,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(zn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ae(t)||e&&Ht.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(;!ae(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(Ca.has(t))t=this.buffer[++e];else if(t==="%"&&$i.has(this.buffer[e+1])&&$i.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===`
133
+ `,r=this.buffer[n+1]):t=n),r==="#"||e&&zt.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&&zt.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ht,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(Yn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ce(t)||e&&zt.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==="%"&&Ii.has(this.buffer[e+1])&&Ii.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
135
  `?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 Pi{static{c(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 Ee(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Ee,"includesToken");function xi(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}c(xi,"findNonEmptyIndex");function Di(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}c(Di,"isFlowToken");function Yt(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[]}}c(Yt,"getPrevProps");function He(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)}c(He,"getFirstKeyStartProps");function Mi(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Ee(e.start,"explicit-key-ind")&&!Ee(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Di(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)}c(Mi,"fixFlowSeqItems");class Qn{static{c(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 Li,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=Oi(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"&&Mi(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&&xi(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":{xi(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=Yt(this.peek(2)),n=He(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(`
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 Ni{static{c(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 ve(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(ve,"includesToken");function Ai(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}c(Ai,"findNonEmptyIndex");function Oi(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}c(Oi,"isFlowToken");function Qt(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[]}}c(Qt,"getPrevProps");function Ve(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)}c(Ve,"getFirstKeyStartProps");function $i(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!ve(e.start,"explicit-key-ind")&&!ve(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Oi(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)}c($i,"fixFlowSeqItems");class zn{static{c(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 Ti,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=Ei(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"&&$i(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&&Ai(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":{Ai(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=Qt(this.peek(2)),n=Ve(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
137
  `)+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 l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(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(Ee(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(Di(t.key)&&!Ee(t.sep,"newline")){const o=He(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(Ee(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=He(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]}):Ee(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&&!Ee(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||Ee(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=Yt(n),r=He(i);Mi(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(`
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 l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ve(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(Oi(t.key)&&!ve(t.sep,"newline")){const o=Ve(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ve(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Ve(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ve(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ve(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ve(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const i=Qt(n),r=Ve(i);$i(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
139
139
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
140
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=Yt(e),n=He(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=Yt(e),n=He(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 Ri(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Pi||null,prettyErrors:e}}c(Ri,"parseOptions");function va(s,e={}){const{lineCounter:t,prettyErrors:n}=Ri(e),i=new Qn(t?.addNewLine),r=new Vn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Ut(s,t)),a.warnings.forEach(Ut(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(va,"parseAllDocuments");function Ki(s,e={}){const{lineCounter:t,prettyErrors:n}=Ri(e),i=new Qn(t?.addNewLine),r=new Vn(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 Le(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Ut(s,t)),o.warnings.forEach(Ut(s,t))),o}c(Ki,"parseDocument");function Ea(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Ki(s,t);if(!i)return null;if(i.warnings.forEach(r=>Hs(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))}c(Ea,"parse");function Ia(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 Ne(s)&&!n?s.toString(t):new Xe(s,n,t).toString(t)}c(Ia,"stringify");var Ta=Object.freeze({__proto__:null,Alias:It,CST:Sa,Composer:Vn,Document:Xe,Lexer:Li,LineCounter:Pi,Pair:Q,Parser:Qn,Scalar:L,Schema:Qt,YAMLError:Bn,YAMLMap:ne,YAMLParseError:Le,YAMLSeq:ve,YAMLWarning:yi,isAlias:ke,isCollection:q,isDocument:Ne,isMap:Ke,isNode:W,isPair:F,isScalar:R,isSeq:_e,parse:Ea,parseAllDocuments:va,parseDocument:Ki,stringify:Ia,visit:Ae,visitAsync:Et});const z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},Na={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 Aa extends Cs{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=vt(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(P.existsSync(this.membraneDir)||P.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=wr.watch(this.membraneDir,Na),this.watcher.on("add",e=>this.handleFileSystemEvent(z.Added,e)).on("change",e=>this.handleFileSystemEvent(z.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(z.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.emit(z.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=D.relative(this.membraneDir,t);if(e===z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return P.readFileSync(e,"utf8")}processFileEvent(e,t){const n=D.relative(this.membraneDir,e);let i;try{i=t?Ta.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return fr.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(){P.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=P.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=D.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=P.readFileSync(i,"utf8"),o=D.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}class mt{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=le}fileWatcher=void 0;notifier;changes=[];hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new Aa({cwd:process.cwd()}),this.fileWatcher.on(z.Added,e=>this.handleLocalEvent(e,z.Added)),this.fileWatcher.on(z.Changed,e=>this.handleLocalEvent(e,z.Changed)),this.fileWatcher.on(z.Deleted,e=>this.handleLocalEvent(e,z.Deleted)),await this.fileWatcher.start(),T.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(lo(e.filePath))switch(t){case z.Added:case z.Changed:await uo(e.filePath);break;case z.Deleted:await fo(e.filePath);break}else{let n=G.fromPathAndData(e.filePath,e.data);if(!n){const r=G.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(ue.OUTGOING);switch(T.info(`[resolver][${this.getDirectionLabel(ue.OUTGOING)}] ${t}: ${n.id}`),t){case z.Added:case z.Changed:await i.putElement(n);break;case z.Deleted:await i.deleteElement(n);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=mt.getChanges(ue.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=mt.getChanges(ue.OUTGOING,this.localManager.cache,this.remoteManager.cache);return this.updateChanges(e),e}getChange(e){const t=this.localManager.cache.get(e.id),n=this.remoteManager.cache.get(e.id);return!t&&n?{type:X.CREATE,element:n,direction:ue.INCOMING,isConflict:!1}:t&&!n?{type:X.DELETE,element:t,direction:ue.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:X.UPDATE,element:t,direction:ue.OUTGOING,isConflict:!0}:null}async resolveChanges(){this.hasChanges()&&(T.info("[resolver] Resolving changes.."),await Promise.all(this.changes.map(e=>this.resolveChange(e))),T.success(`[resolver] Resolved ${this.changes.length} changes`))}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case X.DELETE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case X.CREATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case X.UPDATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),t.putElement(e.element)}}getManager(e){return e===ue.INCOMING?this.localManager:this.remoteManager}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),h=mt.detectChangeForElement(u,p,e);h&&a.push(h)}return a}updateChanges(e){this.changes=e;for(const t of e)T.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);T.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case ue.INCOMING:return"local\u2190remote";case ue.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case X.CREATE:return"ADD";case X.UPDATE:return"UPD";case X.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:X.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:X.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:X.UPDATE,element:e,direction:n,isConflict:!0}:null}}class _i{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=le,this.local=new $s(new go),this.remote=new $s(new yo),this.syncService=new mt(this.local,this.remote)}async push(e={}){await this.notifier.setState(x.PUSHING);try{await this.refreshElements()}catch(n){return T.error(`Failed to refresh elements: ${te(n)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return await this.notifier.setState(x.CONFLICTS);const t=await so();this.remote.setConnectorsMapping(t),await this.syncLocalAndRemoteWorkspaces({watch:e.watch})}async notifyRemote(){await this.notifier.connectToRemote()}async pull(e={}){await this.notifier.setState(x.PULLING);try{await this.refreshElements()}catch(t){return T.error(`Failed to refresh elements: ${te(t)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(x.CONFLICTS);await no({integrations:this.remote.cache.getElementsByType(_.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.syncLocalAndRemoteWorkspaces({watch:e.watch})}async syncLocalAndRemoteWorkspaces(e={}){await this.notifier.setState(x.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}async refreshElements(){return Promise.all([this.remote.refresh(),this.local.refresh()])}updateStats(){const e={};for(const t of this.local.cache.getAll())e[t.type]=(e[t.type]||0)+1;this.notifier.setStats(e)}}new _i;const pt={Agent:"agent",Cli:"cli"};class Xn{static{c(this,"MembraneCLIService")}constructor(e,t=()=>process.exit(0)){this.mode=e,this.onShutdown=t,this.notifications=le,this.workspaceService=new _i,this.mcpStatusService=new Xr}initialized=!1;notifications;workspaceService;mcpStatusService;isShuttingDown=!1;async pullWorkspace(e={}){await this.init();try{return this.workspaceService.pull(e)}catch(t){throw T.error("Failed to pull workspace from remote"),t}}async pushWorkspace(e={}){await this.init();try{return this.workspaceService.push(e)}catch(t){throw T.error("Failed to push workspace to remote"),t}}async syncWorkspaces(e={}){await this.init();try{return this.workspaceService.syncLocalAndRemoteWorkspaces(e)}catch(t){throw T.error("Failed to sync local and remote workspaces"),t}}async init(){if(!this.initialized)try{this.setupProcessCleanup(),this.mode===pt.Agent&&(await this.notifications.connectToRemote(),await this.mcpStatusService.start()),this.initialized=!0}catch(e){throw T.error("Failed to initialize membrane CLI"),e}}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===pt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const ji=Xi(process.argv.slice(2)),Oa=ji.cwd?Hi(ji.cwd):process.cwd(),Fi=new Xn(pt.Agent),$a=c(()=>m(bt,{cwd:Oa,membraneCLIService:Fi,children:m(zr,{})}),"App");function La(){Fi.init(),gt(m($a,{}))}c(La,"runAgent");function Pa(s){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(e=>{e.key&&e.secret?cn.saveToFile({workspaceKey:e.key,workspaceSecret:e.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):e.key||e.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):gt(Me.createElement(bt,null,Me.createElement(Is,{onComplete:c(()=>process.exit(0),"onComplete")})))})}c(Pa,"setupInitCommand");async function Bi(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return rn.sign(t,e)}c(Bi,"generateAdminAccessToken");async function xa(s,e){return(await on.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(xa,"fetchOpenApiSchema");function Ui(s,e=!0){if(!s)return e?B.string():B.string().optional();let t;switch(s.type){case"integer":t=B.coerce.number().int();break;case"number":t=B.coerce.number();break;case"boolean":t=B.coerce.boolean();break;case"string":default:t=B.string();break}return s.format==="uuid"?t=B.string().uuid():s.format==="email"?t=B.string().email():s.format==="date"?t=B.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=B.string().datetime()),s.enum&&(t=B.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()}c(Ui,"convertOpenApiSchemaToZod");function qi(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(qi,"extractPathParameters");function Da(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,l={},u={},p={};if(s.parameters){for(const f of s.parameters)if(f.in==="path")u[f.name]=Ui(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const g=f.required===!0;p[f.name]=Ui(f.schema,g).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(u).length>0&&(l.params=B.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=B.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=B.any().describe("Request body"));const h=Object.keys(l).length>0?B.object(l):B.object({});return{name:o,description:a,parameters:h,async execute(f){try{const g=qi(e);if(g.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const E=g.filter(O=>!(O in f.params));if(E.length>0)throw new Error(`Missing required path parameters: ${E.join(", ")}`)}let w=`${n}${e}`;if(f.params)for(const[E,O]of Object.entries(f.params)){const $=`{${E}}`;w.includes($)&&(w=w.replace($,String(O)))}const d=qi(w);if(d.length>0)throw new Error(`Unresolved path parameters: ${d.join(", ")}`);const y=new URLSearchParams;if(f.query)for(const[E,O]of Object.entries(f.query))O!=null&&y.append(E,String(O));y.toString()&&(w+=`?${y.toString()}`);const C=await Bi(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(v.data=f.body);const A=await on.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return on.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Da,"createApiTool");function Ma(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,l]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&l&&typeof l=="object"){const u=Da(l,r,a,e,t,n);i.push(u)}}return i}c(Ma,"convertOpenApiToTools");function Ra(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=Te();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||ln,n=await Bi(e.workspaceKey,e.workspaceSecret),i=await xa(t,n),r=Ma(i,t,e.workspaceKey,e.workspaceSecret),o=new Cr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
140
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=Qt(e),n=Ve(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=Qt(e),n=Ve(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 Li(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Ni||null,prettyErrors:e}}c(Li,"parseOptions");function Sa(s,e={}){const{lineCounter:t,prettyErrors:n}=Li(e),i=new zn(t?.addNewLine),r=new Gn(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Wt(s,t)),a.warnings.forEach(Wt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}c(Sa,"parseAllDocuments");function Di(s,e={}){const{lineCounter:t,prettyErrors:n}=Li(e),i=new zn(t?.addNewLine),r=new Gn(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 $e(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Wt(s,t)),o.warnings.forEach(Wt(s,t))),o}c(Di,"parseDocument");function Ca(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Di(s,t);if(!i)return null;if(i.warnings.forEach(r=>qs(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))}c(Ca,"parse");function ka(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 Te(s)&&!n?s.toString(t):new Qe(s,n,t).toString(t)}c(ka,"stringify");var va=Object.freeze({__proto__:null,Alias:Nt,CST:ya,Composer:Gn,Document:Qe,Lexer:Ti,LineCounter:Ni,Pair:Q,Parser:zn,Scalar:L,Schema:Zt,YAMLError:jn,YAMLMap:ne,YAMLParseError:$e,YAMLSeq:ke,YAMLWarning:hi,isAlias:Ce,isCollection:U,isDocument:Te,isMap:Re,isNode:q,isPair:F,isScalar:R,isSeq:_e,parse:Ca,parseAllDocuments:Sa,parseDocument:Di,stringify:ka,visit:Ne,visitAsync:Tt});const z={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},Ea={ignored:uo,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 Ia extends gs{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=It(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(P.existsSync(this.membraneDir)||P.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=mr.watch(this.membraneDir,Ea),this.watcher.on("add",e=>this.handleFileSystemEvent(z.Added,e)).on("change",e=>this.handleFileSystemEvent(z.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(z.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.emit(z.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=x.relative(this.membraneDir,t);if(e===z.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};T.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(n,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(n,i),o&&(T.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return P.readFileSync(e,"utf8")}processFileEvent(e,t){const n=x.relative(this.membraneDir,e);let i;try{i=t?va.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:n,data:i}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return cr.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(){P.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=P.readdirSync(e,{withFileTypes:!0});for(const n of t){const i=x.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(i);else if(n.isFile())try{const r=P.readFileSync(i,"utf8"),o=x.relative(this.membraneDir,i);this.updateCache(o,r)}catch{}}}}class pt{static{c(this,"ElementSyncService")}constructor(e,t){this.localManager=e,this.remoteManager=t,this.notifier=ue}fileWatcher=void 0;notifier;changes=[];clear(){this.changes=[]}hasConflicts(){return this.changes.some(e=>e.isConflict)}hasChanges(){return this.changes.length>0}async startWatching(){this.fileWatcher=new Ia({cwd:process.cwd()}),this.fileWatcher.on(z.Added,e=>this.handleLocalEvent(e,z.Added)),this.fileWatcher.on(z.Changed,e=>this.handleLocalEvent(e,z.Changed)),this.fileWatcher.on(z.Deleted,e=>this.handleLocalEvent(e,z.Deleted)),await this.fileWatcher.start(),T.success("[local] Tracking changes..")}async stopWatching(){await this.fileWatcher?.stop(),this.fileWatcher=void 0}async handleLocalEvent(e,t){try{if(oo(e.filePath))switch(t){case z.Added:case z.Changed:await ao(e.filePath);break;case z.Deleted:await co(e.filePath);break}else{let n=V.fromPathAndData(e.filePath,e.data);if(!n){const r=V.idFromPath(e.filePath);if(!r||(n=this.remoteManager.cache.get(r),!n))return}const i=this.getManager(fe.OUTGOING);switch(T.info(`[resolver][${this.getDirectionLabel(fe.OUTGOING)}] ${t}: ${n.id}`),t){case z.Added:case z.Changed:await i.putElement(n);break;case z.Deleted:await i.deleteElement(n);break}}}catch(n){T.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=pt.getChanges(fe.INCOMING,this.remoteManager.cache,this.localManager.cache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=pt.getChanges(fe.OUTGOING,this.localManager.cache,this.remoteManager.cache);return this.updateChanges(e),e}getChange(e){const t=this.localManager.cache.get(e.id),n=this.remoteManager.cache.get(e.id);return!t&&n?{type:X.CREATE,element:n,direction:fe.INCOMING,isConflict:!1}:t&&!n?{type:X.DELETE,element:t,direction:fe.OUTGOING,isConflict:!0}:t&&n&&!t.isEqual(n)?{type:X.UPDATE,element:t,direction:fe.OUTGOING,isConflict:!0}:null}async resolveChanges(){this.hasChanges()&&(T.info("[resolver] Resolving changes.."),await Promise.all(this.changes.map(e=>this.resolveChange(e))),T.success(`[resolver] Resolved ${this.changes.length} changes`))}async resolveChange(e){const t=this.getManager(e.direction);switch(e.type){case X.DELETE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Deleting ${e.element.id}`),t.deleteElement(e.element);case X.CREATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Creating ${e.element.id}`),t.putElement(e.element);case X.UPDATE:return T.info(`[resolver][${this.getDirectionLabel(e.direction)}] Updating ${e.element.id}`),t.putElement(e.element)}}getManager(e){return e===fe.INCOMING?this.localManager:this.remoteManager}static getChanges(e,t,n){const i=t.getAllIds(),r=n.getAllIds(),o=new Set([...i,...r]),a=[];for(const l of o){const u=t.get(l),p=n.get(l),d=pt.detectChangeForElement(u,p,e);d&&a.push(d)}return a}updateChanges(e){this.changes=e;for(const t of e)T.info(`[resolver][${this.getDirectionLabel(t.direction)}] ${this.getTypeLabel(t.type)} ${t.element.id}`);if(this.hasConflicts()){const t=e.filter(n=>n.isConflict);T.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case fe.INCOMING:return"local\u2190remote";case fe.OUTGOING:return"local\u2192remote"}}getTypeLabel(e){switch(e){case X.CREATE:return"ADD";case X.UPDATE:return"UPD";case X.DELETE:return"DEL"}}static detectChangeForElement(e,t,n){return e&&!t?{type:X.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:X.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:X.UPDATE,element:e,direction:n,isConflict:!0}:null}}class Pi{static{c(this,"WorkspaceService")}notifier;local;remote;syncService;constructor(){this.notifier=ue,this.local=new Is(new ho),this.remote=new Is(new po),this.syncService=new pt(this.local,this.remote)}async reset(){this.local.cache.clear(),this.remote.cache.clear(),this.updateStats(),this.syncService.clear()}async push(e={}){await this.notifier.setState(D.PUSHING);try{await this.refreshElements()}catch(n){return T.error(`Failed to refresh elements: ${te(n)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectOutgoingChanges(),this.syncService.hasConflicts()&&!e.force)return await this.notifier.setState(D.CONFLICTS);const t=await eo();this.remote.setConnectorsMapping(t),await this.syncLocalAndRemoteWorkspaces({watch:e.watch})}async notifyRemote(){await this.notifier.connectToRemote()}async pull(e={}){await this.notifier.setState(D.PULLING);try{await this.refreshElements()}catch(t){return T.error(`Failed to refresh elements: ${te(t)?.message??"Unknown error"}`),e?.onComplete?.()}if(this.syncService.detectIncomingChanges(),this.syncService.hasConflicts()&&!e.force)return this.notifier.setState(D.CONFLICTS);await Zr({integrations:this.remote.cache.getElementsByType(K.Integration).map(t=>t.data),allConnectors:e.allConnectors}),await this.syncLocalAndRemoteWorkspaces({watch:e.watch})}async syncLocalAndRemoteWorkspaces(e={}){await this.notifier.setState(D.RESOLVING),this.syncService.hasChanges()&&await this.syncService.resolveChanges(),this.updateStats(),await this.notifier.setState(D.SYNCED),e.watch&&(await this.notifier.setState(D.WATCHING),await this.syncService.startWatching()),e.onComplete?.()}async refreshElements(){return Promise.all([this.remote.refresh(),this.local.refresh()])}updateStats(){const e={};for(const t of this.local.cache.getAll())e[t.type]=(e[t.type]||0)+1;this.notifier.setStats(e)}}new Pi;const dt={Agent:"agent",Cli:"cli"};class xi{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifications=ue,this.workspaceService=new Pi,this.mcpStatusService=new Yr,this.setupProcessCleanup()}initialized=!1;notifications;workspaceService;mcpStatusService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}async pullWorkspace(e={}){try{return this.workspaceService.pull(e)}catch(t){throw T.error(`Failed to pull workspace: ${t}`),t}}async pushWorkspace(e={}){try{return this.workspaceService.push(e)}catch(t){throw T.error(`Failed to push workspace: ${t}`),t}}async syncWorkspaces(e={}){try{return this.workspaceService.syncLocalAndRemoteWorkspaces(e)}catch(t){throw T.error(`Failed to sync workspaces: ${t}`),t}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifications.setState(D.NOT_INITIALIZED);try{await this.loadConfig(),Ze.isCacheDefined(this.currentConfig)?(await this.initServices(),this.initialized=!0,await this.notifications.setState(D.INITIALIZED)):(this.initialized=!1,await this.notifications.setState(D.SETTING_UP))}catch(t){T.error(`Failed to initialize services: ${t}`),await this.notifications.setState(D.ERROR),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ze.loadConfig(this.cwd),this.notifications.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=Ze.updateConfig(t);this.currentConfig=i,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===dt.Agent&&(await this.notifications.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===dt.Agent&&(await this.notifications.connectToRemote(),await this.mcpStatusService.start()),await this.workspaceService.reset()}async stopServices(){this.mode===dt.Agent&&(await this.notifications.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 Mi=Hi(process.argv.slice(2)),Ri=Mi.cwd?Wi(Mi.cwd):process.cwd(),Ta=new xi(dt.Agent,Ri),Na=c(()=>m(wt,{cwd:Ri,membraneCLIService:Ta,children:m(Vr,{})}),"App");function Aa(){mt(m(Na,{}))}c(Aa,"runAgent");function Oa(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?Ze.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)):mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(Cs,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Oa,"setupInitCommand");async function _i(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return rn.sign(t,e)}c(_i,"generateAdminAccessToken");async function $a(s,e){return(await on.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c($a,"fetchOpenApiSchema");function Ki(s,e=!0){if(!s)return e?W.string():W.string().optional();let t;switch(s.type){case"integer":t=W.coerce.number().int();break;case"number":t=W.coerce.number();break;case"boolean":t=W.coerce.boolean();break;case"string":default:t=W.string();break}return s.format==="uuid"?t=W.string().uuid():s.format==="email"?t=W.string().email():s.format==="date"?t=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=W.string().datetime()),s.enum&&(t=W.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()}c(Ki,"convertOpenApiSchemaToZod");function Fi(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Fi,"extractPathParameters");function La(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,l={},u={},p={};if(s.parameters){for(const h of s.parameters)if(h.in==="path")u[h.name]=Ki(h.schema,!0).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const g=h.required===!0;p[h.name]=Ki(h.schema,g).describe(h.description||`Query parameter: ${h.name}`)}}Object.keys(u).length>0&&(l.params=W.object(u).describe("Path parameters")),Object.keys(p).length>0&&(l.query=W.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(l.body=W.any().describe("Request body"));const d=Object.keys(l).length>0?W.object(l):W.object({});return{name:o,description:a,parameters:d,async execute(h){try{const g=Fi(e);if(g.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const I=g.filter(O=>!(O in h.params));if(I.length>0)throw new Error(`Missing required path parameters: ${I.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[I,O]of Object.entries(h.params)){const $=`{${I}}`;w.includes($)&&(w=w.replace($,String(O)))}const f=Fi(w);if(f.length>0)throw new Error(`Unresolved path parameters: ${f.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[I,O]of Object.entries(h.query))O!=null&&y.append(I,String(O));y.toString()&&(w+=`?${y.toString()}`);const C=await _i(i,r),v={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};h.body&&t.toLowerCase()!=="get"&&(v.data=h.body);const A=await on.request({url:w,...v});return{content:[{type:"text",text:JSON.stringify(A.data,null,2)}]}}catch(g){return on.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(La,"createApiTool");function Da(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,l]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&l&&typeof l=="object"){const u=La(l,r,a,e,t,n);i.push(u)}}return i}c(Da,"convertOpenApiToTools");function Pa(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=St();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||cn,n=await _i(e.workspaceKey,e.workspaceSecret),i=await $a(t,n),r=Da(i,t,e.workspaceKey,e.workspaceSecret),o=new wr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
143
143
  Use it for anything related to Membrane or integrations.
144
- `,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async h=>(Zr(process.pid,process.cwd()),p(h)),o.addTool(u)}yn({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(()=>{yn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),nt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{nt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Ra,"setupMcpCommand");const Ka={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},_a={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class J{static{c(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=Ka[t],l=_a[t];return`${i}${a} ${r}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
144
+ `,version:"1.0.0"});for(const u of r){const p=u.execute;u.execute=async d=>(zr(process.pid,process.cwd()),p(d)),o.addTool(u)}gn({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(()=>{gn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),tt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{tt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Pa,"setupMcpCommand");const xa={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Ma={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class G{static{c(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${k.gray(new Date().toISOString())} `:"",r=n.prefix?`${k.gray(n.prefix)} `:"",o=n.suffix?` ${k.gray(n.suffix)}`:"",a=xa[t],l=Ma[t];return`${i}${a} ${r}${l(e)}${o}`}static info(e,t){let n=k.blue;if(t?.color&&(n=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
145
145
  ${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
146
- ${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.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 ja(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{J.header("Opening Workspace in Browser"),J.info("Loading configuration...");const e=Te();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");J.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await ks(process.cwd())}`;J.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),J.success("Browser opened successfully")}catch(e){e instanceof Error&&(J.error(e.message),process.exit(1)),J.error("An unknown error occurred"),process.exit(1)}})}c(ja,"setupOpenCommand");function Fa(s){const{logs:e,state:t,conflicts:n,pull:i}=be();ye(()=>{i(s)},[]);const r=t===x.CONFLICTS;return I(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&I(Xt,{children:[I(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(gn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&m(dn,{})]})}c(Fa,"Pull");function Wi(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(Wi,"getWatchModeCallback");function Ba(s){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 e=>{const t=e.watch?Wi():()=>process.exit(0),n=new Xn(pt.Cli);await n.init(),gt(Me.createElement(bt,{membraneCLIService:n,children:Me.createElement(Fa,{force:e.force,watch:e.watch,allConnectors:e.allConnectors,onComplete:t})}))})}c(Ba,"setupPullCommand");function Ua(s){const{logs:e,state:t,conflicts:n,push:i}=be();ye(()=>{i(s)},[]);const r=t===x.CONFLICTS;return I(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:pn(o.type),children:o.message},o.timestamp+a)),r&&I(Xt,{children:[I(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(gn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&m(dn,{})]})}c(Ua,"Push");function qa(s){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 e=>{const t=e.watch?Wi():()=>process.exit(0),n=new Xn(pt.Cli);await n.init(),gt(Me.createElement(bt,{membraneCLIService:n,children:Me.createElement(Ua,{force:e.force,watch:e.watch,onComplete:t})}))})}c(qa,"setupPushCommand");class Wa{static{c(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=un(),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 Ja="claude-sonnet-4-20250514";class ss{static{c(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=Te();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 cs({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new kr({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:Ja,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new ss({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(),an(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=U.join(this.testsDir,this.testBasePath,this.connectionId,e);if(M.existsSync(t))return de.load(M.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=U.join(this.testsDir,this.testBasePath,this.connectionId,e);M.mkdirSync(U.dirname(n),{recursive:!0}),M.writeFileSync(n,de.dump(t,{noRefs:!0}))}writeResults(e){const t=U.join(this.testsDir,this.testBasePath,this.connectionId);M.mkdirSync(t,{recursive:!0});const n=U.join(t,"test-results.yaml");M.writeFileSync(n,de.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 rn.sign(n,e.workspaceSecret,i)}}Er.interpolate=/{{([\s\S]+?)}}/g;function Zn(s,e){if(typeof s=="string"){const t=vr(s),n={state:e,random:{number:c(()=>Ze.number.int(),"number"),alphaNumeric:c(r=>Ze.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:c(()=>Ze.company.name(),"name"),catchPhrase:c(()=>Ze.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Ze.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=>Zn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Zn(n,e)])):s}c(Zn,"processNode");function Ga(s,e){return Zn(s,e)}c(Ga,"handleTemplate");class Va{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.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(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Ga(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),tn(this.result,e.path,i)}catch(l){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}tn(this.result,e.path,{error:te(l)}),t=!0,i={error:te(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),an(this.result,e.getResult())}}class Ie{static{c(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(k.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:te(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function es(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(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!ts(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=es(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}ts(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(es,"getNotMatchingSubFields");function ts(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}c(ts,"softCompare");class Ha extends Ie{static{c(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=nn(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=ls(n),a=yt(e.input.fields,o,{skipUnknownFields:!0}),l=yt(r.record.fields,o),u=es(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=or(n);if(i.length>0){const r={};i.forEach(a=>{const l=ar(e.input.fields,a);typeof l<"u"&&tn(r,a,l)});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=nn(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=te(t),i=nn(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:
146
+ ${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.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 Ra(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=St();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 ws(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)}})}c(Ra,"setupOpenCommand");function _a(s){return m(fn,{children:m(Ka,{options:s})})}c(_a,"Pull");function Ka({options:s}){const{logs:e,state:t,conflicts:n,pull:i}=oe();Ie(()=>{i(s)},[]);const r=t===D.CONFLICTS;return E(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Ct(o.type),children:o.message},o.timestamp+a)),r&&E(en,{children:[E(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(mn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(dn,{})]})}c(Ka,"PullActivity");function ji(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(ji,"getWatchModeCallback");function Fa(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?ji():()=>process.exit(0);mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(_a,{force:t.force,watch:t.watch,allConnectors:t.allConnectors,onComplete:n})}))})}c(Fa,"setupPullCommand");function ja(s){return m(fn,{children:m(Ba,{options:s})})}c(ja,"Push");function Ba({options:s}){const{logs:e,state:t,conflicts:n,push:i}=oe();Ie(()=>{i(s)},[]);const r=t===D.CONFLICTS;return E(b,{flexDirection:"column",children:[e.slice().map((o,a)=>m(S,{color:Ct(o.type),children:o.message},o.timestamp+a)),r&&E(en,{children:[E(S,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(mn,{}),m(S,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===D.SYNCED&&m(dn,{})]})}c(Ba,"PushActivity");function Ua(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?ji():()=>process.exit(0);mt(xe.createElement(wt,{membraneCLIService:e,children:xe.createElement(ja,{force:t.force,watch:t.watch,onComplete:n})}))})}c(Ua,"setupPushCommand");class qa{static{c(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 Wa="claude-sonnet-4-20250514";class ts{static{c(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=St();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 br({apiKey:i.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const p=await o.messages.create({model:Wa,max_tokens:u,messages:[{role:"user",content:l}]});return p.content[0].type==="text"?p.content[0].text:""},"complete")};return new ts({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(),an(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId,e);if(M.existsSync(t))return pe.load(M.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=B.join(this.testsDir,this.testBasePath,this.connectionId,e);M.mkdirSync(B.dirname(n),{recursive:!0}),M.writeFileSync(n,pe.dump(t,{noRefs:!0}))}writeResults(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId);M.mkdirSync(t,{recursive:!0});const n=B.join(t,"test-results.yaml");M.writeFileSync(n,pe.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 rn.sign(n,e.workspaceSecret,i)}}Cr.interpolate=/{{([\s\S]+?)}}/g;function Qn(s,e){if(typeof s=="string"){const t=Sr(s),n={state:e,random:{number:c(()=>Xe.number.int(),"number"),alphaNumeric:c(r=>Xe.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:c(()=>Xe.company.name(),"name"),catchPhrase:c(()=>Xe.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Xe.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=>Qn(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Qn(n,e)])):s}c(Qn,"processNode");function Ja(s,e){return Qn(s,e)}c(Ja,"handleTemplate");class Ga{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.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(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Ja(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),tn(this.result,e.path,i)}catch(l){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}tn(this.result,e.path,{error:te(l)}),t=!0,i={error:te(l)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),an(this.result,e.getResult())}}class Ee{static{c(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(k.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:te(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Xn(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(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!Zn(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=Xn(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}Zn(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}c(Xn,"getNotMatchingSubFields");function Zn(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}c(Zn,"softCompare");class Va extends Ee{static{c(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=nn(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=cs(n),a=gt(e.input.fields,o,{skipUnknownFields:!0}),l=gt(r.record.fields,o),u=Xn(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const i=nr(n);if(i.length>0){const r={};i.forEach(a=>{const l=sr(e.input.fields,a);typeof l<"u"&&tn(r,a,l)});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=nn(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=te(t),i=nn(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
150
 
151
151
  ${JSON.stringify(i,null,2)}
152
152
 
@@ -186,7 +186,7 @@ ${JSON.stringify(i,null,2)}`).join(`
186
186
 
187
187
  `)}.
188
188
 
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 us(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=fs(i);n[r]=await this.fetchExampleRecords(i)}return n}}class Ya extends Ie{static{c(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=te(t),i=`I'm trying to delete a record from a data collection.
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 ls(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=us(i);n[r]=await this.fetchExampleRecords(i)}return n}}class Ha extends Ee{static{c(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=te(t),i=`I'm trying to delete a record from a data collection.
190
190
 
191
191
  I tried to delete a record with this ID:
192
192
 
@@ -206,7 +206,7 @@ Format your response as a JSON object with two fields:
206
206
  "id": "fixed id"
207
207
  }.
208
208
 
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class za extends Ie{static{c(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=te(t),i=`I'm trying to find a record by ID in a data collection.
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Ya extends Ee{static{c(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=te(t),i=`I'm trying to find a record by ID in a data collection.
210
210
 
211
211
  I tried to find a record with this ID:
212
212
 
@@ -226,7 +226,7 @@ Format your response as a JSON object with two fields:
226
226
  "id": "fixed id"
227
227
  }.
228
228
 
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Qa extends Ie{static{c(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],l=r[o].fields[n];a==null||l==null||(i==="asc"?await this.assert(()=>a<=l,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=l,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=te(t),i=`I'm trying to list records from a data collection.
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class za extends Ee{static{c(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],l=r[o].fields[n];a==null||l==null||(i==="asc"?await this.assert(()=>a<=l,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=l,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=te(t),i=`I'm trying to list records from a data collection.
230
230
 
231
231
  I tried to list records with these parameters:
232
232
 
@@ -246,7 +246,7 @@ Format your response as a JSON object with two fields:
246
246
  "input": { ... fixed parameters ... }
247
247
  }.
248
248
 
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Xa extends Ie{static{c(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 l=r.fields[o];await this.assert(()=>ts(l,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(l)}`)}}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=te(t),i=`I'm trying to match a record in a data collection.
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Qa extends Ee{static{c(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 l=r.fields[o];await this.assert(()=>Zn(l,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(l)}`)}}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=te(t),i=`I'm trying to match a record in a data collection.
250
250
 
251
251
  I tried to match a record with this query:
252
252
 
@@ -266,7 +266,7 @@ Format your response as a JSON object with two fields:
266
266
  "query": { ... fixed query ... }
267
267
  }.
268
268
 
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Za extends Ie{static{c(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(k.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.
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Xa extends Ee{static{c(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(k.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
270
 
271
271
  Record fields:
272
272
  ${JSON.stringify(e,null,2)}
@@ -291,7 +291,7 @@ Format your response as a JSON object with two fields:
291
291
  "input": { ... fixed parameters ... }
292
292
  }.
293
293
 
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class ec extends Ie{static{c(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 tc extends Ie{static{c(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=sn(this.dataCollection),o=ls(r),a=yt(e.input.fields,o,{skipUnknownFields:!0}),l=yt(i.record.fields,o),u=es(l,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:l})}}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=sn(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=te(t),i=sn(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:
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(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Za extends Ee{static{c(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 ec extends Ee{static{c(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=sn(this.dataCollection),o=cs(r),a=gt(e.input.fields,o,{skipUnknownFields:!0}),l=gt(i.record.fields,o),u=Xn(l,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:l})}}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=sn(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=te(t),i=sn(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
295
 
296
296
  ${JSON.stringify(i,null,2)}
297
297
 
@@ -331,9 +331,9 @@ ${JSON.stringify(i,null,2)}`).join(`
331
331
 
332
332
  `)}.
333
333
 
334
- If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,n=[];return us(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=fs(i);n[r]=await this.fetchExampleRecords(i)}return n}}const ns={spec:{testerClass:ec},create:{testerClass:Ha,operationKey:"create"},"find-by-id":{testerClass:za,operationKey:"findById"},list:{testerClass:Qa,operationKey:"list"},match:{testerClass:Xa,operationKey:"match"},search:{testerClass:Za,operationKey:"search"},update:{testerClass:tc,operationKey:"update"},delete:{testerClass:Ya,operationKey:"delete"}};class nc extends Va{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);J.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=ns[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(ns).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(ns).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){J.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class sc extends Wa{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){J.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(J.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(J.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),J.error("Supported test types: connectors"),process.exit(1));const l=o,u=r,p=[...a,...t?t.split("/"):[]].join("/"),h=await ss.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await h.client.get(`connections/${l}/data`),w=[],d=p?p.split("/"):[];if(d.length===0||d[0]==="data"){d[0]==="data"&&d.shift();let C,v;d.length>=1&&(v=d[0],d.length>=2&&d[1].trim()!==""&&(C=d[1]));for(const A of g){if(v&&v!==A.key)continue;const E=new nc({environment:h,dataCollectionKey:A.key,testMethod:C});w.push(E)}}w.length===0&&(J.error(`No test suites found for path: ${e}${p?"/"+p:""}`),process.exit(1));const y={};for(const C of w){await C.run();const v=C.getResult();J.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),an(y,v)}console.debug("[TestRunner] All results collected:",Object.keys(y)),h.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const zt=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
335
- `),"createExperimentalWarning");function ic(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",zt()).action(async()=>{console.warn(zt()),J.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",zt()].join(`
336
- `)).action(async(t,n)=>{try{console.warn(zt()),t||(J.error("Test path is required"),process.exit(1)),J.header(`Testing: ${t}`);const i=new sc({testPath:t,path:n.path,fix:n.fix});await i.initialize(),await i.run(),J.success("Tests completed")}catch(i){i instanceof Error&&(J.error(i.message),process.exit(1)),J.error("An unknown error occurred"),process.exit(1)}})}c(ic,"setupTestCommand");const rc=c(()=>{try{const s=br(import.meta.url),e=Yi(s),t=zi(e,"..","package.json");return JSON.parse(nr(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Ji=rc();function oc(){const s=new Sr().name("membrane").description("Command-line interface for Membrane Agent").version(Ji,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(e=>k.cyan(e.name()),"subcommandTerm"),commandUsage:c(e=>e.name()==="membrane"?`${k.cyan(e.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:e.usage(),"commandUsage"),optionTerm:c(e=>{const t=e.flags;return`${k.gray("\u25B8")} ${k.cyan(t)}`},"optionTerm"),subcommandDescription:c(e=>k.gray(e.description()),"subcommandDescription"),optionDescription:c(e=>k.gray(e.description),"optionDescription"),commandDescription:c(e=>k.gray(e.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
- ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Ji}`)}
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 ls(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=us(i);n[r]=await this.fetchExampleRecords(i)}return n}}const es={spec:{testerClass:Za},create:{testerClass:Va,operationKey:"create"},"find-by-id":{testerClass:Ya,operationKey:"findById"},list:{testerClass:za,operationKey:"list"},match:{testerClass:Qa,operationKey:"match"},search:{testerClass:Xa,operationKey:"search"},update:{testerClass:ec,operationKey:"update"},delete:{testerClass:Ha,operationKey:"delete"}};class tc extends Ga{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);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=es[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(es).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(es).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 nc extends qa{static{c(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 l=o,u=r,p=[...a,...t?t.split("/"):[]].join("/"),d=await ts.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${l}/data`),w=[],f=p?p.split("/"):[];if(f.length===0||f[0]==="data"){f[0]==="data"&&f.shift();let C,v;f.length>=1&&(v=f[0],f.length>=2&&f[1].trim()!==""&&(C=f[1]));for(const A of g){if(v&&v!==A.key)continue;const I=new tc({environment:d,dataCollectionKey:A.key,testMethod:C});w.push(I)}}w.length===0&&(G.error(`No test suites found for path: ${e}${p?"/"+p:""}`),process.exit(1));const y={};for(const C of w){await C.run();const v=C.getResult();G.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),an(y,v)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Xt=c(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
335
+ `),"createExperimentalWarning");function sc(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",Xt()).action(async()=>{console.warn(Xt()),G.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",Xt()].join(`
336
+ `)).action(async(t,n)=>{try{console.warn(Xt()),t||(G.error("Test path is required"),process.exit(1)),G.header(`Testing: ${t}`);const i=new nc({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)}})}c(sc,"setupTestCommand");const ic=c(()=>{try{const s=gr(import.meta.url),e=Ji(s),t=Gi(e,"..","package.json");return JSON.parse(er(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Bi=ic();function rc(){const s=new yr().name("membrane").description("Command-line interface for Membrane Agent").version(Bi,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(t=>k.cyan(t.name()),"subcommandTerm"),commandUsage:c(t=>t.name()==="membrane"?`${k.cyan(t.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:t.usage(),"commandUsage"),optionTerm:c(t=>{const n=t.flags;return`${k.gray("\u25B8")} ${k.cyan(n)}`},"optionTerm"),subcommandDescription:c(t=>k.gray(t.description()),"subcommandDescription"),optionDescription:c(t=>k.gray(t.description),"optionDescription"),commandDescription:c(t=>k.gray(t.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
+ ${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${Bi}`)}
338
338
 
339
- `),Ba(s),qa(s),ic(s),ja(s),Ra(s),Pa(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}c(oc,"runCLI");const Gi=["--cwd"];function ac(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Gi.includes(s[t-1])?!1:!Gi.includes(e))}c(ac,"hasCLIArguments"),ac()?oc():La();
339
+ `);const e=new xi(dt.Cli,process.cwd());Fa(s,e),Ua(s,e),Oa(s,e),Ra(s),sc(s),Pa(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}c(rc,"runCLI");const Ui=["--cwd"];function oc(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Ui.includes(s[t-1])?!1:!Ui.includes(e))}c(oc,"hasCLIArguments"),oc()?rc():Aa();