@membranehq/cli 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +138 -138
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,152 +1,152 @@
1
1
  #!/usr/bin/env node
2
- var yr=Object.defineProperty;var l=(n,e)=>yr(n,"name",{value:e,configurable:!0});import{jsx as y,jsxs as I}from"react/jsx-runtime";import*as J from"node:path";import{resolve as wr,dirname as br,join as Sr}from"node:path";import{useInput as Qe,Box as A,Text as k,Newline as kr,render as sn}from"ink";import Cr from"minimist";import{SWRConfig as vr}from"swr";import Ar from"os";import K from"path";import Or from"conf";import ht,{createContext as ls,useContext as us,useState as D,useEffect as pt,useCallback as fs}from"react";import*as j from"node:fs";import{readFileSync as Er}from"node:fs";import oe from"js-yaml";import{z as F}from"zod";import{exec as Tr}from"node:child_process";import*as $r from"node:crypto";import{createHash as Ir}from"node:crypto";import*as Nr from"node:os";import{TextInput as _r,Select as Lr}from"@inkjs/ui";import rn from"ink-spinner";import ds from"swr/immutable";import xr from"ink-text-input";import{EventEmitter as on}from"node:events";import{WorkspaceElementSpecs as ee,WorkspaceElementType as M,IntegrationAppClient as an,setValueAtLocator as cn,extractIntegrationAppErrorData as ae,getDataCollectionCreateFields as ln,excludeWriteOnlyFieldsFromSchema as hs,valueToSchema as mt,getRequiredFieldsFromSchema as Pr,getValueAtLocator as jr,walkSchema as ps,makeDataLocationPath as ms,getDataCollectionUpdateFields as un}from"@membranehq/sdk";import gt from"jsonwebtoken";import Kr from"chokidar";import P from"fs";import Dr from"archiver";import Mr from"form-data";import Rr from"unzipper";import v from"chalk";import{fileURLToPath as Br}from"node:url";import{Command as Fr}from"commander";import fn from"axios";import{FastMCP as qr}from"fastmcp";import dn from"lodash/merge.js";import Ur from"@anthropic-ai/sdk";import{faker as Xe}from"@faker-js/faker";import Jr from"lodash/template.js";import Vr from"lodash/templateSettings.js";const Wr="membrane",zr="membrane.config.yml",hn="https://api.integration.app";function et(){const n=process.cwd(),e=J.join(n,Wr),t=J.join(n,zr),s=e,i=J.join(s,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:s,workspaceDataFilePath:i}}l(et,"getPaths");function Hr(){return et().membraneDirPath}l(Hr,"getBasePath");const Gr={pat:{type:"string"},workspace:{type:"object"}},pn=new Or({schema:Gr,configName:"config",cwd:K.join(Ar.homedir(),".membrane")}),Yr=l(n=>{pn.set("pat",n)},"setPat"),gs=l(()=>pn.get("pat"),"getPat"),Zr=l(()=>!!pn.get("pat"),"hasPat");class ys{static{l(this,"AccountApiClient")}constructor(e=hn){this.apiBaseUrl=e}async request(e,t={}){const s=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!s.has("Authorization")){const o=gs();if(!o)throw new Error("Personal Access Token not found.");s.set("Authorization",`Bearer ${o}`)}t.body&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:s});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 Qr=l(n=>{const e=new ys(hn);return t=>e.get(t)},"createAccountApiFetcher"),ws=ls(process.cwd());function Xr({cwd:n,children:e}){return y(ws.Provider,{value:n,children:e})}l(Xr,"CwdProvider");function mn(){return us(ws)}l(mn,"useCwd");const eo="membrane.config.yml";function be(n){const e=J.join(n??process.cwd(),eo);try{const t=j.readFileSync(e,"utf8"),s=oe.load(t),i=bs.safeParse(s);return i.success?i.data:null}catch{return null}}l(be,"readProjectConfig");const to="membrane.config.yml",bs=F.object({workspaceKey:F.string().optional(),workspaceSecret:F.string().optional(),apiUri:F.string().optional(),testCustomerId:F.string().optional(),anthropicApiKey:F.string().optional()});F.enum(["pull"]);const Ss=ls(void 0);function no({children:n}){const e=mn(),[t,s]=D(null),[i,r]=D(!0);pt(()=>{const u=be(e);s(u),r(!1)},[e]);const o=fs(u=>{const d=J.join(e,to),h={...be(e)??{},...u},m=bs.safeParse(h);return m.success?(j.writeFileSync(d,oe.dump(m.data)),s(m.data),!0):!1},[e]),a=fs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return y(Ss.Provider,{value:c,children:n})}l(no,"ProjectConfigProvider");function gn(){const n=us(Ss);if(n===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return n}l(gn,"useProjectConfig");function yn({cwd:n,children:e}){const t=n||process.cwd();return y(Xr,{cwd:t,children:y(no,{children:y(vr,{value:{fetcher:Qr()},children:e})})})}l(yn,"Layout");const wn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const n=J.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(j.existsSync(n))try{t=JSON.parse(j.readFileSync(n,"utf8"))}catch{t={}}const s={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return j.writeFileSync(n,JSON.stringify(s,null,2)),`MCP server configuration added to ${n}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const n=J.join(process.cwd(),".cursor"),e=J.join(n,"mcp.json");j.existsSync(n)||j.mkdirSync(n);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let s={};if(j.existsSync(e))try{s=JSON.parse(j.readFileSync(e,"utf8"))}catch{s={}}const i={...s,mcpServers:{...s.mcpServers,...t.mcpServers}};return j.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}],so=l(({onExit:n,onComplete:e})=>{const[t,s]=D(0),[i,r]=D(!1),[o,a]=D(null),[c,u]=D(""),[d,f]=D("");Qe((w,p)=>{if(c||d){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)n();else if(p.upArrow||w==="k")s(Math.max(0,t-1));else if(p.downArrow||w==="j")s(Math.min(wn.length-1,t+1));else if(p.return||w===" "){const g=wn[t];a(g),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"green",children:"Success"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[y(k,{color:"green",children:c}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),y(A,{marginTop:1,paddingLeft:2,children:y(k,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"red",children:"Error"})]})}),y(A,{flexDirection:"column",paddingLeft:2,children:y(k,{color:"red",children:d})}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"cyan",children:"Confirmation"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[I(k,{children:["Connect ",y(k,{bold:!0,children:o.name})," to Membrane via MCP?"]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),y(A,{marginTop:1,children:y(k,{color:"yellow",bold:!0,children:o.actionDescription})}),y(A,{marginTop:2,marginBottom:1,children:I(k,{children:[y(k,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",y(k,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",y(k,{color:"cyan",children:"Select Agent"})]})}),I(A,{flexDirection:"column",paddingLeft:2,children:[y(k,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),y(A,{marginTop:1,flexDirection:"column",children:wn.map((w,p)=>I(A,{children:[I(k,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),I(k,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})},"AddMcpServerScreen"),he=J.join(Nr.tmpdir(),"membrane-mcp-status"),ks=3e4;function bn(n){return Ir("md5").update(n).digest("hex").slice(0,8)}l(bn,"getCwdHash");function Sn(n,e){const t=bn(e);return J.join(he,`mcp-${t}-${n}.json`)}l(Sn,"getStatusFilePath");function Te(n,e){try{const t=e||process.cwd();if(!n){const i=yt(t);return i.length===0?null:i[0]}const s=Sn(n,t);if(j.existsSync(s)){const i=j.statSync(s),r=new Date;if(r.getTime()-i.mtime.getTime()>ks)return tt(n,t),null;const a=j.readFileSync(s,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>ks)return tt(n,t),null}return c}}catch{n&&e&&tt(n,e)}return null}l(Te,"getMcpStatus");function yt(n){try{const e=n||process.cwd(),t=bn(e);if(!j.existsSync(he))return[];const s=j.readdirSync(he),i=[];for(const r of s){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=Te(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yt,"getAllMcpStatusFiles");function kn(n){try{const t={...Te(n.processId,n.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:n.processId,cwd:n.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...n};j.existsSync(he)||j.mkdirSync(he,{recursive:!0});const s=Sn(n.processId,n.cwd);j.writeFileSync(s,JSON.stringify(t,null,2))}catch{}}l(kn,"updateMcpStatus");function tt(n,e){try{const t=e||process.cwd();if(n){const s=Sn(n,t);j.existsSync(s)&&j.unlinkSync(s)}else{const s=bn(t);if(j.existsSync(he)){const i=j.readdirSync(he);for(const r of i)r.match(new RegExp(`^mcp-${s}-\\d+\\.json$`))&&j.unlinkSync(J.join(he,r))}}}catch{}}l(tt,"clearMcpStatus");function io(n,e){const t=Te(n,e);t&&kn({processId:n,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(io,"trackToolExecution");function ro(){const[n,e]=D(Te()),[t,s]=D(yt()),[i,r]=D(null);return pt(()=>{try{const a=process.cwd();e(Te(void 0,a)),s(yt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),s([])}const o=setInterval(()=>{try{const a=process.cwd(),c=Te(void 0,a),u=yt(a);e(c),s(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),s([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:n,allMcpServers:t,error:i,isRunning:n?.isRunning||!1,toolsCount:n?.toolsCount||0,totalRequests:n?.totalRequests||0,lastActivity:n?.lastActivity,processId:n?.processId,serverCount:t.length}}l(ro,"useMcpStatus");const oo=l(()=>{const n=Math.min(100,process.stdout.columns||100),{error:e,serverCount:t,allMcpServers:s}=ro();return I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[y(A,{marginTop:-1,marginBottom:0,flexDirection:"column",children:I(k,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",e?y(k,{color:"red",children:"error reading status"}):t===0?y(k,{color:"yellow",children:"none"}):y(k,{color:"green",children:t})]})}),!e&&t===0&&y(A,{marginTop:1,children:I(k,{color:"grey",children:["Connect your AI agents to Membrane.",y(kr,{}),"It will give them tools and context to build integrations."]})}),s.length>0&&y(A,{flexDirection:"column",paddingLeft:2,marginTop:1,children:s.map((i,r)=>y(A,{children:I(k,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"[a: connect an agent]"})})]})},"AgentStatus"),Cs=l(({onExit:n,showEscOption:e=!0})=>{const[t,s]=D(""),{data:i,error:r,isLoading:o}=ds("/account"),{updateConfig:a,isLoading:c}=gn(),u=i?.workspaces,d=o||c;if(Qe((g,S)=>{S.escape&&n?.()}),d)return I(A,{children:[y(rn,{}),y(k,{children:" Fetching workspaces..."})]});if(r)return I(A,{flexDirection:"column",children:[I(k,{color:"red",children:["Error: ",r.message]}),y(A,{marginTop:1,children:y(k,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(g=>g.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(g=>({label:g.name,value:g.id})),m=h.length,w=u?.length??0,p=l(async g=>{const S=f.find(T=>T.id===g);if(!S)return;const{key:b,secret:C}=S;!b||!C||(await a({workspaceKey:b,workspaceSecret:C}),n?.())},"handleSelect");return I(A,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[y(A,{marginTop:-1,children:y(k,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),I(A,{marginTop:1,children:[y(k,{children:"Search: "}),y(_r,{placeholder:"Enter a search query...",onChange:s})]}),w>5&&I(k,{children:["Showing ",m," of ",w," workspaces."]}),y(A,{marginTop:1,children:y(Lr,{options:h,onChange:l(g=>{g&&p(g)},"onChange")})}),e&&y(A,{marginTop:1,children:y(k,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),ao=l(({currentPat:n,onSubmit:e})=>{const[t,s]=D(""),[i,r]=D(!1),[o,a]=D(null);return I(A,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[y(A,{marginTop:-1,marginBottom:1,children:y(k,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),y(k,{children:"Please provide your Personal Access Token. You can find it here:"}),y(A,{marginTop:1,marginBottom:1,children:y(k,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),n&&y(k,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),y(xr,{mask:"*",placeholder:`${n?"******":"Enter your token here..."}`,value:t,onChange:s,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),s("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&y(A,{marginTop:1,children:I(k,{children:[y(rn,{type:"dots"})," Validating token..."]})}),o&&y(k,{color:"red",children:o})]})},"PersonalAccessTokenInput");var nt=(n=>(n[n.Authenticate=0]="Authenticate",n[n.ConnectWorkspace=1]="ConnectWorkspace",n))(nt||{});const co={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},vs=l(()=>{const{config:n}=gn(),e=Zr(),t=!!(n?.workspaceKey&&n?.workspaceSecret);return{isAuthenticated:e,workspaceIsConfigured:t,isSetupComplete:e&&t}},"useSetup"),lo=l(({status:n,label:e})=>I(A,{children:[I(A,{width:2,children:[n==="current"&&y(rn,{type:"dots"}),n==="done"&&y(k,{children:"\u2705"})]}),y(k,{dimColor:n!=="current",children:e})]}),"StepDisplay"),Cn=[nt.Authenticate,nt.ConnectWorkspace],As=l(({onComplete:n})=>{const[e,t]=D(!1),[s,i]=D(0),[r,o]=D(!1),[a,c]=D(null),[u,d]=D(""),{isSetupComplete:f}=vs(),h=Cn[s],m=s+1,w=Cn.length,p=Cn.map((C,T)=>{let O="pending";return T<s?O="done":T===s&&(O="current"),{id:C,label:co[C],status:O}}),g=gs();g&&"*".repeat(g.length);const S=l(async C=>{c(null),o(!0);const T=g&&C===""?g:C,O=new ys;try{await O.request("/account",{headers:{Authorization:`Bearer ${T}`}}),Yr(T),i($=>$+1),d("")}catch($){console.log($),c("Invalid token. Please try again.")}finally{o(!1)}},"handlePatSubmit"),b=l(()=>{t(!0),n&&n()},"handleWorkspaceSelected");return Qe((C,T)=>{f&&T.escape&&n&&n()}),e?y(A,{children:y(k,{children:"\u2705 Setup complete. You are ready to go!"})}):I(A,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",I(k,{color:"cyan",children:["Step ",m," of ",w]}),f&&y(k,{color:"grey",children:" [esc: go back]"})]})}),y(A,{flexDirection:"column",paddingLeft:2,children:p.map(C=>y(lo,{status:C.status,label:C.label},C.id))})]}),h===nt.Authenticate&&y(ao,{currentPat:g,onSubmit:S}),h===nt.ConnectWorkspace&&y(Cs,{onExit:b,showEscOption:!1})]})},"Setup"),Os=l(()=>{const{isSetupComplete:n}=vs(),{config:e}=gn(),t=mn();return{isSetupComplete:n,workspaceKey:e?.workspaceKey,config:e,cwd:t}},"useStatus"),uo="membrane",fo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function Es(n){return J.join(n,uo)}l(Es,"getMembraneDir");class ho extends on{static{l(this,"WorkspaceLogger")}_logs=[];get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const s={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(s),this._logs=this._logs.slice(0,1e3),this.emit("logAdded")}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=[],this.emit("logAdded")}}const V=new ho;class po{static{l(this,"LocalElementsManagerService")}elements={};basePath;constructor(){this.basePath=Es(process.cwd())}async read(){for(const e of Object.keys(ee)){const t=await this.readElements(e);this.elements[e]=t}}async readElements(e){const t=J.join(this.basePath,ee[e].apiPath),s=j.readdirSync(t);return Promise.all(s.map(i=>this.readElement(J.join(t,i))))}async readElement(e){const t=j.readFileSync(e,"utf8");return oe.load(t)}async writeElement(e,t){const s=this.getElementDir(e,t),i=J.join(s,"spec.yaml"),r=J.join(this.basePath,s),o=J.join(r,"spec.yaml");V.info(`Writing ${i}`),j.existsSync(r)||j.mkdirSync(r,{recursive:!0}),j.writeFileSync(o,oe.dump(t))}getElementDir(e,t){const s=this.getElementTypeDir(e);let i=J.join(s,t.key);const r=this.getIntegrationKey(t);if(r){const o=`${this.getElementTypeDir(M.Integration)}/${r}`;i=J.join(o,i)}return i}getElementTypeDir(e){return ee[e].apiPath}getIntegrationKey(e){return e.integration?e.integration.key:e.integrationKey}}function mo(n){if(!wo(n)&&yo(n))return go(n)}l(mo,"getTypeAndKeyFromPath");function go(n){const e=Object.values(ee).map(o=>o.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),s=n.match(t);if(s&&s.groups){const{elementTypePlural:o,elementKey:a}=s.groups,c=Ts(o);if(c)return{key:a,type:c}}const i=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),r=n.match(i);if(r&&r.groups){const{elementTypePlural:o,elementKey:a}=r.groups,c=Ts(o);if(c)return{key:a,type:c}}}l(go,"extractWorkspaceElementKeyReference");function yo(n){return n.endsWith(".yml")||n.endsWith(".yaml")}l(yo,"isWorkspaceElementFile");function wo(n){const[e]=n.split(J.sep);return e===ee[M.Connector].apiPath}l(wo,"isConnectorFile");function Ts(n){return Object.values(M).find(e=>bo(e)===n)}l(Ts,"getWorkspaceElementTypeFromFolderName");function bo(n){return ee[n].apiPath}l(bo,"getWorkspaceElementTypeFolderName");var L={},wt={},$s;function Is(){if($s)return wt;$s=1,Object.defineProperty(wt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toCamelCase"),wt.default=n,wt}l(Is,"requireJsCamelcase");var bt={},Ns;function _s(){if(Ns)return bt;Ns=1,Object.defineProperty(bt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(n,"toSnakeCase"),bt.default=n,bt}l(_s,"requireJsSnakecase");var St={},Ls;function xs(){if(Ls)return St;Ls=1,Object.defineProperty(St,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toPascalCase"),St.default=n,St}l(xs,"requireJsPascalcase");var kt={},Ps;function So(){if(Ps)return kt;Ps=1,Object.defineProperty(kt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(n,"toDotCase"),kt.default=n,kt}l(So,"requireJsDotcase");var Ct={},js;function ko(){if(js)return Ct;js=1,Object.defineProperty(Ct,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(n,"toPathCase"),Ct.default=n,Ct}l(ko,"requireJsPathcase");var vt={},Ks;function Co(){if(Ks)return vt;Ks=1,Object.defineProperty(vt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(n,"toTextCase"),vt.default=n,vt}l(Co,"requireJsTextcase");var At={},Ds;function vo(){if(Ds)return At;Ds=1,Object.defineProperty(At,"__esModule",{value:!0});function n(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(s,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(n,"toSentenceCase"),At.default=n,At}l(vo,"requireJsSentencecase");var Ot={},Ms;function Ao(){if(Ms)return Ot;Ms=1,Object.defineProperty(Ot,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,s,i,r){return s+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(n,"toHeaderCase"),Ot.default=n,Ot}l(Ao,"requireJsHeadercase");var Et={},Rs;function Bs(){if(Rs)return Et;Rs=1,Object.defineProperty(Et,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(n,"toKebabCase"),Et.default=n,Et}l(Bs,"requireJsKebabcase");var $e={},vn={},Fs;function Ie(){return Fs||(Fs=1,function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.belongToTypes=n.isValidObject=n.isArrayObject=n.validateOptions=n.DefaultOption=void 0,n.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},n.validateOptions=function(e){return e===void 0&&(e=n.DefaultOption),e.recursive==null?e=n.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},n.isArrayObject=function(e){return e!=null&&Array.isArray(e)},n.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},n.belongToTypes=function(e,t){return(t||[]).some(function(s){return e instanceof s})}}(vn)),vn}l(Ie,"requireUtils");var qs;function Oo(){if(qs)return $e;qs=1;var n=$e&&$e.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty($e,"__esModule",{value:!0});var e=Ie();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"lowerKeys"),$e.default=t,$e}l(Oo,"requireLowercaseKeysObject");var Ne={},Us;function Eo(){if(Us)return Ne;Us=1;var n=Ne&&Ne.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Ne,"__esModule",{value:!0});var e=Ie();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"upperKeys"),Ne.default=t,Ne}l(Eo,"requireUppercaseKeysObject");var _e={},Js;function To(){if(Js)return _e;Js=1;var n=_e&&_e.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(_e,"__esModule",{value:!0});var e=Ie(),t=Is();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"camelKeys"),_e.default=s,_e}l(To,"requireCamelcaseKeysObject");var Le={},Vs;function $o(){if(Vs)return Le;Vs=1;var n=Le&&Le.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Le,"__esModule",{value:!0});var e=Ie(),t=_s();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"snakeKeys"),Le.default=s,Le}l($o,"requireSnakecaseKeysObject");var xe={},Ws;function Io(){if(Ws)return xe;Ws=1;var n=xe&&xe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(xe,"__esModule",{value:!0});var e=Ie(),t=xs();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"pascalKeys"),xe.default=s,xe}l(Io,"requirePascalcaseKeysObject");var Pe={},zs;function No(){if(zs)return Pe;zs=1;var n=Pe&&Pe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Pe,"__esModule",{value:!0});var e=Ie(),t=Bs();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"kebabKeys"),Pe.default=s,Pe}l(No,"requireKebabcaseKeysObject");var Hs;function _o(){if(Hs)return L;Hs=1,Object.defineProperty(L,"__esModule",{value:!0}),L.kebabKeys=L.pascalKeys=L.snakeKeys=L.camelKeys=L.upperKeys=L.lowerKeys=L.toLowerCase=L.toUpperCase=L.toKebabCase=L.toHeaderCase=L.toSentenceCase=L.toTextCase=L.toPathCase=L.toDotCase=L.toPascalCase=L.toSnakeCase=L.toCamelCase=void 0;var n=Is();L.toCamelCase=n.default;var e=_s();L.toSnakeCase=e.default;var t=xs();L.toPascalCase=t.default;var s=So();L.toDotCase=s.default;var i=ko();L.toPathCase=i.default;var r=Co();L.toTextCase=r.default;var o=vo();L.toSentenceCase=o.default;var a=Ao();L.toHeaderCase=a.default;var c=Bs();L.toKebabCase=c.default;var u=Oo();L.lowerKeys=u.default;var d=Eo();L.upperKeys=d.default;var f=To();L.camelKeys=f.default;var h=$o();L.snakeKeys=h.default;var m=Io();L.pascalKeys=m.default;var w=No();L.kebabKeys=w.default;var p=l(function(b){return String(b||"").toLowerCase()},"toLowerCase");L.toLowerCase=p;var g=l(function(b){return String(b||"").toUpperCase()},"toUpperCase");L.toUpperCase=g;var S={toCamelCase:n.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:s.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:g,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return L.default=S,L}l(_o,"requireLib");var An,Gs;function Lo(){return Gs||(Gs=1,An=_o()),An}l(Lo,"requireJsConvertCase");var je=Lo();const H={[M.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(n=>({id:n.id,key:n.key,name:n.name,connectorId:n.connectorId,baseUri:n.baseUri,connectorVersion:n.connectorVersion}),"exportCleanup")},[M.Connector]:{element:"connector",elements:"connectors",exportable:!1},[M.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(n=>(delete n.integration,n),"exportCleanup")},[M.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[M.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[M.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[M.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[M.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,exportCleanup:l(n=>(delete n.dataSourceId,n),"exportCleanup")},[M.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0}};function xo(n){return delete n.workspaceId,delete n.createdAt,delete n.updatedAt,delete n.revision,delete n.parentRevision,Object.keys(n).map(e=>{e.match(/universal.*Revision/g)&&delete n[e]}),n}l(xo,"baseExportCleanup");class Po{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return gt.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=be(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 an({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const s=!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||s||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const On=new Po;async function Ys(n){const e=await On.getClient(n);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(Ys,"getWorkspaceId");class jo{static{l(this,"RemoteElementsManagerService")}client;elementsCache={};async pull(){this.elementsCache[M.Integration]=await this.getIntegrations();const e=[M.Integration,M.Connector];for(const t of Object.keys(H)){if(e.includes(t))continue;V.info(`Pulling ${t}...`);const s=await this.pullElements(t);this.elementsCache[t]=s,V.success(`Pulled ${s.length} ${t}${s.length!==1?"s":""}`)}return this.elementsCache}async pullElements(e){const s=(await this.findAll(e)).map(i=>this.cleanup(e,i));if(!this.canBeIntegrationSpecific(e))return s;for(const i of this.elementsCache[M.Integration]){V.info(`Pulling ${e} elements for integration ${i.key}`);const o=(await this.findAll(e,{integrationKey:i.key})).map(a=>({integrationKey:i.key,...this.cleanup(e,a)}));s.push(...o)}return s}async pushElement(e,t){if(!H[e])throw new Error(`Unknown element type: ${e}`);const i={...t};await this.pull(),delete i.integrationId;const r=this.matchElement(i,e);r?await this.handleExistingElement(e,i,r):await this.handleNewElement(e,i)}cleanup(e,t){return H[e]?.exportCleanup?H[e].exportCleanup(t):this.baseExportCleanup(t)}canBeIntegrationSpecific(e){return H[e]?.integrationSpecific}baseExportCleanup(e){return delete e.workspaceId,delete e.createdAt,delete e.updatedAt,delete e.revision,delete e.parentRevision,Object.keys(e).map(t=>{t.match(/universal.*Revision/g)&&delete e[t]}),e}findIntegrationId(e){const s=this.elementsCache.integration?.find(i=>i.key===e);if(!s)throw new Error(`Integration with key ${e} not found`);return s.id}matchElement(e,t){const s=this.elementsCache[t]?.filter(i=>i.key===e.key&&i.integrationKey===e.integrationKey&&!i.archivedAt);if(!(!s||s.length===0)){if(s.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return s[0]}}async handleExistingElement(e,t,s){const i=H[e],r=await this.getClient(),o=je.toCamelCase(ee[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await r[o](s.id).put(t),V.info(`Updated ${t.integrationKey||"universal"} ${i.element} ${t.key}`);else if(this.hasParent(t))try{await r[o](s.id).reset(),V.info(`Customization reset ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw V.error(`Error resetting element: ${s.id} ${t.key}`),a}else V.warning(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}async handleNewElement(e,t){const s=H[e],i=await this.getClient(),r=je.toCamelCase(ee[e].name),o=je.toCamelCase(ee[e].namePlural);if(this.hasParent(t)){try{await i[r]({key:t.key}).apply([t.integrationKey])}catch{try{await i[r]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey);await i[o].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await i[r]({key:t.key,integrationKey:t.integrationKey}).put(t),V.success(`Applied & Customized ${t.integrationKey||"universal"} ${s.element} ${t.key}`)}catch(a){throw V.error(`Error customizing element: ${t.key}`),a}else V.success(`Applied universal ${s.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const a=this.findIntegrationId(t.integrationKey);t.integrationId=a}await i[o].create(t),V.success(`Created ${t.integrationKey||"universal"} ${s.element} ${t.key}`)}catch(a){throw V.error(`Error creating element ${e} ${t.key} for integration ${t.integrationKey}`),a}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}async findById(e,t){return(await this.getClient())[e](t).get()}async findByKey(e,t,s={}){return(await this.getClient())[e](t).get(s)}async findAll(e,t={}){return(await this.getClient())[H[e].elements].findAll(t)}async create(e,t){return(await this.getClient())[e].create(t)}async update(e,t){if(!t.id)throw new Error("Element must have an id to update");return(await this.getClient())[e](t.id).put(t)}async put(e,t){return t.id?this.update(e,t):this.create(e,t)}async reset(e,t){if(!t.id)throw new Error("Element must have an id to reset");return(await this.getClient())[e](t.id).reset()}async apply(e,t){if(!t.id)throw new Error("Element must have an id to apply");return(await this.getClient())[e](t.id).apply()}async archive(e,t){if(!t.id)throw new Error("Element must have an id to archive");await(await this.getClient())[e](t.id).archive()}async getIntegrations(){return(await this.getClient()).integrations.findAll()}async exists(e,t){try{return await this.findById(e,t),!0}catch{return!1}}async getClient(){return this.client||(this.client=await On.getClient(process.cwd())),this.client}}const En=Symbol.for("yaml.alias"),Tn=Symbol.for("yaml.document"),pe=Symbol.for("yaml.map"),Zs=Symbol.for("yaml.pair"),ce=Symbol.for("yaml.scalar"),Ke=Symbol.for("yaml.seq"),ne=Symbol.for("yaml.node.type"),me=l(n=>!!n&&typeof n=="object"&&n[ne]===En,"isAlias"),Se=l(n=>!!n&&typeof n=="object"&&n[ne]===Tn,"isDocument"),De=l(n=>!!n&&typeof n=="object"&&n[ne]===pe,"isMap"),B=l(n=>!!n&&typeof n=="object"&&n[ne]===Zs,"isPair"),R=l(n=>!!n&&typeof n=="object"&&n[ne]===ce,"isScalar$1"),Me=l(n=>!!n&&typeof n=="object"&&n[ne]===Ke,"isSeq");function q(n){if(n&&typeof n=="object")switch(n[ne]){case pe:case Ke:return!0}return!1}l(q,"isCollection$1");function U(n){if(n&&typeof n=="object")switch(n[ne]){case En:case pe:case ce:case Ke:return!0}return!1}l(U,"isNode");const Qs=l(n=>(R(n)||q(n))&&!!n.anchor,"hasAnchor"),X=Symbol("break visit"),Xs=Symbol("skip children"),le=Symbol("remove node");function ke(n,e){const t=ei(e);Se(n)?Re(null,n.contents,t,Object.freeze([n]))===le&&(n.contents=null):Re(null,n,t,Object.freeze([]))}l(ke,"visit$1"),ke.BREAK=X,ke.SKIP=Xs,ke.REMOVE=le;function Re(n,e,t,s){const i=ti(n,e,t,s);if(U(i)||B(i))return ni(n,s,i),Re(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=Re(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===le&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){s=Object.freeze(s.concat(e));const r=Re("key",e.key,t,s);if(r===X)return X;r===le&&(e.key=null);const o=Re("value",e.value,t,s);if(o===X)return X;o===le&&(e.value=null)}}return i}l(Re,"visit_");async function Tt(n,e){const t=ei(e);Se(n)?await Be(null,n.contents,t,Object.freeze([n]))===le&&(n.contents=null):await Be(null,n,t,Object.freeze([]))}l(Tt,"visitAsync"),Tt.BREAK=X,Tt.SKIP=Xs,Tt.REMOVE=le;async function Be(n,e,t,s){const i=await ti(n,e,t,s);if(U(i)||B(i))return ni(n,s,i),Be(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=await Be(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===X)return X;o===le&&(e.items.splice(r,1),r-=1)}}}else if(B(e)){s=Object.freeze(s.concat(e));const r=await Be("key",e.key,t,s);if(r===X)return X;r===le&&(e.key=null);const o=await Be("value",e.value,t,s);if(o===X)return X;o===le&&(e.value=null)}}return i}l(Be,"visitAsync_");function ei(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}l(ei,"initVisitor");function ti(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(De(e))return t.Map?.(n,e,s);if(Me(e))return t.Seq?.(n,e,s);if(B(e))return t.Pair?.(n,e,s);if(R(e))return t.Scalar?.(n,e,s);if(me(e))return t.Alias?.(n,e,s)}l(ti,"callVisitor");function ni(n,e,t){const s=e[e.length-1];if(q(s))s.items[n]=t;else if(B(s))n==="key"?s.key=t:s.value=t;else if(Se(s))s.contents=t;else{const i=me(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(ni,"replaceNode");const Ko={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Do=l(n=>n.replace(/[!,[\]{}]/g,e=>Ko[e]),"escapeTagName");class Q{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},Q.defaultYaml,e),this.tags=Object.assign({},Q.defaultTags,t)}clone(){const e=new Q(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new Q(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:Q.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},Q.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:Q.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},Q.defaultTags),this.atNextDocument=!1);const s=e.trim().split(/[ \t]+/),i=s.shift();switch(i){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[r,o]=s;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=s;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[,s,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Do(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&U(e.contents)){const r={};ke(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of s)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
3
- `)}}Q.defaultYaml={explicit:!1,version:"1.2"},Q.defaultTags={"!!":"tag:yaml.org,2002:"};function si(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}l(si,"anchorIsValid");function ii(n){const e=new Set;return ke(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}l(ii,"anchorNames");function ri(n,e){for(let t=1;;++t){const s=`${n}${t}`;if(!e.has(s))return s}}l(ri,"findNewAnchor");function Mo(n,e){const t=[],s=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=ii(n));const o=ri(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=s.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:s}}l(Mo,"createNodeAnchors");function Fe(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let i=0,r=s.length;i<r;++i){const o=s[i],a=Fe(n,s,String(i),o);a===void 0?delete s[i]:a!==o&&(s[i]=a)}else if(s instanceof Map)for(const i of Array.from(s.keys())){const r=s.get(i),o=Fe(n,s,i,r);o===void 0?s.delete(i):o!==r&&s.set(i,o)}else if(s instanceof Set)for(const i of Array.from(s)){const r=Fe(n,s,i,i);r===void 0?s.delete(i):r!==i&&(s.delete(i),s.add(r))}else for(const[i,r]of Object.entries(s)){const o=Fe(n,s,i,r);o===void 0?delete s[i]:o!==r&&(s[i]=o)}return n.call(e,t,s)}l(Fe,"applyReviver");function se(n,e,t){if(Array.isArray(n))return n.map((s,i)=>se(s,String(i),t));if(n&&typeof n.toJSON=="function"){if(!t||!Qs(n))return n.toJSON(e,t);const s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=r=>{s.res=r,delete t.onCreate};const i=n.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof n=="bigint"&&!t?.keep?Number(n):n}l(se,"toJS");class $n{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,ne,{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:s,onAnchor:i,reviver:r}={}){if(!Se(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 s=="number"?s:100},a=se(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?Fe(r,{"":a},"",a):a}}class $t extends $n{static{l(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 s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],ke(e,{Node:l((r,o)=>{(me(o)||Qs(o))&&s.push(o)},"Node")}),t&&(t.aliasResolveCache=s));let i;for(const r of s){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:s,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(se(o,null,t),a=s.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=It(i,o,s)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,s){const i=`*${this.source}`;if(e){if(si(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 It(n,e,t){if(me(e)){const s=e.resolve(n),i=t&&s&&t.get(s);return i?i.count*i.aliasCount:0}else if(q(e)){let s=0;for(const i of e.items){const r=It(n,i,t);r>s&&(s=r)}return s}else if(B(e)){const s=It(n,e.key,t),i=It(n,e.value,t);return Math.max(s,i)}return 1}l(It,"getAliasCount");const oi=l(n=>!n||typeof n!="function"&&typeof n!="object","isScalarValue");class _ extends $n{static{l(this,"Scalar")}constructor(e){super(ce),this.value=e}toJSON(e,t){return t?.keep?this.value:se(this.value,e,t)}toString(){return String(this.value)}}_.BLOCK_FOLDED="BLOCK_FOLDED",_.BLOCK_LITERAL="BLOCK_LITERAL",_.PLAIN="PLAIN",_.QUOTE_DOUBLE="QUOTE_DOUBLE",_.QUOTE_SINGLE="QUOTE_SINGLE";const Ro="tag:yaml.org,2002:";function Bo(n,e,t){if(e){const s=t.filter(r=>r.tag===e),i=s.find(r=>!r.format)??s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>s.identify?.(n)&&!s.format)}l(Bo,"findTagObject");function st(n,e,t){if(Se(n)&&(n=n.contents),U(n))return n;if(B(n)){const f=t.schema[pe].createNode?.(t.schema,null,t);return f.items.push(n),f}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:s,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(s&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=i(n)),new $t(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=Ro+e.slice(2));let u=Bo(n,e,o.tags);if(!u){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){const f=new _(n);return c&&(c.node=f),f}u=n instanceof Map?o[pe]:Symbol.iterator in Object(n)?o[Ke]:o[pe]}r&&(r(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,n,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,n,t):new _(n);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}l(st,"createNode");function Nt(n,e,t){let s=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]=s,s=o}else s=new Map([[r,s]])}return st(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:n,sourceObjects:new Map})}l(Nt,"collectionFromPath");const it=l(n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,"isEmptyPath");class ai extends $n{static{l(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(s=>U(s)||B(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(it(e))this.add(t);else{const[s,...i]=e,r=this.get(s,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(s,Nt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}deleteIn(e){const[t,...s]=e;if(s.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){const[s,...i]=e,r=this.get(s,!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(!B(t))return!1;const s=t.value;return s==null||e&&R(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){const[t,...s]=e;if(s.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(s):!1}setIn(e,t){const[s,...i]=e;if(i.length===0)this.set(s,t);else{const r=this.get(s,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(s,Nt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}}const Fo=l(n=>n.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function ue(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}l(ue,"indentComment");const Ce=l((n,e,t)=>n.endsWith(`
4
- `)?ue(t,e):t.includes(`
2
+ var _r=Object.defineProperty;var l=(s,e)=>_r(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as E,Fragment as Dr}from"react/jsx-runtime";import*as K from"node:path";import{resolve as jr,dirname as Kr,join as Rr}from"node:path";import{useInput as Pe,Box as b,Text as S,Newline as Mr,render as gn}from"ink";import Br from"minimist";import{SWRConfig as Fr}from"swr";import qr from"os";import j from"path";import Ur from"conf";import kt,{createContext as yn,useContext as wn,useState as R,useEffect as me,useCallback as Cs,useMemo as Jr,useRef as vs}from"react";import*as L from"node:fs";import{readFileSync as Vr}from"node:fs";import fe from"js-yaml";import{z as U}from"zod";import{exec as Wr}from"node:child_process";import*as bn from"node:crypto";import{createHash as zr}from"node:crypto";import*as Gr from"node:os";import{TextInput as Hr,Select as Yr}from"@inkjs/ui";import Ct from"ink-spinner";import Es from"swr/immutable";import Zr from"ink-text-input";import{EventEmitter as Qr}from"events";import{WorkspaceElementType as P,WorkspaceElementSpecs as ie,IntegrationAppClient as Sn,setValueAtLocator as kn,extractIntegrationAppErrorData as de,getDataCollectionCreateFields as Cn,excludeWriteOnlyFieldsFromSchema as Ts,valueToSchema as vt,getRequiredFieldsFromSchema as Xr,getValueAtLocator as eo,walkSchema as As,makeDataLocationPath as Os,getDataCollectionUpdateFields as vn}from"@membranehq/sdk";import Et from"jsonwebtoken";import to from"chokidar";import D from"fs";import no from"archiver";import so from"form-data";import io from"unzipper";import v from"chalk";import{fileURLToPath as ro}from"node:url";import{Command as oo}from"commander";import En from"axios";import{FastMCP as ao}from"fastmcp";import Tn from"lodash/merge.js";import co from"@anthropic-ai/sdk";import{faker as rt}from"@faker-js/faker";import lo from"lodash/template.js";import uo from"lodash/templateSettings.js";const fo="membrane",ho="membrane.config.yml",An="https://api.integration.app";function ot(){const s=process.cwd(),e=K.join(s,fo),t=K.join(s,ho),n=e,i=K.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:i}}l(ot,"getPaths");function po(){return ot().membraneDirPath}l(po,"getBasePath");const mo={pat:{type:"string"},workspace:{type:"object"}},Is=new Ur({schema:mo,configName:"config",cwd:j.join(qr.homedir(),".membrane")}),go=l(s=>{Is.set("pat",s)},"setPat"),$s=l(()=>Is.get("pat"),"getPat");class Ns{static{l(this,"AccountApiClient")}constructor(e=An){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=$s();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 yo=l(s=>{const e=new Ns(An);return t=>e.get(t)},"createAccountApiFetcher"),xs=yn(process.cwd());function wo({cwd:s,children:e}){return g(xs.Provider,{value:s,children:e})}l(wo,"CwdProvider");function Ls(){return wn(xs)}l(Ls,"useCwd");const bo="membrane.config.yml";function Te(s){const e=K.join(s??process.cwd(),bo);try{const t=L.readFileSync(e,"utf8"),n=fe.load(t),i=Ps.safeParse(n);return i.success?i.data:null}catch{return null}}l(Te,"readProjectConfig");const So="membrane.config.yml",Ps=U.object({workspaceKey:U.string().optional(),workspaceSecret:U.string().optional(),apiUri:U.string().optional(),testCustomerId:U.string().optional(),anthropicApiKey:U.string().optional()});U.enum(["pull"]);const _s=yn(void 0);function ko({children:s}){const e=Ls(),[t,n]=R(null),[i,r]=R(!0);me(()=>{const u=Te(e);n(u),r(!1)},[e]);const o=Cs(u=>{const f=K.join(e,So),h={...Te(e)??{},...u},m=Ps.safeParse(h);return m.success?(L.writeFileSync(f,fe.dump(m.data)),n(m.data),!0):!1},[e]),a=Cs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return g(_s.Provider,{value:c,children:s})}l(ko,"ProjectConfigProvider");function at(){const s=wn(_s);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}l(at,"useProjectConfig");function On({cwd:s,children:e}){const t=s||process.cwd();return g(wo,{cwd:t,children:g(ko,{children:g(Fr,{value:{fetcher:yo()},children:e})})})}l(On,"Layout");const In=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const s=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const i={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Co({onExit:s,onComplete:e}){const[t,n]=R(0),[i,r]=R(!1),[o,a]=R(null),[c,u]=R(""),[f,d]=R("");Pe((w,p)=>{if(c||f){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)s();else if(p.upArrow||w==="k")n(Math.max(0,t-1));else if(p.downArrow||w==="j")n(Math.min(In.length-1,t+1));else if(p.return||w===" "){const y=In[t];a(y),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){d(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(S,{color:"green",children:"Success"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[g(S,{color:"green",children:c}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(b,{marginTop:1,paddingLeft:2,children:g(S,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(S,{color:"red",children:"Error"})]})}),g(b,{flexDirection:"column",paddingLeft:2,children:g(S,{color:"red",children:f})}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(S,{color:"cyan",children:"Confirmation"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[E(S,{children:["Connect ",g(S,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(b,{marginTop:1,children:g(S,{color:"yellow",bold:!0,children:o.actionDescription})}),g(b,{marginTop:2,marginBottom:1,children:E(S,{children:[g(S,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(S,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(S,{color:"cyan",children:"Select Agent"})]})}),E(b,{flexDirection:"column",paddingLeft:2,children:[g(S,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(b,{marginTop:1,flexDirection:"column",children:In.map((w,p)=>E(b,{children:[E(S,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),E(S,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(Co,"AddMcpServerScreen");const be=K.join(Gr.tmpdir(),"membrane-mcp-status"),Ds=3e4;function $n(s){return zr("md5").update(s).digest("hex").slice(0,8)}l($n,"getCwdHash");function Nn(s,e){const t=$n(e);return K.join(be,`mcp-${t}-${s}.json`)}l(Nn,"getStatusFilePath");function _e(s,e){try{const t=e||process.cwd();if(!s){const i=Tt(t);return i.length===0?null:i[0]}const n=Nn(s,t);if(L.existsSync(n)){const i=L.statSync(n),r=new Date;if(r.getTime()-i.mtime.getTime()>Ds)return ct(s,t),null;const a=L.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>Ds)return ct(s,t),null}return c}}catch{s&&e&&ct(s,e)}return null}l(_e,"getMcpStatus");function Tt(s){try{const e=s||process.cwd(),t=$n(e);if(!L.existsSync(be))return[];const n=L.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),c=_e(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(Tt,"getAllMcpStatusFiles");function xn(s){try{const t={..._e(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(be)||L.mkdirSync(be,{recursive:!0});const n=Nn(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(xn,"updateMcpStatus");function ct(s,e){try{const t=e||process.cwd();if(s){const n=Nn(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=$n(t);if(L.existsSync(be)){const i=L.readdirSync(be);for(const r of i)r.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(be,r))}}}catch{}}l(ct,"clearMcpStatus");function vo(s,e){const t=_e(s,e);t&&xn({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(vo,"trackToolExecution");function Eo(){const[s,e]=R(_e()),[t,n]=R(Tt()),[i,r]=R(null);return me(()=>{try{const a=process.cwd();e(_e(void 0,a)),n(Tt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),n([])}const o=setInterval(()=>{try{const a=process.cwd(),c=_e(void 0,a),u=Tt(a);e(c),n(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),n([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:s,allMcpServers:t,error:i,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(Eo,"useMcpStatus");function To(){const{error:s,serverCount:e,allMcpServers:t}=Eo(),n=Math.min(100,process.stdout.columns||100);return E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(b,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(S,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(S,{color:"red",children:"error reading status"}):e===0?g(S,{color:"yellow",children:"none"}):g(S,{color:"green",children:e})]})}),!s&&e===0&&g(b,{marginTop:1,children:E(S,{color:"grey",children:["Connect your AI agents to Membrane.",g(Mr,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(b,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((i,r)=>g(b,{children:E(S,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"[a: connect an agent]"})})]})}l(To,"Agent");function js({onExit:s,showEscOption:e=!0}){const[t,n]=R(""),{data:i,error:r,isLoading:o}=Es("/account"),{updateConfig:a,isLoading:c}=at(),u=i?.workspaces,f=o||c;if(Pe((y,C)=>{C.escape&&s?.()}),f)return E(b,{children:[g(Ct,{}),g(S,{children:" Fetching workspaces..."})]});if(r)return E(b,{flexDirection:"column",children:[E(S,{color:"red",children:["Error: ",r.message]}),g(b,{marginTop:1,children:g(S,{color:"grey",children:"Press ESC to go back"})})]});const d=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],h=d.map(y=>({label:y.name,value:y.id})),m=h.length,w=u?.length??0;async function p(y){const C=d.find(T=>T.id===y);if(!C)return;const{key:k,secret:O}=C;!k||!O||(await a({workspaceKey:k,workspaceSecret:O}),s?.())}return l(p,"handleSelect"),E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(b,{marginTop:-1,children:g(S,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(b,{marginTop:1,children:[g(S,{children:"Search: "}),g(Hr,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&E(S,{children:["Showing ",m," of ",w," workspaces."]}),g(b,{marginTop:1,children:g(Yr,{options:h,onChange:l(y=>{y&&p(y)},"onChange")})}),e&&g(b,{marginTop:1,children:g(S,{color:"grey",children:"Press ESC to go back"})})]})}l(js,"SelectWorkspace");function Ao({currentPat:s,onSubmit:e}){const[t,n]=R(""),[i,r]=R(!1),[o,a]=R(null);return E(b,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(b,{marginTop:-1,marginBottom:1,children:g(S,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(S,{children:"Please provide your Personal Access Token. You can find it here:"}),g(b,{marginTop:1,marginBottom:1,children:g(S,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(S,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Zr,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&g(b,{marginTop:1,children:E(S,{children:[g(Ct,{type:"dots"})," Validating token..."]})}),o&&g(S,{color:"red",children:o})]})}l(Ao,"PersonalAccessTokenInput");var lt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(lt||{});const Oo={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ks=l(()=>{const{config:s}=at(),e=!!(s?.workspaceKey&&s?.workspaceSecret);return{workspaceIsConfigured:e,isSetupComplete:e}},"useSetup"),Ln=[lt.Authenticate,lt.ConnectWorkspace];function Rs({onComplete:s}){const[e,t]=R(!1),[n,i]=R(0),{isSetupComplete:r}=Ks(),o=$s(),a=Ln[n],c=n+1,u=Ln.length,f=Ln.map((m,w)=>{let p="pending";return w<n?p="done":w===n&&(p="current"),{id:m,label:Oo[m],status:p}});async function d(m){const w=o&&m===""?o:m,p=new Ns;try{await p.request("/account",{headers:{Authorization:`Bearer ${w}`}}),go(w),i(y=>y+1)}catch(y){console.error(y)}}l(d,"handlePatSubmit");function h(){t(!0),s&&s()}return l(h,"handleWorkspaceSelected"),Pe((m,w)=>{r&&w.escape&&s&&s()}),e?g(b,{children:g(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:[g(b,{marginTop:-1,marginBottom:1,children:E(S,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(S,{color:"cyan",children:["Step ",c," of ",u]}),r&&g(S,{color:"grey",children:" [esc: go back]"})]})}),g(b,{flexDirection:"column",paddingLeft:2,children:f.map(m=>g(Io,{status:m.status,label:m.label},m.id))})]}),a===lt.Authenticate&&g(Ao,{currentPat:o,onSubmit:d}),a===lt.ConnectWorkspace&&g(js,{onExit:h,showEscOption:!1})]})}l(Rs,"Setup");function Io({status:s,label:e}){return E(b,{children:[E(b,{width:2,children:[s==="current"&&g(Ct,{type:"dots"}),s==="done"&&g(S,{children:"\u2705"})]}),g(S,{dimColor:s!=="current",children:e})]})}l(Io,"StepDisplay");class At extends Qr{static{l(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const Ot={Pull:"pull",Exit:"exit"};class $o extends At{static{l(this,"WorkspaceCommands")}constructor(){super()}pull(e={}){this.emit(Ot.Pull,e)}exit(){this.emit(Ot.Exit)}}const ut=new $o,H={[P.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[P.Connector]:{element:"connector",elements:"connectors",exportable:!1},[P.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(s=>(delete s.integration,s),"exportCleanup")},[P.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[P.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[P.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[P.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[P.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:l(s=>(delete s.dataSourceId,s),"exportCleanup")},[P.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"}};function No(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}l(No,"baseExportCleanup");const xo="membrane",Lo=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function It(s){return K.join(s,xo)}l(It,"getMembraneDir");const Po=["id","workspaceId","integrationId","createdAt","updatedAt","revision","parentRevision","archivedAt"],Ms=[P.Action,P.FieldMapping,P.Flow,P.DataSource];class Q{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,i){if(!i)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=i,this.integrationKey=n||Q.extractIntegrationKey(i)}get id(){return this.type===P.Integration?`${this.type}:${this.key}`:Q.isIntegrationSpecific(this.type)?`${this.integrationKey||"universal"}:${this.type}:${this.key}`:`${this.type}:${this.key}`}get dirPath(){const e=ie[this.type].apiPath;if(this.integrationKey){const t=ie[P.Integration].apiPath;return K.join(t,this.integrationKey,e,this.key)}return K.join(e,this.key)}get path(){return K.join(this.dirPath,"spec.yaml")}get relativePath(){return K.relative(It(process.cwd()),this.path)}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean(),i=bn.createHash("sha256").update(JSON.stringify(t,Object.keys(t).sort())).digest("hex"),r=bn.createHash("sha256").update(JSON.stringify(n,Object.keys(n).sort())).digest("hex");return i===r}hasParent(){return!!this.data?.[this.getParentKey()]}clean(){const e={...this.data};return Po.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return H?.[this.type]?.parentKey&&(e=H?.[this.type]?.parentKey),e}static new(e,t,n,i){return new Q(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 Q(e,t.key,n,t)}static fromPathAndData(e,t){const n=Q.parsePath(e);if(n)return Q.new(n.type,n.key,n.integrationKey,t)}static fromElement(e){return new Q(e.type,e.key,e.integrationKey,{...e.data})}static parsePath(e){const t=this.getRelativePath(e);if(this.isConnectorFile(t)||!this.isElementFile(t))return;const n=Object.values(ie).map(c=>c.apiPath).join("|"),i=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),r=t.match(i);if(r?.groups){const{elementType:c,elementKey:u}=r.groups,f=this.getElementTypeFromPath(c);if(f)return{type:f,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:c,elementType:u,elementKey:f}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:f,integrationKey:c}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static isConnectorFile(e){const[t]=e.split(K.sep);return t===ie[P.Connector].apiPath}static getElementTypeFromPath(e){return Object.values(P).find(t=>ie[t].apiPath===e)}static getRelativePath(e){return K.relative(It(process.cwd()),e)}static isIntegrationSpecific(e){return Ms.includes(e)}static canBeIntegrationSpecific(e){return Ms.includes(e)}}const Pn={NewLog:"NewLog"};class _o extends At{static{l(this,"WorkspaceLogger")}_logs=[];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.emit(Pn.NewLog)}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=[],this.emit(Pn.NewLog)}}const F=new _o;class Bs{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;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()}}class Do{static{l(this,"LocalElementsManagerService")}elements;basePath;constructor(){this.basePath=It(process.cwd()),this.elements=new Bs}async read(){this.elements.clear(),await this.readElementsByType(P.Integration);const e=[P.Integration,P.Connector],t=Object.keys(H);return Promise.all(t.filter(n=>!e.includes(n)).map(async n=>{await this.readElementsByType(n)}))}async readElementsByType(e){const t=K.join(this.basePath,ie[e].apiPath);await this.readElementsInDir(t);const n=this.elements.getElementsByType(P.Integration);for(const i of n){const r=K.join(this.basePath,ie[P.Integration].apiPath,i.key,ie[e].apiPath);await this.readElementsInDir(r)}}async readElement(e){if(!L.existsSync(e))return null;const t=L.readFileSync(e,"utf8"),n=fe.load(t);return n?Q.fromPathAndData(e,n):null}async writeElement(e){if(!e.data)throw new Error("Element must have data to write");const t=K.join(this.basePath,e.dirPath),n=K.join(this.basePath,e.path);L.existsSync(t)||L.mkdirSync(t,{recursive:!0}),L.writeFileSync(n,fe.dump(e.data)),this.elements.put(e),F.success(`Written ${e.type} key: ${e.key}`)}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.elements.remove(e),this.pruneEmptyDir(n),F.success(`Deleted ${e.type} key: ${e.key}`)}async readElementsInDir(e){if(!L.existsSync(e))return;const t=L.readdirSync(e);if(t.length===0)return;const n=t.map(async i=>{const r=K.join(e,i,"spec.yaml");return this.readElement(r)});this.elements.addAll(await Promise.all(n))}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class jo{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return Et.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 Sn({token:t,apiUri:e.apiUri})}async getClient(e){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 _n=new jo;async function Fs(s){const e=await _n.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(Fs,"getWorkspaceId");class Ko{static{l(this,"RemoteElementsManagerService")}client;elements;constructor(){this.elements=new Bs}async pull(){this.elements.clear(),await this.getIntegrations();const e=[P.Integration,P.Connector],t=Object.keys(H);return Promise.all(t.filter(n=>!e.includes(n)).map(async n=>{const i=await this.pullElements(n);this.elements.addAll(i)}))}async pullElements(e){const t=await this.findAll(e);if(!Q.canBeIntegrationSpecific(e))return t;const n=this.elements.getElementsByType(P.Integration);for(const i of n){const r=i.key;F.info(`Pulling ${e} elements for integration ${r}`);const o=await this.findAll(e,{integrationKey:r});t.push(...o)}return F.success(`Pulled ${t.length} ${e}${t.length!==1?"s":""}`),t}async pushElement(e){return this.elements.get(e.id)?this.update(e):this.create(e)}findIntegrationId(e){const t=this.elements.getElementsByType(P.Integration);for(const n of t)if(n.key===e)return n.data.id;throw new Error(`Integration not found: ${e}`)}async put(e){return e.data.id?this.update(e):this.create(e)}async create(e){F.info(`Creating ${e.type} key: ${e.key}`);const t=e.clean(),i=await(await this.getClient())[ie[e.type].apiPath].create(t),r=Q.fromData(e.type,i);this.elements.put(r),F.success(`Created ${e.type} key: ${e.key}`)}async update(e){if(F.info(`Updating ${e.type} key: ${e.key}`),!e.data.id)throw new Error("Element must have an id to update");const t=e.clean(),i=await(await this.getClient())[e.type](e.data.id).put(t),r=Q.fromData(e.type,i);this.elements.put(r),F.success(`Updated ${e.type} key: ${e.key}`)}async findAll(e,t={}){return(await(await this.getClient())[H[e].elements].findAll(t)).map(r=>Q.fromData(e,r))}async findById(e){const n=await(await this.getClient())[e.type](e.data.id).get();return Q.fromData(e.type,n)}async getIntegrations(){const t=await(await this.getClient()).integrations.findAll();this.elements.addAll(t.map(n=>Q.fromData(P.Integration,n)))}async getClient(){return this.client||(this.client=await _n.getClient(process.cwd())),this.client}}const Dn=Symbol.for("yaml.alias"),jn=Symbol.for("yaml.document"),Se=Symbol.for("yaml.map"),qs=Symbol.for("yaml.pair"),he=Symbol.for("yaml.scalar"),De=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),ke=l(s=>!!s&&typeof s=="object"&&s[oe]===Dn,"isAlias"),Ae=l(s=>!!s&&typeof s=="object"&&s[oe]===jn,"isDocument"),je=l(s=>!!s&&typeof s=="object"&&s[oe]===Se,"isMap"),q=l(s=>!!s&&typeof s=="object"&&s[oe]===qs,"isPair"),M=l(s=>!!s&&typeof s=="object"&&s[oe]===he,"isScalar$1"),Ke=l(s=>!!s&&typeof s=="object"&&s[oe]===De,"isSeq");function J(s){if(s&&typeof s=="object")switch(s[oe]){case Se:case De:return!0}return!1}l(J,"isCollection$1");function V(s){if(s&&typeof s=="object")switch(s[oe]){case Dn:case Se:case he:case De:return!0}return!1}l(V,"isNode");const Us=l(s=>(M(s)||J(s))&&!!s.anchor,"hasAnchor"),ne=Symbol("break visit"),Js=Symbol("skip children"),pe=Symbol("remove node");function Oe(s,e){const t=Vs(e);Ae(s)?Re(null,s.contents,t,Object.freeze([s]))===pe&&(s.contents=null):Re(null,s,t,Object.freeze([]))}l(Oe,"visit$1"),Oe.BREAK=ne,Oe.SKIP=Js,Oe.REMOVE=pe;function Re(s,e,t,n){const i=Ws(s,e,t,n);if(V(i)||q(i))return zs(s,n,i),Re(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=Re(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ne)return ne;o===pe&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=Re("key",e.key,t,n);if(r===ne)return ne;r===pe&&(e.key=null);const o=Re("value",e.value,t,n);if(o===ne)return ne;o===pe&&(e.value=null)}}return i}l(Re,"visit_");async function $t(s,e){const t=Vs(e);Ae(s)?await Me(null,s.contents,t,Object.freeze([s]))===pe&&(s.contents=null):await Me(null,s,t,Object.freeze([]))}l($t,"visitAsync"),$t.BREAK=ne,$t.SKIP=Js,$t.REMOVE=pe;async function Me(s,e,t,n){const i=await Ws(s,e,t,n);if(V(i)||q(i))return zs(s,n,i),Me(s,i,t,n);if(typeof i!="symbol"){if(J(e)){n=Object.freeze(n.concat(e));for(let r=0;r<e.items.length;++r){const o=await Me(r,e.items[r],t,n);if(typeof o=="number")r=o-1;else{if(o===ne)return ne;o===pe&&(e.items.splice(r,1),r-=1)}}}else if(q(e)){n=Object.freeze(n.concat(e));const r=await Me("key",e.key,t,n);if(r===ne)return ne;r===pe&&(e.key=null);const o=await Me("value",e.value,t,n);if(o===ne)return ne;o===pe&&(e.value=null)}}return i}l(Me,"visitAsync_");function Vs(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}l(Vs,"initVisitor");function Ws(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(je(e))return t.Map?.(s,e,n);if(Ke(e))return t.Seq?.(s,e,n);if(q(e))return t.Pair?.(s,e,n);if(M(e))return t.Scalar?.(s,e,n);if(ke(e))return t.Alias?.(s,e,n)}l(Ws,"callVisitor");function zs(s,e,t){const n=e[e.length-1];if(J(n))n.items[s]=t;else if(q(n))s==="key"?n.key=t:n.value=t;else if(Ae(n))n.contents=t;else{const i=ke(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(zs,"replaceNode");const Ro={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Mo=l(s=>s.replace(/[!,[\]{}]/g,e=>Ro[e]),"escapeTagName");class te{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},te.defaultYaml,e),this.tags=Object.assign({},te.defaultTags,t)}clone(){const e=new te(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new te(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:te.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},te.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:te.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},te.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+Mo(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&&V(e.contents)){const r={};Oe(e.contents,(o,a)=>{V(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
+ `)}}te.defaultYaml={explicit:!1,version:"1.2"},te.defaultTags={"!!":"tag:yaml.org,2002:"};function Gs(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}l(Gs,"anchorIsValid");function Hs(s){const e=new Set;return Oe(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(Hs,"anchorNames");function Ys(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(Ys,"findNewAnchor");function Bo(s,e){const t=[],n=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=Hs(s));const o=Ys(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=n.get(r);if(typeof o=="object"&&o.anchor&&(M(o.node)||J(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:n}}l(Bo,"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)}l(Be,"applyReviver");function ae(s,e,t){if(Array.isArray(s))return s.map((n,i)=>ae(n,String(i),t));if(s&&typeof s.toJSON=="function"){if(!t||!Us(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=r=>{n.res=r,delete t.onCreate};const i=s.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof s=="bigint"&&!t?.keep?Number(s):s}l(ae,"toJS");class Kn{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,oe,{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(!Ae(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=ae(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?Be(r,{"":a},"",a):a}}class Nt extends Kn{static{l(this,"Alias")}constructor(e){super(Dn),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],Oe(e,{Node:l((r,o)=>{(ke(o)||Us(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let i;for(const r of n){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=n.get(o);if(a||(ae(o,null,t),a=n.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=xt(i,o,n)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){const i=`*${this.source}`;if(e){if(Gs(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 xt(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(J(e)){let n=0;for(const i of e.items){const r=xt(s,i,t);r>n&&(n=r)}return n}else if(q(e)){const n=xt(s,e.key,t),i=xt(s,e.value,t);return Math.max(n,i)}return 1}l(xt,"getAliasCount");const Zs=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class N extends Kn{static{l(this,"Scalar")}constructor(e){super(he),this.value=e}toJSON(e,t){return t?.keep?this.value:ae(this.value,e,t)}toString(){return String(this.value)}}N.BLOCK_FOLDED="BLOCK_FOLDED",N.BLOCK_LITERAL="BLOCK_LITERAL",N.PLAIN="PLAIN",N.QUOTE_DOUBLE="QUOTE_DOUBLE",N.QUOTE_SINGLE="QUOTE_SINGLE";const Fo="tag:yaml.org,2002:";function qo(s,e,t){if(e){const n=t.filter(r=>r.tag===e),i=n.find(r=>!r.format)??n[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(n=>n.identify?.(s)&&!n.format)}l(qo,"findTagObject");function ft(s,e,t){if(Ae(s)&&(s=s.contents),V(s))return s;if(q(s)){const d=t.schema[Se].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=i(s)),new Nt(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Fo+e.slice(2));let u=qo(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new N(s);return c&&(c.node=d),d}u=s instanceof Map?o[Se]:Symbol.iterator in Object(s)?o[De]:o[Se]}r&&(r(u),delete t.onTagObj);const f=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new N(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(ft,"createNode");function Lt(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 ft(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}l(Lt,"collectionFromPath");const dt=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Qs extends Kn{static{l(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>V(n)||q(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(dt(e))this.add(t);else{const[n,...i]=e,r=this.get(n,!0);if(J(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(n,Lt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const i=this.get(t,!0);if(J(i))return i.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...i]=e,r=this.get(n,!0);return i.length===0?!t&&M(r)?r.value:r:J(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!q(t))return!1;const n=t.value;return n==null||e&&M(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const i=this.get(t,!0);return J(i)?i.hasIn(n):!1}setIn(e,t){const[n,...i]=e;if(i.length===0)this.set(n,t);else{const r=this.get(n,!0);if(J(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(n,Lt(this.schema,i,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${i}`)}}}const Uo=l(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function ge(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}l(ge,"indentComment");const Ie=l((s,e,t)=>s.endsWith(`
4
+ `)?ge(t,e):t.includes(`
5
5
  `)?`
6
- `+ue(t,e):(n.endsWith(" ")?"":" ")+t,"lineComment"),ci="flow",In="block",_t="quoted";function Lt(n,e,t="flow",{indentAtStart:s,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return n;i<r&&(r=0);const c=Math.max(1+r,1+i-e.length);if(n.length<=c)return n;const u=[],d={};let f=i-e.length;typeof s=="number"&&(s>i-Math.max(2,r)?u.push(0):f=i-s);let h,m,w=!1,p=-1,g=-1,S=-1;t===In&&(p=li(n,p,e.length),p!==-1&&(f=p+c));for(let C;C=n[p+=1];){if(t===_t&&C==="\\"){switch(g=p,n[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}S=p}if(C===`
7
- `)t===In&&(p=li(n,p,e.length)),f=p+e.length+c,h=void 0;else{if(C===" "&&m&&m!==" "&&m!==`
8
- `&&m!==" "){const T=n[p+1];T&&T!==" "&&T!==`
9
- `&&T!==" "&&(h=p)}if(p>=f)if(h)u.push(h),f=h+c,h=void 0;else if(t===_t){for(;m===" "||m===" ";)m=C,C=n[p+=1],w=!0;const T=p>S+1?p-2:g-1;if(d[T])return n;u.push(T),d[T]=!0,f=T+c,h=void 0}else w=!0}m=C}if(w&&a&&a(),u.length===0)return n;o&&o();let b=n.slice(0,u[0]);for(let C=0;C<u.length;++C){const T=u[C],O=u[C+1]||n.length;T===0?b=`
10
- ${e}${n.slice(0,O)}`:(t===_t&&d[T]&&(b+=`${n[T]}\\`),b+=`
11
- ${e}${n.slice(T+1,O)}`)}return b}l(Lt,"foldFlowLines");function li(n,e,t){let s=e,i=e+1,r=n[i];for(;r===" "||r===" ";)if(e<i+t)r=n[++e];else{do r=n[++e];while(r&&r!==`
12
- `);s=e,i=e+1,r=n[i]}return s}l(li,"consumeMoreIndentedLines");const xt=l((n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),"getFoldOptions"),Pt=l(n=>/^(%|---|\.\.\.)/m.test(n),"containsDocumentMarker");function qo(n,e,t){if(!e||e<0)return!1;const s=e-t,i=n.length;if(i<=s)return!1;for(let r=0,o=0;r<i;++r)if(n[r]===`
13
- `){if(r-o>s)return!0;if(o=r+1,i-o<=s)return!1}return!0}l(qo,"lineLengthOverLimit");function rt(n,e){const t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:s}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(Pt(n)?" ":"");let o="",a=0;for(let c=0,u=t[c];u;u=t[++c])if(u===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);const d=t.substr(c+2,4);switch(d){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:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||t[c+2]==='"'||t.length<i)c+=1;else{for(o+=t.slice(a,c)+`
6
+ `+ge(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Xs="flow",Rn="block",Pt="quoted";function _t(s,e,t="flow",{indentAtStart:n,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return s;i<r&&(r=0);const c=Math.max(1+r,1+i-e.length);if(s.length<=c)return s;const u=[],f={};let d=i-e.length;typeof n=="number"&&(n>i-Math.max(2,r)?u.push(0):d=i-n);let h,m,w=!1,p=-1,y=-1,C=-1;t===Rn&&(p=ei(s,p,e.length),p!==-1&&(d=p+c));for(let O;O=s[p+=1];){if(t===Pt&&O==="\\"){switch(y=p,s[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}C=p}if(O===`
7
+ `)t===Rn&&(p=ei(s,p,e.length)),d=p+e.length+c,h=void 0;else{if(O===" "&&m&&m!==" "&&m!==`
8
+ `&&m!==" "){const T=s[p+1];T&&T!==" "&&T!==`
9
+ `&&T!==" "&&(h=p)}if(p>=d)if(h)u.push(h),d=h+c,h=void 0;else if(t===Pt){for(;m===" "||m===" ";)m=O,O=s[p+=1],w=!0;const T=p>C+1?p-2:y-1;if(f[T])return s;u.push(T),f[T]=!0,d=T+c,h=void 0}else w=!0}m=O}if(w&&a&&a(),u.length===0)return s;o&&o();let k=s.slice(0,u[0]);for(let O=0;O<u.length;++O){const T=u[O],I=u[O+1]||s.length;T===0?k=`
10
+ ${e}${s.slice(0,I)}`:(t===Pt&&f[T]&&(k+=`${s[T]}\\`),k+=`
11
+ ${e}${s.slice(T+1,I)}`)}return k}l(_t,"foldFlowLines");function ei(s,e,t){let n=e,i=e+1,r=s[i];for(;r===" "||r===" ";)if(e<i+t)r=s[++e];else{do r=s[++e];while(r&&r!==`
12
+ `);n=e,i=e+1,r=s[i]}return n}l(ei,"consumeMoreIndentedLines");const Dt=l((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),jt=l(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Jo(s,e,t){if(!e||e<0)return!1;const n=e-t,i=s.length;if(i<=n)return!1;for(let r=0,o=0;r<i;++r)if(s[r]===`
13
+ `){if(r-o>n)return!0;if(o=r+1,i-o<=n)return!1}return!0}l(Jo,"lineLengthOverLimit");function ht(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(jt(s)?" ":"");let o="",a=0;for(let c=0,u=t[c];u;u=t[++c])if(u===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);const f=t.substr(c+2,4);switch(f){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:f.substr(0,2)==="00"?o+="\\x"+f.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(n||t[c+2]==='"'||t.length<i)c+=1;else{for(o+=t.slice(a,c)+`
14
14
 
15
15
  `;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
16
- `,c+=2;o+=r,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,s?o:Lt(o,r,_t,xt(e,!1))}l(rt,"doubleQuotedString");function Nn(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
17
- `)||/[ \t]\n|\n[ \t]/.test(n))return rt(n,e);const t=e.indent||(Pt(n)?" ":""),s="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${t}`)+"'";return e.implicitKey?s:Lt(s,t,ci,xt(e,!1))}l(Nn,"singleQuotedString");function qe(n,e){const{singleQuote:t}=e.options;let s;if(t===!1)s=rt;else{const i=n.includes('"'),r=n.includes("'");i&&!r?s=Nn:r&&!i?s=rt:s=t?Nn:rt}return s(n,e)}l(qe,"quotedString");let _n;try{_n=new RegExp(`(^|(?<!
16
+ `,c+=2;o+=r,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:_t(o,r,Pt,Dt(e,!1))}l(ht,"doubleQuotedString");function Mn(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(s))return ht(s,e);const t=e.indent||(jt(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${t}`)+"'";return e.implicitKey?n:_t(n,t,Xs,Dt(e,!1))}l(Mn,"singleQuotedString");function Fe(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=ht;else{const i=s.includes('"'),r=s.includes("'");i&&!r?n=Mn:r&&!i?n=ht:n=t?Mn:ht}return n(s,e)}l(Fe,"quotedString");let Bn;try{Bn=new RegExp(`(^|(?<!
19
19
  ))
20
20
  +(?!
21
- |$)`,"g")}catch{_n=/\n+(?!\n|$)/g}function jt({comment:n,type:e,value:t},s,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=s.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return qe(t,s);const u=s.indent||(s.forceBlockIndent||Pt(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===_.BLOCK_FOLDED?!1:e===_.BLOCK_LITERAL?!0:!qo(t,c,u.length);if(!t)return d?`|
21
+ |$)`,"g")}catch{Bn=/\n+(?!\n|$)/g}function Kt({comment:s,type:e,value:t},n,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return Fe(t,n);const u=n.indent||(n.forceBlockIndent||jt(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===N.BLOCK_FOLDED?!1:e===N.BLOCK_LITERAL?!0:!Jo(t,c,u.length);if(!t)return f?`|
22
22
  `:`>
23
- `;let f,h;for(h=t.length;h>0;--h){const O=t[h-1];if(O!==`
24
- `&&O!==" "&&O!==" ")break}let m=t.substring(h);const w=m.indexOf(`
25
- `);w===-1?f="-":t===m||w!==m.length-1?(f="+",r&&r()):f="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
26
- `&&(m=m.slice(0,-1)),m=m.replace(_n,`$&${u}`));let p=!1,g,S=-1;for(g=0;g<t.length;++g){const O=t[g];if(O===" ")p=!0;else if(O===`
27
- `)S=g;else break}let b=t.substring(0,S<g?S+1:g);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${u}`));let T=(p?u?"2":"1":"")+f;if(n&&(T+=" "+a(n.replace(/ ?[\r\n]+/g," ")),i&&i()),!d){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 x=xt(s,!0);o!=="folded"&&e!==_.BLOCK_FOLDED&&(x.onOverflow=()=>{$=!0});const E=Lt(`${b}${O}${m}`,u,In,x);if(!$)return`>${T}
29
- ${u}${E}`}return t=t.replace(/\n+/g,`$&${u}`),`|${T}
30
- ${u}${b}${t}${m}`}l(jt,"blockString");function Uo(n,e,t,s){const{type:i,value:r}=n,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:d}=e;if(a&&r.includes(`
31
- `)||d&&/[[\]{},]/.test(r))return qe(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||d||!r.includes(`
32
- `)?qe(r,e):jt(n,e,t,s);if(!a&&!d&&i!==_.PLAIN&&r.includes(`
33
- `))return jt(n,e,t,s);if(Pt(r)){if(c==="")return e.forceBlockIndent=!0,jt(n,e,t,s);if(a&&c===u)return qe(r,e)}const f=r.replace(/\n+/g,`$&
34
- ${c}`);if(o){const h=l(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:m,tags:w}=e.doc.schema;if(w.some(h)||m?.some(h))return qe(r,e)}return a?f:Lt(f,c,ci,xt(e,!1))}l(Uo,"plainString");function ot(n,e,t,s){const{implicitKey:i,inFlow:r}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)});let{type:a}=n;a!==_.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=_.QUOTE_DOUBLE);const c=l(d=>{switch(d){case _.BLOCK_FOLDED:case _.BLOCK_LITERAL:return i||r?qe(o.value,e):jt(o,e,t,s);case _.QUOTE_DOUBLE:return rt(o.value,e);case _.QUOTE_SINGLE:return Nn(o.value,e);case _.PLAIN:return Uo(o,e,t,s);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=i&&d||f;if(u=c(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}l(ot,"stringifyString");function ui(n,e){const t=Object.assign({blockQuote:!0,commentString:Fo,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},n.schema.toStringOptions,e);let s;switch(t.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}l(ui,"createStringifyContext");function Jo(n,e){if(e.tag){const i=n.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,s;if(R(e)){s=e.value;let i=n.filter(r=>r.identify?.(s));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 s=e,t=n.find(i=>i.nodeClass&&s instanceof i.nodeClass);if(!t){const i=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${i} value`)}return t}l(Jo,"getTagObject");function Vo(n,e,{anchors:t,doc:s}){if(!s.directives)return"";const i=[],r=(R(n)||q(n))&&n.anchor;r&&si(r)&&(t.add(r),i.push(`&${r}`));const o=n.tag??(e.default?null:e.tag);return o&&i.push(s.directives.tagString(o)),i.join(" ")}l(Vo,"stringifyProps");function Ue(n,e,t,s){if(B(n))return n.toString(e,t,s);if(me(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let i;const r=U(n)?n:e.doc.createNode(n,{onTagObj:l(c=>i=c,"onTagObj")});i??(i=Jo(e.doc.schema.tags,r));const o=Vo(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,s):R(r)?ot(r,e,t,s):r.toString(e,t,s);return o?R(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
- ${e.indent}${a}`:a}l(Ue,"stringify$2");function Wo({key:n,value:e},t,s,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=U(n)&&n.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(q(n)||!U(n)&&typeof n=="object"){const x="With simple keys, collection cannot be used as a key value";throw new Error(x)}}let m=!f&&(!n||h&&e==null&&!t.inFlow||q(n)||(R(n)?n.type===_.BLOCK_FOLDED||n.type===_.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(f||!r),indent:a+c});let w=!1,p=!1,g=Ue(n,t,()=>w=!0,()=>p=!0);if(!m&&!t.inFlow&&g.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(r||e==null)return w&&s&&s(),g===""?"?":m?`? ${g}`:g}else if(r&&!f||e==null&&m)return g=`? ${g}`,h&&!w?g+=Ce(g,t.indent,u(h)):p&&i&&i(),g;w&&(h=null),m?(h&&(g+=Ce(g,t.indent,u(h))),g=`? ${g}
36
- ${a}:`):(g=`${g}:`,h&&(g+=Ce(g,t.indent,u(h))));let S,b,C;U(e)?(S=!!e.spaceBefore,b=e.commentBefore,C=e.comment):(S=!1,b=null,C=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!h&&R(e)&&(t.indentAtStart=g.length+1),p=!1,!d&&c.length>=2&&!t.inFlow&&!m&&Me(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let T=!1;const O=Ue(e,t,()=>T=!0,()=>p=!0);let $=" ";if(h||S||b){if($=S?`
37
- `:"",b){const x=u(b);$+=`
38
- ${ue(x,t.indent)}`}O===""&&!t.inFlow?$===`
23
+ `;let d,h;for(h=t.length;h>0;--h){const I=t[h-1];if(I!==`
24
+ `&&I!==" "&&I!==" ")break}let m=t.substring(h);const w=m.indexOf(`
25
+ `);w===-1?d="-":t===m||w!==m.length-1?(d="+",r&&r()):d="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
26
+ `&&(m=m.slice(0,-1)),m=m.replace(Bn,`$&${u}`));let p=!1,y,C=-1;for(y=0;y<t.length;++y){const I=t[y];if(I===" ")p=!0;else if(I===`
27
+ `)C=y;else break}let k=t.substring(0,C<y?C+1:y);k&&(t=t.substring(k.length),k=k.replace(/\n+/g,`$&${u}`));let T=(p?u?"2":"1":"")+d;if(s&&(T+=" "+a(s.replace(/ ?[\r\n]+/g," ")),i&&i()),!f){const I=t.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let $=!1;const B=Dt(n,!0);o!=="folded"&&e!==N.BLOCK_FOLDED&&(B.onOverflow=()=>{$=!0});const A=_t(`${k}${I}${m}`,u,Rn,B);if(!$)return`>${T}
29
+ ${u}${A}`}return t=t.replace(/\n+/g,`$&${u}`),`|${T}
30
+ ${u}${k}${t}${m}`}l(Kt,"blockString");function Vo(s,e,t,n){const{type:i,value:r}=s,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:f}=e;if(a&&r.includes(`
31
+ `)||f&&/[[\]{},]/.test(r))return Fe(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||f||!r.includes(`
32
+ `)?Fe(r,e):Kt(s,e,t,n);if(!a&&!f&&i!==N.PLAIN&&r.includes(`
33
+ `))return Kt(s,e,t,n);if(jt(r)){if(c==="")return e.forceBlockIndent=!0,Kt(s,e,t,n);if(a&&c===u)return Fe(r,e)}const d=r.replace(/\n+/g,`$&
34
+ ${c}`);if(o){const h=l(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),"test"),{compat:m,tags:w}=e.doc.schema;if(w.some(h)||m?.some(h))return Fe(r,e)}return a?d:_t(d,c,Xs,Dt(e,!1))}l(Vo,"plainString");function pt(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!==N.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=N.QUOTE_DOUBLE);const c=l(f=>{switch(f){case N.BLOCK_FOLDED:case N.BLOCK_LITERAL:return i||r?Fe(o.value,e):Kt(o,e,t,n);case N.QUOTE_DOUBLE:return ht(o.value,e);case N.QUOTE_SINGLE:return Mn(o.value,e);case N.PLAIN:return Vo(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,h=i&&f||d;if(u=c(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}l(pt,"stringifyString");function ti(s,e){const t=Object.assign({blockQuote:!0,commentString:Uo,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}l(ti,"createStringifyContext");function Wo(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(M(e)){n=e.value;let i=s.filter(r=>r.identify?.(n));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else n=e,t=s.find(i=>i.nodeClass&&n instanceof i.nodeClass);if(!t){const i=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${i} value`)}return t}l(Wo,"getTagObject");function zo(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const i=[],r=(M(s)||J(s))&&s.anchor;r&&Gs(r)&&(t.add(r),i.push(`&${r}`));const o=s.tag??(e.default?null:e.tag);return o&&i.push(n.directives.tagString(o)),i.join(" ")}l(zo,"stringifyProps");function qe(s,e,t,n){if(q(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=V(s)?s:e.doc.createNode(s,{onTagObj:l(c=>i=c,"onTagObj")});i??(i=Wo(e.doc.schema.tags,r));const o=zo(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,n):M(r)?pt(r,e,t,n):r.toString(e,t,n);return o?M(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
35
+ ${e.indent}${a}`:a}l(qe,"stringify$2");function Go({key:s,value:e},t,n,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=t;let h=V(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(J(s)||!V(s)&&typeof s=="object"){const B="With simple keys, collection cannot be used as a key value";throw new Error(B)}}let m=!d&&(!s||h&&e==null&&!t.inFlow||J(s)||(M(s)?s.type===N.BLOCK_FOLDED||s.type===N.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(d||!r),indent:a+c});let w=!1,p=!1,y=qe(s,t,()=>w=!0,()=>p=!0);if(!m&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(r||e==null)return w&&n&&n(),y===""?"?":m?`? ${y}`:y}else if(r&&!d||e==null&&m)return y=`? ${y}`,h&&!w?y+=Ie(y,t.indent,u(h)):p&&i&&i(),y;w&&(h=null),m?(h&&(y+=Ie(y,t.indent,u(h))),y=`? ${y}
36
+ ${a}:`):(y=`${y}:`,h&&(y+=Ie(y,t.indent,u(h))));let C,k,O;V(e)?(C=!!e.spaceBefore,k=e.commentBefore,O=e.comment):(C=!1,k=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!h&&M(e)&&(t.indentAtStart=y.length+1),p=!1,!f&&c.length>=2&&!t.inFlow&&!m&&Ke(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let T=!1;const I=qe(e,t,()=>T=!0,()=>p=!0);let $=" ";if(h||C||k){if($=C?`
37
+ `:"",k){const B=u(k);$+=`
38
+ ${ge(B,t.indent)}`}I===""&&!t.inFlow?$===`
39
39
  `&&($=`
40
40
 
41
41
  `):$+=`
42
- ${t.indent}`}else if(!m&&q(e)){const x=O[0],E=O.indexOf(`
43
- `),z=E!==-1,de=t.inFlow??e.flow??e.items.length===0;if(z||!de){let Ee=!1;if(z&&(x==="&"||x==="!")){let G=O.indexOf(" ");x==="&"&&G!==-1&&G<E&&O[G+1]==="!"&&(G=O.indexOf(" ",G+1)),(G===-1||E<G)&&(Ee=!0)}Ee||($=`
44
- ${t.indent}`)}}else(O===""||O[0]===`
45
- `)&&($="");return g+=$+O,t.inFlow?T&&s&&s():C&&!T?g+=Ce(g,t.indent,u(C)):p&&i&&i(),g}l(Wo,"stringifyPair");function fi(n,e){(n==="debug"||n==="warn")&&console.warn(e)}l(fi,"warn");const Kt="<<",fe={identify:l(n=>n===Kt||typeof n=="symbol"&&n.description===Kt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new _(Symbol(Kt)),{addToJSMap:di}),"resolve"),stringify:l(()=>Kt,"stringify")},zo=l((n,e)=>(fe.identify(e)||R(e)&&(!e.type||e.type===_.PLAIN)&&fe.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===fe.tag&&t.default),"isMergeKey");function di(n,e,t){if(t=n&&me(t)?t.resolve(n.doc):t,Me(t))for(const s of t.items)Ln(n,e,s);else if(Array.isArray(t))for(const s of t)Ln(n,e,s);else Ln(n,e,t)}l(di,"addMergeToJSMap");function Ln(n,e,t){const s=n&&me(t)?t.resolve(n.doc):t;if(!De(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,n,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(Ln,"mergeValue");function hi(n,e,{key:t,value:s}){if(U(t)&&t.addToJSMap)t.addToJSMap(n,e,s);else if(zo(n,t))di(n,e,s);else{const i=se(t,"",n);if(e instanceof Map)e.set(i,se(s,i,n));else if(e instanceof Set)e.add(i);else{const r=Ho(t,i,n),o=se(s,r,n);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}l(hi,"addPairToJSMap");function Ho(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(U(n)&&t?.doc){const s=ui(t.doc,{});s.anchors=new Set;for(const r of t.anchors.keys())s.anchors.add(r.anchor);s.inFlow=!0,s.inStringifyKey=!0;const i=n.toString(s);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),fi(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}l(Ho,"stringifyKey");function xn(n,e,t){const s=st(n,void 0,t),i=st(e,void 0,t);return new Y(s,i)}l(xn,"createPair");class Y{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,ne,{value:Zs}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return U(t)&&(t=t.clone(e)),U(s)&&(s=s.clone(e)),new Y(t,s)}toJSON(e,t){const s=t?.mapAsMap?new Map:{};return hi(t,s,this)}toString(e,t,s){return e?.doc?Wo(this,e,t,s):JSON.stringify(this)}}function pi(n,e,t){return(e.inFlow??n.flow?Yo:Go)(n,e,t)}l(pi,"stringifyCollection");function Go({comment:n,items:e},t,{blockItemPrefix:s,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,d=Object.assign({},t,{indent:r,type:null});let f=!1;const h=[];for(let w=0;w<e.length;++w){const p=e[w];let g=null;if(U(p))!f&&p.spaceBefore&&h.push(""),Dt(t,h,p.commentBefore,f),p.comment&&(g=p.comment);else if(B(p)){const b=U(p.key)?p.key:null;b&&(!f&&b.spaceBefore&&h.push(""),Dt(t,h,b.commentBefore,f))}f=!1;let S=Ue(p,d,()=>g=null,()=>f=!0);g&&(S+=Ce(S,r,u(g))),f&&g&&(f=!1),h.push(s+S)}let m;if(h.length===0)m=i.start+i.end;else{m=h[0];for(let w=1;w<h.length;++w){const p=h[w];m+=p?`
42
+ ${t.indent}`}else if(!m&&J(e)){const B=I[0],A=I.indexOf(`
43
+ `),z=A!==-1,we=t.inFlow??e.flow??e.items.length===0;if(z||!we){let Le=!1;if(z&&(B==="&"||B==="!")){let G=I.indexOf(" ");B==="&"&&G!==-1&&G<A&&I[G+1]==="!"&&(G=I.indexOf(" ",G+1)),(G===-1||A<G)&&(Le=!0)}Le||($=`
44
+ ${t.indent}`)}}else(I===""||I[0]===`
45
+ `)&&($="");return y+=$+I,t.inFlow?T&&n&&n():O&&!T?y+=Ie(y,t.indent,u(O)):p&&i&&i(),y}l(Go,"stringifyPair");function ni(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(ni,"warn");const Rt="<<",ye={identify:l(s=>s===Rt||typeof s=="symbol"&&s.description===Rt,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new N(Symbol(Rt)),{addToJSMap:si}),"resolve"),stringify:l(()=>Rt,"stringify")},Ho=l((s,e)=>(ye.identify(e)||M(e)&&(!e.type||e.type===N.PLAIN)&&ye.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===ye.tag&&t.default),"isMergeKey");function si(s,e,t){if(t=s&&ke(t)?t.resolve(s.doc):t,Ke(t))for(const n of t.items)Fn(s,e,n);else if(Array.isArray(t))for(const n of t)Fn(s,e,n);else Fn(s,e,t)}l(si,"addMergeToJSMap");function Fn(s,e,t){const n=s&&ke(t)?t.resolve(s.doc):t;if(!je(n))throw new Error("Merge sources must be maps or map aliases");const i=n.toJSON(null,s,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(Fn,"mergeValue");function ii(s,e,{key:t,value:n}){if(V(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Ho(s,t))si(s,e,n);else{const i=ae(t,"",s);if(e instanceof Map)e.set(i,ae(n,i,s));else if(e instanceof Set)e.add(i);else{const r=Yo(t,i,s),o=ae(n,r,s);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}l(ii,"addPairToJSMap");function Yo(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(V(s)&&t?.doc){const n=ti(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)+'..."'),ni(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}l(Yo,"stringifyKey");function qn(s,e,t){const n=ft(s,void 0,t),i=ft(e,void 0,t);return new Z(n,i)}l(qn,"createPair");class Z{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,oe,{value:qs}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return V(t)&&(t=t.clone(e)),V(n)&&(n=n.clone(e)),new Z(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return ii(t,n,this)}toString(e,t,n){return e?.doc?Go(this,e,t,n):JSON.stringify(this)}}function ri(s,e,t){return(e.inFlow??s.flow?Qo:Zo)(s,e,t)}l(ri,"stringifyCollection");function Zo({comment:s,items:e},t,{blockItemPrefix:n,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,f=Object.assign({},t,{indent:r,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const p=e[w];let y=null;if(V(p))!d&&p.spaceBefore&&h.push(""),Mt(t,h,p.commentBefore,d),p.comment&&(y=p.comment);else if(q(p)){const k=V(p.key)?p.key:null;k&&(!d&&k.spaceBefore&&h.push(""),Mt(t,h,k.commentBefore,d))}d=!1;let C=qe(p,f,()=>y=null,()=>d=!0);y&&(C+=Ie(C,r,u(y))),d&&y&&(d=!1),h.push(n+C)}let m;if(h.length===0)m=i.start+i.end;else{m=h[0];for(let w=1;w<h.length;++w){const p=h[w];m+=p?`
46
46
  ${c}${p}`:`
47
- `}}return n?(m+=`
48
- `+ue(u(n),c),a&&a()):f&&o&&o(),m}l(Go,"stringifyBlockCollection");function Yo({items:n},e,{flowChars:t,itemIndent:s}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;s+=r;const c=Object.assign({},e,{indent:s,inFlow:!0,type:null});let u=!1,d=0;const f=[];for(let w=0;w<n.length;++w){const p=n[w];let g=null;if(U(p))p.spaceBefore&&f.push(""),Dt(e,f,p.commentBefore,!1),p.comment&&(g=p.comment);else if(B(p)){const b=U(p.key)?p.key:null;b&&(b.spaceBefore&&f.push(""),Dt(e,f,b.commentBefore,!1),b.comment&&(u=!0));const C=U(p.value)?p.value:null;C?(C.comment&&(g=C.comment),C.commentBefore&&(u=!0)):p.value==null&&b?.comment&&(g=b.comment)}g&&(u=!0);let S=Ue(p,c,()=>g=null);w<n.length-1&&(S+=","),g&&(S+=Ce(S,s,a(g))),!u&&(f.length>d||S.includes(`
49
- `))&&(u=!0),f.push(S),d=f.length}const{start:h,end:m}=t;if(f.length===0)return h+m;if(!u){const w=f.reduce((p,g)=>p+g.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=h;for(const p of f)w+=p?`
47
+ `}}return s?(m+=`
48
+ `+ge(u(s),c),a&&a()):d&&o&&o(),m}l(Zo,"stringifyBlockCollection");function Qo({items:s},e,{flowChars:t,itemIndent:n}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;n+=r;const c=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,f=0;const d=[];for(let w=0;w<s.length;++w){const p=s[w];let y=null;if(V(p))p.spaceBefore&&d.push(""),Mt(e,d,p.commentBefore,!1),p.comment&&(y=p.comment);else if(q(p)){const k=V(p.key)?p.key:null;k&&(k.spaceBefore&&d.push(""),Mt(e,d,k.commentBefore,!1),k.comment&&(u=!0));const O=V(p.value)?p.value:null;O?(O.comment&&(y=O.comment),O.commentBefore&&(u=!0)):p.value==null&&k?.comment&&(y=k.comment)}y&&(u=!0);let C=qe(p,c,()=>y=null);w<s.length-1&&(C+=","),y&&(C+=Ie(C,n,a(y))),!u&&(d.length>f||C.includes(`
49
+ `))&&(u=!0),d.push(C),f=d.length}const{start:h,end:m}=t;if(d.length===0)return h+m;if(!u){const w=d.reduce((p,y)=>p+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=h;for(const p of d)w+=p?`
50
50
  ${r}${i}${p}`:`
51
51
  `;return`${w}
52
- ${i}${m}`}else return`${h}${o}${f.join(" ")}${o}${m}`}l(Yo,"stringifyFlowCollection");function Dt({indent:n,options:{commentString:e}},t,s,i){if(s&&i&&(s=s.replace(/^\n+/,"")),s){const r=ue(e(s),n);t.push(r.trimStart())}}l(Dt,"addCommentBefore");function ve(n,e){const t=R(e)?e.value:e;for(const s of n)if(B(s)&&(s.key===e||s.key===t||R(s.key)&&s.key.value===t))return s}l(ve,"findPair");class te extends ai{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(pe,e),this.items=[]}static from(e,t,s){const{keepUndefined:i,replacer:r}=s,o=new this(e),a=l((c,u)=>{if(typeof r=="function")u=r.call(t,c,u);else if(Array.isArray(r)&&!r.includes(c))return;(u!==void 0||i)&&o.items.push(xn(c,u,s))},"add");if(t instanceof Map)for(const[c,u]of t)a(c,u);else if(t&&typeof t=="object")for(const c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let s;B(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new Y(e,e?.value):s=new Y(e.key,e.value);const i=ve(this.items,s.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${s.key} already set`);R(i.value)&&oi(s.value)?i.value.value=s.value:i.value=s.value}else if(r){const o=this.items.findIndex(a=>r(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){const t=ve(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=ve(this.items,e)?.value;return(!t&&R(i)?i.value:i)??void 0}has(e){return!!ve(this.items,e)}set(e,t){this.add(new Y(e,t),!0)}toJSON(e,t,s){const i=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)hi(t,i,r);return i}toString(e,t,s){if(!e)return JSON.stringify(this);for(const i of this.items)if(!B(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})),pi(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}}const Je={collection:"map",default:!0,nodeClass:te,tag:"tag:yaml.org,2002:map",resolve(n,e){return De(n)||e("Expected a mapping for this tag"),n},createNode:l((n,e,t)=>te.from(n,e,t),"createNode")};class ge extends ai{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Ke,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 s=Mt(e);if(typeof s!="number")return;const i=this.items[s];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 s=Mt(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[s];R(i)&&oi(t)?i.value=t:this.items[s]=t}toJSON(e,t){const s=[];t?.onCreate&&t.onCreate(s);let i=0;for(const r of this.items)s.push(se(r,String(i++),t));return s}toString(e,t,s){return e?pi(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){const{replacer:i}=s,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const c=t instanceof Set?a:String(o++);a=i.call(t,c,a)}r.items.push(st(a,void 0,s))}}return r}}function Mt(n){let e=R(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(Mt,"asItemIndex");const Ve={collection:"seq",default:!0,nodeClass:ge,tag:"tag:yaml.org,2002:seq",resolve(n,e){return Me(n)||e("Expected a sequence for this tag"),n},createNode:l((n,e,t)=>ge.from(n,e,t),"createNode")},Rt={identify:l(n=>typeof n=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(n=>n,"resolve"),stringify(n,e,t,s){return e=Object.assign({actualString:!0},e),ot(n,e,t,s)}},Bt={identify:l(n=>n==null,"identify"),createNode:l(()=>new _(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new _(null),"resolve"),stringify:l(({source:n},e)=>typeof n=="string"&&Bt.test.test(n)?n:e.options.nullStr,"stringify")},Pn={identify:l(n=>typeof n=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(n=>new _(n[0]==="t"||n[0]==="T"),"resolve"),stringify({source:n,value:e},t){if(n&&Pn.test.test(n)){const s=n[0]==="t"||n[0]==="T";if(e===s)return n}return e?t.options.trueStr:t.options.falseStr}};function ie({format:n,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);const i=typeof s=="number"?s:Number(s);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(s);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}l(ie,"stringifyNumber");const mi={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ie},gi={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(n=>parseFloat(n),"resolve"),stringify(n){const e=Number(n.value);return isFinite(e)?e.toExponential():ie(n)}},yi={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){const e=new _(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ie},Ft=l(n=>typeof n=="bigint"||Number.isInteger(n),"intIdentify$2"),jn=l((n,e,t,{intAsBigInt:s})=>s?BigInt(n):parseInt(n.substring(e),t),"intResolve$1");function wi(n,e,t){const{value:s}=n;return Ft(s)&&s>=0?t+s.toString(e):ie(n)}l(wi,"intStringify$1");const bi={identify:l(n=>Ft(n)&&n>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((n,e,t)=>jn(n,2,8,t),"resolve"),stringify:l(n=>wi(n,8,"0o"),"stringify")},Si={identify:Ft,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((n,e,t)=>jn(n,0,10,t),"resolve"),stringify:ie},ki={identify:l(n=>Ft(n)&&n>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:l((n,e,t)=>jn(n,2,16,t),"resolve"),stringify:l(n=>wi(n,16,"0x"),"stringify")},Zo=[Je,Ve,Rt,Bt,Pn,bi,Si,ki,mi,gi,yi];function Ci(n){return typeof n=="bigint"||Number.isInteger(n)}l(Ci,"intIdentify$1");const qt=l(({value:n})=>JSON.stringify(n),"stringifyJSON"),Qo=[{identify:l(n=>typeof n=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(n=>n,"resolve"),stringify:qt},{identify:l(n=>n==null,"identify"),createNode:l(()=>new _(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:qt},{identify:l(n=>typeof n=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:l(n=>n==="true","resolve"),stringify:qt},{identify:Ci,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:l((n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),"resolve"),stringify:l(({value:n})=>Ci(n)?n.toString():JSON.stringify(n),"stringify")},{identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:l(n=>parseFloat(n),"resolve"),stringify:qt}],Xo={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},ea=[Je,Ve].concat(Qo,Xo),Kn={identify:l(n=>n instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof atob=="function"){const t=atob(n.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let i=0;i<t.length;++i)s[i]=t.charCodeAt(i);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},s,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=_.BLOCK_LITERAL),e!==_.QUOTE_DOUBLE){const c=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let f=0,h=0;f<u;++f,h+=c)d[f]=a.substr(h,c);a=d.join(e===_.BLOCK_LITERAL?`
53
- `:" ")}return ot({comment:n,type:e,value:a},s,i,r)}};function vi(n,e){if(Me(n))for(let t=0;t<n.items.length;++t){let s=n.items[t];if(!B(s)){if(De(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");const i=s.items[0]||new Y(new _(null));if(s.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${s.commentBefore}
54
- ${i.key.commentBefore}`:s.commentBefore),s.comment){const r=i.value??i.key;r.comment=r.comment?`${s.comment}
55
- ${r.comment}`:s.comment}s=i}n.items[t]=B(s)?s:new Y(s)}}else e("Expected a sequence for this tag");return n}l(vi,"resolvePairs");function Ai(n,e,t){const{replacer:s}=t,i=new ge(n);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(xn(a,c,t))}return i}l(Ai,"createPairs");const Dn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:vi,createNode:Ai};class Ge extends ge{static{l(this,"YAMLOMap")}constructor(){super(),this.add=te.prototype.add.bind(this),this.delete=te.prototype.delete.bind(this),this.get=te.prototype.get.bind(this),this.has=te.prototype.has.bind(this),this.set=te.prototype.set.bind(this),this.tag=Ge.tag}toJSON(e,t){if(!t)return super.toJSON(e);const s=new Map;t?.onCreate&&t.onCreate(s);for(const i of this.items){let r,o;if(B(i)?(r=se(i.key,"",t),o=se(i.value,r,t)):r=se(i,"",t),s.has(r))throw new Error("Ordered maps must not include duplicate keys");s.set(r,o)}return s}static from(e,t,s){const i=Ai(e,t,s),r=new this;return r.items=i.items,r}}Ge.tag="tag:yaml.org,2002:omap";const Mn={collection:"seq",identify:l(n=>n instanceof Map,"identify"),nodeClass:Ge,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){const t=vi(n,e),s=[];for(const{key:i}of t.items)R(i)&&(s.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):s.push(i.value));return Object.assign(new Ge,t)},createNode:l((n,e,t)=>Ge.from(n,e,t),"createNode")};function Oi({value:n,source:e},t){return e&&(n?Ei:Ti).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}l(Oi,"boolStringify");const Ei={identify:l(n=>n===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new _(!0),"resolve"),stringify:Oi},Ti={identify:l(n=>n===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new _(!1),"resolve"),stringify:Oi},ta={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ie},na={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(n=>parseFloat(n.replace(/_/g,"")),"resolve"),stringify(n){const e=Number(n.value);return isFinite(e)?e.toExponential():ie(n)}},sa={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){const e=new _(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){const s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:ie},at=l(n=>typeof n=="bigint"||Number.isInteger(n),"intIdentify");function Ut(n,e,t,{intAsBigInt:s}){const i=n[0];if((i==="-"||i==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}const o=BigInt(n);return i==="-"?BigInt(-1)*o:o}const r=parseInt(n,t);return i==="-"?-1*r:r}l(Ut,"intResolve");function Rn(n,e,t){const{value:s}=n;if(at(s)){const i=s.toString(e);return s<0?"-"+t+i.substr(1):t+i}return ie(n)}l(Rn,"intStringify");const ia={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((n,e,t)=>Ut(n,2,2,t),"resolve"),stringify:l(n=>Rn(n,2,"0b"),"stringify")},ra={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((n,e,t)=>Ut(n,1,8,t),"resolve"),stringify:l(n=>Rn(n,8,"0"),"stringify")},oa={identify:at,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((n,e,t)=>Ut(n,0,10,t),"resolve"),stringify:ie},aa={identify:at,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((n,e,t)=>Ut(n,2,16,t),"resolve"),stringify:l(n=>Rn(n,16,"0x"),"stringify")};class Ye extends te{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=Ye.tag}add(e){let t;B(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Y(e.key,null):t=new Y(e,null),ve(this.items,t.key)||this.items.push(t)}get(e,t){const s=ve(this.items,e);return!t&&B(s)?R(s.key)?s.key.value:s.key:s}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 s=ve(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Y(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){const{replacer:i}=s,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(xn(o,null,s));return r}}Ye.tag="tag:yaml.org,2002:set";const Bn={collection:"map",identify:l(n=>n instanceof Set,"identify"),nodeClass:Ye,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((n,e,t)=>Ye.from(n,e,t),"createNode"),resolve(n,e){if(De(n)){if(n.hasAllNullValues(!0))return Object.assign(new Ye,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};function Fn(n,e){const t=n[0],s=t==="-"||t==="+"?n.substring(1):n,i=l(o=>e?BigInt(o):Number(o),"num"),r=s.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(Fn,"parseSexagesimal");function $i(n){let{value:e}=n,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ie(n);let s="";e<0&&(s="-",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))),s+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l($i,"stringifySexagesimal");const Ii={identify:l(n=>typeof n=="bigint"||Number.isInteger(n),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((n,e,{intAsBigInt:t})=>Fn(n,t),"resolve"),stringify:$i},Ni={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(n=>Fn(n,!1),"resolve"),stringify:$i},Jt={identify:l(n=>n 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(n){const e=n.match(Jt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,s,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,s-1,i,r||0,o||0,a||0,c);const d=e[8];if(d&&d!=="Z"){let f=Fn(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:l(({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},_i=[Je,Ve,Rt,Bt,Ei,Ti,ia,ra,oa,aa,ta,na,sa,Kn,fe,Mn,Dn,Bn,Ii,Ni,Jt],Li=new Map([["core",Zo],["failsafe",[Je,Ve,Rt]],["json",ea],["yaml11",_i],["yaml-1.1",_i]]),xi={binary:Kn,bool:Pn,float:yi,floatExp:gi,floatNaN:mi,floatTime:Ni,int:Si,intHex:ki,intOct:bi,intTime:Ii,map:Je,merge:fe,null:Bt,omap:Mn,pairs:Dn,seq:Ve,set:Bn,timestamp:Jt},ca={"tag:yaml.org,2002:binary":Kn,"tag:yaml.org,2002:merge":fe,"tag:yaml.org,2002:omap":Mn,"tag:yaml.org,2002:pairs":Dn,"tag:yaml.org,2002:set":Bn,"tag:yaml.org,2002:timestamp":Jt};function qn(n,e,t){const s=Li.get(e);if(s&&!n)return t&&!s.includes(fe)?s.concat(fe):s.slice();let i=s;if(!i)if(Array.isArray(n))i=[];else{const r=Array.from(Li.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(n))for(const r of n)i=i.concat(r);else typeof n=="function"&&(i=n(i.slice()));return t&&(i=i.concat(fe)),i.reduce((r,o)=>{const a=typeof o=="string"?xi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(xi).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(qn,"getTags");const la=l((n,e)=>n.key<e.key?-1:n.key>e.key?1:0,"sortMapEntriesByKey");class nn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:s,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?qn(e,"compat"):e?qn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?ca:{},this.tags=qn(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,pe,{value:Je}),Object.defineProperty(this,ce,{value:Rt}),Object.defineProperty(this,Ke,{value:Ve}),this.sortMapEntries=typeof o=="function"?o:o===!0?la:null}clone(){const e=Object.create(nn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function ua(n,e){const t=[];let s=e.directives===!0;if(e.directives!==!1&&n.directives){const c=n.directives.toString(n);c?(t.push(c),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");const i=ui(n,e),{commentString:r}=i.options;if(n.commentBefore){t.length!==1&&t.unshift("");const c=r(n.commentBefore);t.unshift(ue(c,""))}let o=!1,a=null;if(n.contents){if(U(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){const d=r(n.contents.commentBefore);t.push(ue(d,""))}i.forceBlockIndent=!!n.comment,a=n.contents.comment}const c=a?void 0:()=>o=!0;let u=Ue(n.contents,i,()=>a=null,c);a&&(u+=Ce(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Ue(n.contents,i));if(n.directives?.docEnd)if(n.comment){const c=r(n.comment);c.includes(`
56
- `)?(t.push("..."),t.push(ue(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=n.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(ue(r(c),"")))}return t.join(`
52
+ ${i}${m}`}else return`${h}${o}${d.join(" ")}${o}${m}`}l(Qo,"stringifyFlowCollection");function Mt({indent:s,options:{commentString:e}},t,n,i){if(n&&i&&(n=n.replace(/^\n+/,"")),n){const r=ge(e(n),s);t.push(r.trimStart())}}l(Mt,"addCommentBefore");function $e(s,e){const t=M(e)?e.value:e;for(const n of s)if(q(n)&&(n.key===e||n.key===t||M(n.key)&&n.key.value===t))return n}l($e,"findPair");class re extends Qs{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Se,e),this.items=[]}static from(e,t,n){const{keepUndefined:i,replacer:r}=n,o=new this(e),a=l((c,u)=>{if(typeof r=="function")u=r.call(t,c,u);else if(Array.isArray(r)&&!r.includes(c))return;(u!==void 0||i)&&o.items.push(qn(c,u,n))},"add");if(t instanceof Map)for(const[c,u]of t)a(c,u);else if(t&&typeof t=="object")for(const c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;q(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new Z(e,e?.value):n=new Z(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`);M(i.value)&&Zs(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&&M(i)?i.value:i)??void 0}has(e){return!!$e(this.items,e)}set(e,t){this.add(new Z(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)ii(t,i,r);return i}toString(e,t,n){if(!e)return JSON.stringify(this);for(const i of this.items)if(!q(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ri(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ue={collection:"map",default:!0,nodeClass:re,tag:"tag:yaml.org,2002:map",resolve(s,e){return je(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>re.from(s,e,t),"createNode")};class Ce extends Qs{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(De,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Bt(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Bt(e);if(typeof n!="number")return;const i=this.items[n];return!t&&M(i)?i.value:i}has(e){const t=Bt(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Bt(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[n];M(i)&&Zs(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(ae(r,String(i++),t));return n}toString(e,t,n){return e?ri(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){const{replacer:i}=n,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const c=t instanceof Set?a:String(o++);a=i.call(t,c,a)}r.items.push(ft(a,void 0,n))}}return r}}function Bt(s){let e=M(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(Bt,"asItemIndex");const Je={collection:"seq",default:!0,nodeClass:Ce,tag:"tag:yaml.org,2002:seq",resolve(s,e){return Ke(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>Ce.from(s,e,t),"createNode")},Ft={identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),pt(s,e,t,n)}},qt={identify:l(s=>s==null,"identify"),createNode:l(()=>new N(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new N(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&qt.test.test(s)?s:e.options.nullStr,"stringify")},Un={identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(s=>new N(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&Un.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 le({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const i=typeof n=="number"?n:Number(n);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}l(le,"stringifyNumber");const oi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:le},ai={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():le(s)}},ci={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new N(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:le},Ut=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),Jn=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function li(s,e,t){const{value:n}=s;return Ut(n)&&n>=0?t+n.toString(e):le(s)}l(li,"intStringify$1");const ui={identify:l(s=>Ut(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>Jn(s,2,8,t),"resolve"),stringify:l(s=>li(s,8,"0o"),"stringify")},fi={identify:Ut,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>Jn(s,0,10,t),"resolve"),stringify:le},di={identify:l(s=>Ut(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:l((s,e,t)=>Jn(s,2,16,t),"resolve"),stringify:l(s=>li(s,16,"0x"),"stringify")},Xo=[Ue,Je,Ft,qt,Un,ui,fi,di,oi,ai,ci];function hi(s){return typeof s=="bigint"||Number.isInteger(s)}l(hi,"intIdentify$1");const Jt=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),ea=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:Jt},{identify:l(s=>s==null,"identify"),createNode:l(()=>new N(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:Jt},{identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:l(s=>s==="true","resolve"),stringify:Jt},{identify:hi,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:l((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:l(({value:s})=>hi(s)?s.toString():JSON.stringify(s),"stringify")},{identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:l(s=>parseFloat(s),"resolve"),stringify:Jt}],ta={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},na=[Ue,Je].concat(ea,ta),Vn={identify:l(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let i=0;i<t.length;++i)n[i]=t.charCodeAt(i);return n}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),s},stringify({comment:s,type:e,value:t},n,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=N.BLOCK_LITERAL),e!==N.QUOTE_DOUBLE){const c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let d=0,h=0;d<u;++d,h+=c)f[d]=a.substr(h,c);a=f.join(e===N.BLOCK_LITERAL?`
53
+ `:" ")}return pt({comment:s,type:e,value:a},n,i,r)}};function pi(s,e){if(Ke(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!q(n)){if(je(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const i=n.items[0]||new Z(new N(null));if(n.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${n.commentBefore}
54
+ ${i.key.commentBefore}`:n.commentBefore),n.comment){const r=i.value??i.key;r.comment=r.comment?`${n.comment}
55
+ ${r.comment}`:n.comment}n=i}s.items[t]=q(n)?n:new Z(n)}}else e("Expected a sequence for this tag");return s}l(pi,"resolvePairs");function mi(s,e,t){const{replacer:n}=t,i=new Ce(s);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(qn(a,c,t))}return i}l(mi,"createPairs");const Wn={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:pi,createNode:mi};class nt extends Ce{static{l(this,"YAMLOMap")}constructor(){super(),this.add=re.prototype.add.bind(this),this.delete=re.prototype.delete.bind(this),this.get=re.prototype.get.bind(this),this.has=re.prototype.has.bind(this),this.set=re.prototype.set.bind(this),this.tag=nt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const i of this.items){let r,o;if(q(i)?(r=ae(i.key,"",t),o=ae(i.value,r,t)):r=ae(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=mi(e,t,n),r=new this;return r.items=i.items,r}}nt.tag="tag:yaml.org,2002:omap";const zn={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:nt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=pi(s,e),n=[];for(const{key:i}of t.items)M(i)&&(n.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):n.push(i.value));return Object.assign(new nt,t)},createNode:l((s,e,t)=>nt.from(s,e,t),"createNode")};function gi({value:s,source:e},t){return e&&(s?yi:wi).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(gi,"boolStringify");const yi={identify:l(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new N(!0),"resolve"),stringify:gi},wi={identify:l(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new N(!1),"resolve"),stringify:gi},sa={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:le},ia={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():le(s)}},ra={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new N(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:le},mt=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Vt(s,e,t,{intAsBigInt:n}){const i=s[0];if((i==="-"||i==="+")&&(e+=1),s=s.substring(e).replace(/_/g,""),n){switch(t){case 2:s=`0b${s}`;break;case 8:s=`0o${s}`;break;case 16:s=`0x${s}`;break}const o=BigInt(s);return i==="-"?BigInt(-1)*o:o}const r=parseInt(s,t);return i==="-"?-1*r:r}l(Vt,"intResolve");function Gn(s,e,t){const{value:n}=s;if(mt(n)){const i=n.toString(e);return n<0?"-"+t+i.substr(1):t+i}return le(s)}l(Gn,"intStringify");const oa={identify:mt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>Vt(s,2,2,t),"resolve"),stringify:l(s=>Gn(s,2,"0b"),"stringify")},aa={identify:mt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>Vt(s,1,8,t),"resolve"),stringify:l(s=>Gn(s,8,"0"),"stringify")},ca={identify:mt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>Vt(s,0,10,t),"resolve"),stringify:le},la={identify:mt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>Vt(s,2,16,t),"resolve"),stringify:l(s=>Gn(s,16,"0x"),"stringify")};class st extends re{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=st.tag}add(e){let t;q(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Z(e.key,null):t=new Z(e,null),$e(this.items,t.key)||this.items.push(t)}get(e,t){const n=$e(this.items,e);return!t&&q(n)?M(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 Z(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(qn(o,null,n));return r}}st.tag="tag:yaml.org,2002:set";const Hn={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:st,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>st.from(s,e,t),"createNode"),resolve(s,e){if(je(s)){if(s.hasAllNullValues(!0))return Object.assign(new st,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Yn(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,i=l(o=>e?BigInt(o):Number(o),"num"),r=n.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(Yn,"parseSexagesimal");function bi(s){let{value:e}=s,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return le(s);let n="";e<0&&(n="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),n+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l(bi,"stringifySexagesimal");const Si={identify:l(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((s,e,{intAsBigInt:t})=>Yn(s,t),"resolve"),stringify:bi},ki={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(s=>Yn(s,!1),"resolve"),stringify:bi},Wt={identify:l(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(Wt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,i,r||0,o||0,a||0,c);const f=e[8];if(f&&f!=="Z"){let d=Yn(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:l(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Ci=[Ue,Je,Ft,qt,yi,wi,oa,aa,ca,la,sa,ia,ra,Vn,ye,zn,Wn,Hn,Si,ki,Wt],vi=new Map([["core",Xo],["failsafe",[Ue,Je,Ft]],["json",na],["yaml11",Ci],["yaml-1.1",Ci]]),Ei={binary:Vn,bool:Un,float:ci,floatExp:ai,floatNaN:oi,floatTime:ki,int:fi,intHex:di,intOct:ui,intTime:Si,map:Ue,merge:ye,null:qt,omap:zn,pairs:Wn,seq:Je,set:Hn,timestamp:Wt},ua={"tag:yaml.org,2002:binary":Vn,"tag:yaml.org,2002:merge":ye,"tag:yaml.org,2002:omap":zn,"tag:yaml.org,2002:pairs":Wn,"tag:yaml.org,2002:set":Hn,"tag:yaml.org,2002:timestamp":Wt};function Zn(s,e,t){const n=vi.get(e);if(n&&!s)return t&&!n.includes(ye)?n.concat(ye):n.slice();let i=n;if(!i)if(Array.isArray(s))i=[];else{const r=Array.from(vi.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(ye)),i.reduce((r,o)=>{const a=typeof o=="string"?Ei[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(Ei).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(Zn,"getTags");const fa=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class mn{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Zn(e,"compat"):e?Zn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?ua:{},this.tags=Zn(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Se,{value:Ue}),Object.defineProperty(this,he,{value:Ft}),Object.defineProperty(this,De,{value:Je}),this.sortMapEntries=typeof o=="function"?o:o===!0?fa:null}clone(){const e=Object.create(mn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function da(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const c=s.directives.toString(s);c?(t.push(c),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const i=ti(s,e),{commentString:r}=i.options;if(s.commentBefore){t.length!==1&&t.unshift("");const c=r(s.commentBefore);t.unshift(ge(c,""))}let o=!1,a=null;if(s.contents){if(V(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=r(s.contents.commentBefore);t.push(ge(f,""))}i.forceBlockIndent=!!s.comment,a=s.contents.comment}const c=a?void 0:()=>o=!0;let u=qe(s.contents,i,()=>a=null,c);a&&(u+=Ie(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 c=r(s.comment);c.includes(`
56
+ `)?(t.push("..."),t.push(ge(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=s.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(ge(r(c),"")))}return t.join(`
57
57
  `)+`
58
- `}l(ua,"stringifyDocument");class Ze{static{l(this,"Document")}constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ne,{value:Tn});let i=null;typeof t=="function"||Array.isArray(t)?i=t:s===void 0&&t&&(s=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"},s);this.options=r;let{version:o}=r;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Q({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,i,s)}clone(){const e=Object.create(Ze.prototype,{[ne]:{value:Tn}});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=U(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){We(this.contents)&&this.contents.add(e)}addIn(e,t){We(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const s=ii(this);e.anchor=!t||s.has(t)?ri(t||"a",s):t}return new $t(e.anchor)}createNode(e,t,s){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const g=l(b=>typeof b=="number"||b instanceof String||b instanceof Number,"keyToStr"),S=t.filter(g).map(String);S.length>0&&(t=t.concat(S)),i=t}else s===void 0&&t&&(s=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:d}=s??{},{onAnchor:f,setAnchors:h,sourceObjects:m}=Mo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:m},p=st(e,d,w);return a&&q(p)&&(p.flow=!0),h(),p}createPair(e,t,s={}){const i=this.createNode(e,null,s),r=this.createNode(t,null,s);return new Y(i,r)}delete(e){return We(this.contents)?this.contents.delete(e):!1}deleteIn(e){return it(e)?this.contents==null?!1:(this.contents=null,!0):We(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 it(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 it(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):We(this.contents)&&this.contents.set(e,t)}setIn(e,t){it(e)?this.contents=t:this.contents==null?this.contents=Nt(this.schema,Array.from(e),t):We(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Q({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Q({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=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(s)this.schema=new nn(Object.assign(s,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:s,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=se(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:d}of a.anchors.values())r(d,u);return typeof o=="function"?Fe(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return ua(this,e)}}function We(n){if(q(n))return!0;throw new Error("Expected a YAML collection as document contents")}l(We,"assertCollection");class Un extends Error{static{l(this,"YAMLError")}constructor(e,t,s,i){super(),this.name=e,this.code=s,this.message=i,this.pos=t}}class Ae extends Un{static{l(this,"YAMLParseError")}constructor(e,t,s){super("YAMLParseError",e,t,s)}}class Pi extends Un{static{l(this,"YAMLWarning")}constructor(e,t,s){super("YAMLWarning",e,t,s)}}const Vt=l((n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:s,col:i}=t.linePos[0];t.message+=` at line ${s}, column ${i}`;let r=i-1,o=n.substring(e.lineStarts[s-1],e.lineStarts[s]).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"),s>1&&/^ *$/.test(o.substring(0,r))){let a=n.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
- `),o=a+o}if(/[^ ]/.test(o)){let a=1;const c=t.linePos[1];c&&c.line===s&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
58
+ `}l(da,"stringifyDocument");class it{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:jn});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 te({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){const e=Object.create(it.prototype,{[oe]:{value:jn}});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=V(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ve(this.contents)&&this.contents.add(e)}addIn(e,t){Ve(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=Hs(this);e.anchor=!t||n.has(t)?Ys(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=l(k=>typeof k=="number"||k instanceof String||k instanceof Number,"keyToStr"),C=t.filter(y).map(String);C.length>0&&(t=t.concat(C)),i=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:f}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:m}=Bo(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:m},p=ft(e,f,w);return a&&J(p)&&(p.flow=!0),h(),p}createPair(e,t,n={}){const i=this.createNode(e,null,n),r=this.createNode(t,null,n);return new Z(i,r)}delete(e){return Ve(this.contents)?this.contents.delete(e):!1}deleteIn(e){return dt(e)?this.contents==null?!1:(this.contents=null,!0):Ve(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return J(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return dt(e)?!t&&M(this.contents)?this.contents.value:this.contents:J(this.contents)?this.contents.getIn(e,t):void 0}has(e){return J(this.contents)?this.contents.has(e):!1}hasIn(e){return dt(e)?this.contents!==void 0:J(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Lt(this.schema,[e],t):Ve(this.contents)&&this.contents.set(e,t)}setIn(e,t){dt(e)?this.contents=t:this.contents==null?this.contents=Lt(this.schema,Array.from(e),t):Ve(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 te({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 te({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 mn(Object.assign(n,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=ae(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:f}of a.anchors.values())r(f,u);return typeof o=="function"?Be(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return da(this,e)}}function Ve(s){if(J(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(Ve,"assertCollection");class Qn extends Error{static{l(this,"YAMLError")}constructor(e,t,n,i){super(),this.name=e,this.code=n,this.message=i,this.pos=t}}class Ne extends Qn{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ti extends Qn{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const zt=l((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:i}=t.linePos[0];t.message+=` at line ${n}, column ${i}`;let r=i-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,r))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
+ `),o=a+o}if(/[^ ]/.test(o)){let a=1;const c=t.linePos[1];c&&c.line===n&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
60
60
 
61
61
  ${o}
62
62
  ${u}
63
- `}},"prettifyError");function ze(n,{flow:e,indicator:t,next:s,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,d=a,f="",h="",m=!1,w=!1,p=null,g=null,S=null,b=null,C=null,T=null,O=null;for(const E of n)switch(w&&(E.type!=="space"&&E.type!=="newline"&&E.type!=="comma"&&r(E.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(u&&E.type!=="comment"&&E.type!=="newline"&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),E.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&E.source.includes(" ")&&(p=E),d=!0;break;case"comment":{d||r(E,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const z=E.source.substring(1)||" ";f?f+=h+z:f=z,h="",u=!1;break}case"newline":u?f?f+=E.source:(!T||t!=="seq-item-ind")&&(c=!0):h+=E.source,u=!0,m=!0,(g||S)&&(b=E),d=!0;break;case"anchor":g&&r(E,"MULTIPLE_ANCHORS","A node can have at most one anchor"),E.source.endsWith(":")&&r(E.offset+E.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=E,O??(O=E.offset),u=!1,d=!1,w=!0;break;case"tag":{S&&r(E,"MULTIPLE_TAGS","A node can have at most one tag"),S=E,O??(O=E.offset),u=!1,d=!1,w=!0;break}case t:(g||S)&&r(E,"BAD_PROP_ORDER",`Anchors and tags must be after the ${E.source} indicator`),T&&r(E,"UNEXPECTED_TOKEN",`Unexpected ${E.source} in ${e??"collection"}`),T=E,u=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){C&&r(E,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),C=E,u=!1,d=!1;break}default:r(E,"UNEXPECTED_TOKEN",`Unexpected ${E.type} token`),u=!1,d=!1}const $=n[n.length-1],x=$?$.offset+$.source.length:i;return w&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(u&&p.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:C,found:T,spaceBefore:c,comment:f,hasNewline:m,anchor:g,tag:S,newlineAfterProp:b,end:x,start:O??x}}l(ze,"resolveProps");function ct(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
64
- `))return!0;if(n.end){for(const e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of n.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(ct(e.key)||ct(e.value))return!0}return!1;default:return!0}}l(ct,"containsNewline");function Jn(n,e,t){if(e?.type==="flow-collection"){const s=e.end[0];s.indent===n&&(s.source==="]"||s.source==="}")&&ct(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Jn,"flowIndentCheck");function ji(n,e,t){const{uniqueKeys:s}=n.options;if(s===!1)return!1;const i=typeof s=="function"?s:(r,o)=>r===o||R(r)&&R(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(ji,"mapIncludes");const Ki="All mapping items must start at the same column";function fa({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=r?.nodeClass??te,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=s.offset,u=null;for(const d of s.items){const{start:f,key:h,sep:m,value:w}=d,p=ze(f,{indicator:"explicit-key-ind",next:h??m?.[0],offset:c,onError:i,parentIndent:s.indent,startOnNewline:!0}),g=!p.found;if(g){if(h&&(h.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&i(c,"BAD_INDENT",Ki)),!p.anchor&&!p.tag&&!m){u=p.end,p.comment&&(a.comment?a.comment+=`
65
- `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||ct(h))&&i(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==s.indent&&i(c,"BAD_INDENT",Ki);t.atKey=!0;const S=p.end,b=h?n(t,h,p,i):e(t,S,f,null,p,i);t.schema.compat&&Jn(s.indent,h,i),t.atKey=!1,ji(t,a.items,b)&&i(S,"DUPLICATE_KEY","Map keys must be unique");const C=ze(m??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:i,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(c=C.end,C.found){g&&(w?.type==="block-map"&&!C.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<C.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const T=w?n(t,w,C,i):e(t,c,m,null,C,i);t.schema.compat&&Jn(s.indent,w,i),c=T.range[2];const O=new Y(b,T);t.options.keepSourceTokens&&(O.srcToken=d),a.items.push(O)}else{g&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),C.comment&&(b.comment?b.comment+=`
66
- `+C.comment:b.comment=C.comment);const T=new Y(b);t.options.keepSourceTokens&&(T.srcToken=d),a.items.push(T)}}return u&&u<c&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,c,u??c],a}l(fa,"resolveBlockMap");function da({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=r?.nodeClass??ge,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=s.offset,u=null;for(const{start:d,value:f}of s.items){const h=ze(d,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const m=f?n(t,f,h,i):e(t,h.end,d,null,h,i);t.schema.compat&&Jn(s.indent,f,i),c=m.range[2],a.items.push(m)}return a.range=[s.offset,c,u??c],a}l(da,"resolveBlockSeq");function lt(n,e,t,s){let i="";if(n){let r=!1,o="";for(const a of n){const{source:c,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=c.substring(1)||" ";i?i+=o+d:i=d,o="";break}case"newline":i&&(o+=c),r=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:i,offset:e}}l(lt,"resolveEnd");const Vn="Block collections are not allowed within flow collections",Wn=l(n=>n&&(n.type==="block-map"||n.type==="block-seq"),"isBlock");function ha({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=s.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?te:ge),u=new c(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=s.offset+s.start.source.length;for(let g=0;g<s.items.length;++g){const S=s.items[g],{start:b,key:C,sep:T,value:O}=S,$=ze(b,{flow:a,indicator:"explicit-key-ind",next:C??T?.[0],offset:f,onError:i,parentIndent:s.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!T&&!O){g===0&&$.comma?i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<s.items.length-1&&i($.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),$.comment&&(u.comment?u.comment+=`
67
- `+$.comment:u.comment=$.comment),f=$.end;continue}!o&&t.options.strict&&ct(C)&&i(C,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)$.comma&&i($.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if($.comma||i($.start,"MISSING_CHAR",`Missing , between ${a} items`),$.comment){let x="";e:for(const E of b)switch(E.type){case"comma":case"space":break;case"comment":x=E.source.substring(1);break e;default:break e}if(x){let E=u.items[u.items.length-1];B(E)&&(E=E.value??E.key),E.comment?E.comment+=`
68
- `+x:E.comment=x,$.comment=$.comment.substring(x.length+1)}}if(!o&&!T&&!$.found){const x=O?n(t,O,$,i):e(t,$.end,T,null,$,i);u.items.push(x),f=x.range[2],Wn(O)&&i(x.range,"BLOCK_IN_FLOW",Vn)}else{t.atKey=!0;const x=$.end,E=C?n(t,C,$,i):e(t,x,b,null,$,i);Wn(C)&&i(E.range,"BLOCK_IN_FLOW",Vn),t.atKey=!1;const z=ze(T??[],{flow:a,indicator:"map-value-ind",next:O,offset:E.range[2],onError:i,parentIndent:s.indent,startOnNewline:!1});if(z.found){if(!o&&!$.found&&t.options.strict){if(T)for(const G of T){if(G===z.found)break;if(G.type==="newline"){i(G,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<z.found.offset-1024&&i(z.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(z.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const de=O?n(t,O,z,i):z.found?e(t,z.end,T,null,z,i):null;de?Wn(O)&&i(de.range,"BLOCK_IN_FLOW",Vn):z.comment&&(E.comment?E.comment+=`
69
- `+z.comment:E.comment=z.comment);const Ee=new Y(E,de);if(t.options.keepSourceTokens&&(Ee.srcToken=S),o){const G=u;ji(t,G.items,E)&&i(x,"DUPLICATE_KEY","Map keys must be unique"),G.items.push(Ee)}else{const G=new te(t.schema);G.flow=!0,G.items.push(Ee);const cs=(de??E).range;G.range=[E.range[0],cs[1],cs[2]],u.items.push(G)}f=de?de.range[2]:z.end}}const h=o?"}":"]",[m,...w]=s.end;let p=f;if(m&&m.source===h)p=m.offset+m.source.length;else{const g=a[0].toUpperCase()+a.substring(1),S=d?`${g} must end with a ${h}`:`${g} in block collection must be sufficiently indented and end with a ${h}`;i(f,d?"MISSING_CHAR":"BAD_INDENT",S),m&&m.source.length!==1&&w.unshift(m)}if(w.length>0){const g=lt(w,p,t.options.strict,i);g.comment&&(u.comment?u.comment+=`
70
- `+g.comment:u.comment=g.comment),u.range=[s.offset,p,g.offset]}else u.range=[s.offset,p,p];return u}l(ha,"resolveFlowCollection");function zn(n,e,t,s,i,r){const o=t.type==="block-map"?fa(n,e,t,s,r):t.type==="block-seq"?da(n,e,t,s,r):ha(n,e,t,s,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(zn,"resolveCollection");function pa(n,e,t,s,i){const r=s.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:m}=s,w=h&&r?h.offset>r.offset?h:r:h??r;w&&(!m||m.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===te.tagName&&a==="map"||o===ge.tagName&&a==="seq")return zn(n,e,t,i,o);let c=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!c){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=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),zn(n,e,t,i,o)}const u=zn(n,e,t,i,o,c),d=c.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,f=U(d)?d:new _(d);return f.range=u.range,f.tag=o,c?.format&&(f.format=c.format),f}l(pa,"composeCollection");function Di(n,e,t){const s=e.offset,i=ma(e,n.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[s,s,s]};const r=i.mode===">"?_.BLOCK_FOLDED:_.BLOCK_LITERAL,o=e.source?ga(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const g=o[p][1];if(g===""||g==="\r")a=p;else break}if(a===0){const p=i.chomp==="+"&&o.length>0?`
71
- `.repeat(Math.max(1,o.length-1)):"";let g=s+i.length;return e.source&&(g+=e.source.length),{value:p,type:r,comment:i.comment,range:[s,g,g]}}let c=e.indent+i.indent,u=e.offset+i.length,d=0;for(let p=0;p<a;++p){const[g,S]=o[p];if(S===""||S==="\r")i.indent===0&&g.length>c&&(c=g.length);else{g.length<c&&t(u+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=g.length),d=p,c===0&&!n.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=g.length+S.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>c&&(a=p+1);let f="",h="",m=!1;for(let p=0;p<d;++p)f+=o[p][0].slice(c)+`
72
- `;for(let p=d;p<a;++p){let[g,S]=o[p];u+=g.length+S.length+1;const b=S[S.length-1]==="\r";if(b&&(S=S.slice(0,-1)),S&&g.length<c){const T=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-S.length-(b?2:1),"BAD_INDENT",T),g=""}r===_.BLOCK_LITERAL?(f+=h+g.slice(c)+S,h=`
73
- `):g.length>c||S[0]===" "?(h===" "?h=`
63
+ `}},"prettifyError");function We(s,{flow:e,indicator:t,next:n,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,d="",h="",m=!1,w=!1,p=null,y=null,C=null,k=null,O=null,T=null,I=null;for(const A of s)switch(w&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&r(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(u&&A.type!=="comment"&&A.type!=="newline"&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),A.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(p=A),f=!0;break;case"comment":{f||r(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const z=A.source.substring(1)||" ";d?d+=h+z:d=z,h="",u=!1;break}case"newline":u?d?d+=A.source:(!T||t!=="seq-item-ind")&&(c=!0):h+=A.source,u=!0,m=!0,(y||C)&&(k=A),f=!0;break;case"anchor":y&&r(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&r(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,I??(I=A.offset),u=!1,f=!1,w=!0;break;case"tag":{C&&r(A,"MULTIPLE_TAGS","A node can have at most one tag"),C=A,I??(I=A.offset),u=!1,f=!1,w=!0;break}case t:(y||C)&&r(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),T&&r(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),T=A,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){O&&r(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=A,u=!1,f=!1;break}default:r(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,f=!1}const $=s[s.length-1],B=$?$.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"),p&&(u&&p.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:O,found:T,spaceBefore:c,comment:d,hasNewline:m,anchor:y,tag:C,newlineAfterProp:k,end:B,start:I??B}}l(We,"resolveProps");function gt(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(gt(e.key)||gt(e.value))return!0}return!1;default:return!0}}l(gt,"containsNewline");function Xn(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&gt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Xn,"flowIndentCheck");function Ai(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const i=typeof n=="function"?n:(r,o)=>r===o||M(r)&&M(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(Ai,"mapIncludes");const Oi="All mapping items must start at the same column";function ha({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??re,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,u=null;for(const f of n.items){const{start:d,key:h,sep:m,value:w}=f,p=We(d,{indicator:"explicit-key-ind",next:h??m?.[0],offset:c,onError:i,parentIndent:n.indent,startOnNewline:!0}),y=!p.found;if(y){if(h&&(h.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&i(c,"BAD_INDENT",Oi)),!p.anchor&&!p.tag&&!m){u=p.end,p.comment&&(a.comment?a.comment+=`
65
+ `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||gt(h))&&i(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&i(c,"BAD_INDENT",Oi);t.atKey=!0;const C=p.end,k=h?s(t,h,p,i):e(t,C,d,null,p,i);t.schema.compat&&Xn(n.indent,h,i),t.atKey=!1,Ai(t,a.items,k)&&i(C,"DUPLICATE_KEY","Map keys must be unique");const O=We(m??[],{indicator:"map-value-ind",next:w,offset:k.range[2],onError:i,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(c=O.end,O.found){y&&(w?.type==="block-map"&&!O.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<O.found.offset-1024&&i(k.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const T=w?s(t,w,O,i):e(t,c,m,null,O,i);t.schema.compat&&Xn(n.indent,w,i),c=T.range[2];const I=new Z(k,T);t.options.keepSourceTokens&&(I.srcToken=f),a.items.push(I)}else{y&&i(k.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(k.comment?k.comment+=`
66
+ `+O.comment:k.comment=O.comment);const T=new Z(k);t.options.keepSourceTokens&&(T.srcToken=f),a.items.push(T)}}return u&&u<c&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,u??c],a}l(ha,"resolveBlockMap");function pa({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=r?.nodeClass??Ce,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=n.offset,u=null;for(const{start:f,value:d}of n.items){const h=We(f,{indicator:"seq-item-ind",next:d,offset:c,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(c,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const m=d?s(t,d,h,i):e(t,h.end,f,null,h,i);t.schema.compat&&Xn(n.indent,d,i),c=m.range[2],a.items.push(m)}return a.range=[n.offset,c,u??c],a}l(pa,"resolveBlockSeq");function yt(s,e,t,n){let i="";if(s){let r=!1,o="";for(const a of s){const{source:c,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const f=c.substring(1)||" ";i?i+=o+f:i=f,o="";break}case"newline":i&&(o+=c),r=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:i,offset:e}}l(yt,"resolveEnd");const es="Block collections are not allowed within flow collections",ts=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function ma({composeNode:s,composeEmptyNode:e},t,n,i,r){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?re:Ce),u=new c(t.schema);u.flow=!0;const f=t.atRoot;f&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=n.offset+n.start.source.length;for(let y=0;y<n.items.length;++y){const C=n.items[y],{start:k,key:O,sep:T,value:I}=C,$=We(k,{flow:a,indicator:"explicit-key-ind",next:O??T?.[0],offset:d,onError:i,parentIndent:n.indent,startOnNewline:!1});if(!$.found){if(!$.anchor&&!$.tag&&!T&&!I){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&&gt(O)&&i(O,"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 B="";e:for(const A of k)switch(A.type){case"comma":case"space":break;case"comment":B=A.source.substring(1);break e;default:break e}if(B){let A=u.items[u.items.length-1];q(A)&&(A=A.value??A.key),A.comment?A.comment+=`
68
+ `+B:A.comment=B,$.comment=$.comment.substring(B.length+1)}}if(!o&&!T&&!$.found){const B=I?s(t,I,$,i):e(t,$.end,T,null,$,i);u.items.push(B),d=B.range[2],ts(I)&&i(B.range,"BLOCK_IN_FLOW",es)}else{t.atKey=!0;const B=$.end,A=O?s(t,O,$,i):e(t,B,k,null,$,i);ts(O)&&i(A.range,"BLOCK_IN_FLOW",es),t.atKey=!1;const z=We(T??[],{flow:a,indicator:"map-value-ind",next:I,offset:A.range[2],onError:i,parentIndent:n.indent,startOnNewline:!1});if(z.found){if(!o&&!$.found&&t.options.strict){if(T)for(const G of T){if(G===z.found)break;if(G.type==="newline"){i(G,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}$.start<z.found.offset-1024&&i(z.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else I&&("source"in I&&I.source&&I.source[0]===":"?i(I,"MISSING_CHAR",`Missing space after : in ${a}`):i(z.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const we=I?s(t,I,z,i):z.found?e(t,z.end,T,null,z,i):null;we?ts(I)&&i(we.range,"BLOCK_IN_FLOW",es):z.comment&&(A.comment?A.comment+=`
69
+ `+z.comment:A.comment=z.comment);const Le=new Z(A,we);if(t.options.keepSourceTokens&&(Le.srcToken=C),o){const G=u;Ai(t,G.items,A)&&i(B,"DUPLICATE_KEY","Map keys must be unique"),G.items.push(Le)}else{const G=new re(t.schema);G.flow=!0,G.items.push(Le);const ks=(we??A).range;G.range=[A.range[0],ks[1],ks[2]],u.items.push(G)}d=we?we.range[2]:z.end}}const h=o?"}":"]",[m,...w]=n.end;let p=d;if(m&&m.source===h)p=m.offset+m.source.length;else{const y=a[0].toUpperCase()+a.substring(1),C=f?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;i(d,f?"MISSING_CHAR":"BAD_INDENT",C),m&&m.source.length!==1&&w.unshift(m)}if(w.length>0){const y=yt(w,p,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
70
+ `+y.comment:u.comment=y.comment),u.range=[n.offset,p,y.offset]}else u.range=[n.offset,p,p];return u}l(ma,"resolveFlowCollection");function ns(s,e,t,n,i,r){const o=t.type==="block-map"?ha(s,e,t,n,r):t.type==="block-seq"?pa(s,e,t,n,r):ma(s,e,t,n,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(ns,"resolveCollection");function ga(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:m}=n,w=h&&r?h.offset>r.offset?h:r:h??r;w&&(!m||m.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===re.tagName&&a==="map"||o===Ce.tagName&&a==="seq")return ns(s,e,t,i,o);let c=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!c){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=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),ns(s,e,t,i,o)}const u=ns(s,e,t,i,o,c),f=c.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,d=V(f)?f:new N(f);return d.range=u.range,d.tag=o,c?.format&&(d.format=c.format),d}l(ga,"composeCollection");function Ii(s,e,t){const n=e.offset,i=ya(e,s.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[n,n,n]};const r=i.mode===">"?N.BLOCK_FOLDED:N.BLOCK_LITERAL,o=e.source?wa(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const y=o[p][1];if(y===""||y==="\r")a=p;else break}if(a===0){const p=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:p,type:r,comment:i.comment,range:[n,y,y]}}let c=e.indent+i.indent,u=e.offset+i.length,f=0;for(let p=0;p<a;++p){const[y,C]=o[p];if(C===""||C==="\r")i.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=y.length),f=p,c===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+C.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>c&&(a=p+1);let d="",h="",m=!1;for(let p=0;p<f;++p)d+=o[p][0].slice(c)+`
72
+ `;for(let p=f;p<a;++p){let[y,C]=o[p];u+=y.length+C.length+1;const k=C[C.length-1]==="\r";if(k&&(C=C.slice(0,-1)),C&&y.length<c){const T=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-C.length-(k?2:1),"BAD_INDENT",T),y=""}r===N.BLOCK_LITERAL?(d+=h+y.slice(c)+C,h=`
73
+ `):y.length>c||C[0]===" "?(h===" "?h=`
74
74
  `:!m&&h===`
75
75
  `&&(h=`
76
76
 
77
- `),f+=h+g.slice(c)+S,h=`
78
- `,m=!0):S===""?h===`
79
- `?f+=`
77
+ `),d+=h+y.slice(c)+C,h=`
78
+ `,m=!0):C===""?h===`
79
+ `?d+=`
80
80
  `:h=`
81
- `:(f+=h+S,h=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)f+=`
82
- `+o[p][0].slice(c);f[f.length-1]!==`
83
- `&&(f+=`
84
- `);break;default:f+=`
85
- `}const w=s+i.length+e.source.length;return{value:f,type:r,comment:i.comment,range:[s,w,w]}}l(Di,"resolveBlockScalar");function ma({offset:n,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",c=-1;for(let h=1;h<i.length;++h){const m=i[h];if(!a&&(m==="-"||m==="+"))a=m;else{const w=Number(m);!o&&w?o=w:c===-1&&(c=n+h)}}c!==-1&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,d="",f=i.length;for(let h=1;h<e.length;++h){const m=e[h];switch(m.type){case"space":u=!0;case"newline":f+=m.source.length;break;case"comment":t&&!u&&s(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,d=m.source.substring(1);break;case"error":s(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{const w=`Unexpected token in block scalar header: ${m.type}`;s(m,"UNEXPECTED_TOKEN",w);const p=m.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:r,indent:o,chomp:a,comment:d,length:f}}l(ma,"parseBlockScalarHeader");function ga(n){const e=n.split(/\n( *)/),t=e[0],s=t.match(/^( *)/),r=[s?.[1]?[s[1],t.slice(s[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}l(ga,"splitLines");function Mi(n,e,t){const{offset:s,type:i,source:r,end:o}=n;let a,c;const u=l((h,m,w)=>t(s+h,m,w),"_onError");switch(i){case"scalar":a=_.PLAIN,c=ya(r,u);break;case"single-quoted-scalar":a=_.QUOTE_SINGLE,c=wa(r,u);break;case"double-quoted-scalar":a=_.QUOTE_DOUBLE,c=ba(r,u);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[s,s+r.length,s+r.length]}}const d=s+r.length,f=lt(o,d,e,t);return{value:c,type:a,comment:f.comment,range:[s,d,f.offset]}}l(Mi,"resolveFlowScalar");function ya(n,e){let t="";switch(n[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 ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Ri(n)}l(ya,"plainValue");function wa(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Ri(n.slice(1,-1)).replace(/''/g,"'")}l(wa,"singleQuotedValue");function Ri(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
81
+ `:(d+=h+C,h=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)d+=`
82
+ `+o[p][0].slice(c);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]}}l(Ii,"resolveBlockScalar");function ya({offset:s,props:e},t,n){if(e[0].type!=="block-scalar-header")return n(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",c=-1;for(let h=1;h<i.length;++h){const m=i[h];if(!a&&(m==="-"||m==="+"))a=m;else{const w=Number(m);!o&&w?o=w:c===-1&&(c=s+h)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,f="",d=i.length;for(let h=1;h<e.length;++h){const m=e[h];switch(m.type){case"space":u=!0;case"newline":d+=m.source.length;break;case"comment":t&&!u&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,f=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{const w=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",w);const p=m.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:r,indent:o,chomp:a,comment:f,length:d}}l(ya,"parseBlockScalarHeader");function wa(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),r=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}l(wa,"splitLines");function $i(s,e,t){const{offset:n,type:i,source:r,end:o}=s;let a,c;const u=l((h,m,w)=>t(n+h,m,w),"_onError");switch(i){case"scalar":a=N.PLAIN,c=ba(r,u);break;case"single-quoted-scalar":a=N.QUOTE_SINGLE,c=Sa(r,u);break;case"double-quoted-scalar":a=N.QUOTE_DOUBLE,c=ka(r,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[n,n+r.length,n+r.length]}}const f=n+r.length,d=yt(o,f,e,t);return{value:c,type:a,comment:d.comment,range:[n,f,d.offset]}}l($i,"resolveFlowScalar");function ba(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}`),Ni(s)}l(ba,"plainValue");function Sa(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Ni(s.slice(1,-1)).replace(/''/g,"'")}l(Sa,"singleQuotedValue");function Ni(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
86
86
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
87
- `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(n);if(!s)return n;let i=s[1],r=" ",o=e.lastIndex;for(t.lastIndex=o;s=t.exec(n);)s[1]===""?r===`
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+s[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(n),i+r+(s?.[1]??"")}l(Ri,"foldLines");function ba(n,e){let t="";for(let s=1;s<n.length-1;++s){const i=n[s];if(!(i==="\r"&&n[s+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]??"")}l(Ni,"foldLines");function ka(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}=Sa(n,s);t+=r,s=o}else if(i==="\\"){let r=n[++s];const o=ka[r];if(o)t+=o;else if(r===`
92
- `)for(r=n[s+1];r===" "||r===" ";)r=n[++s+1];else if(r==="\r"&&n[s+1]===`
93
- `)for(r=n[++s+1];r===" "||r===" ";)r=n[++s+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=Ca(n,s+1,a,e),s+=a}else{const a=n.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=s;let o=n[s+1];for(;o===" "||o===" ";)o=n[++s+1];o!==`
94
- `&&!(o==="\r"&&n[s+2]===`
95
- `)&&(t+=s>r?n.slice(r,s+1):i)}else t+=i}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}l(ba,"doubleQuotedValue");function Sa(n,e){let t="",s=n[e+1];for(;(s===" "||s===" "||s===`
96
- `||s==="\r")&&!(s==="\r"&&n[e+2]!==`
97
- `);)s===`
91
+ `){const{fold:r,offset:o}=Ca(s,n);t+=r,n=o}else if(i==="\\"){let r=s[++n];const o=va[r];if(o)t+=o;else if(r===`
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+=Ea(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
+ `&&!(o==="\r"&&s[n+2]===`
95
+ `)&&(t+=n>r?s.slice(r,n+1):i)}else t+=i}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}l(ka,"doubleQuotedValue");function Ca(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
+ `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
97
+ `);)n===`
98
98
  `&&(t+=`
99
- `),e+=1,s=n[e+1];return t||(t=" "),{fold:t,offset:e}}l(Sa,"foldNewline");const ka={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 Ca(n,e,t,s){const i=n.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=n.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}l(Ca,"parseCharCode");function Bi(n,e,t,s){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Di(n,e,s):Mi(e,n.options.strict,s),c=t?n.directives.tagName(t.source,f=>s(t,"TAG_RESOLVE_FAILED",f)):null;let u;n.options.stringKeys&&n.atKey?u=n.schema[ce]:c?u=va(n.schema,i,c,t,s):e.type==="scalar"?u=Aa(n,i,e,s):u=n.schema[ce];let d;try{const f=u.resolve(i,h=>s(t??e,"TAG_RESOLVE_FAILED",h),n.options);d=R(f)?f:new _(f)}catch(f){const h=f instanceof Error?f.message:String(f);s(t??e,"TAG_RESOLVE_FAILED",h),d=new _(i)}return d.range=a,d.source=i,r&&(d.type=r),c&&(d.tag=c),u.format&&(d.format=u.format),o&&(d.comment=o),d}l(Bi,"composeScalar");function va(n,e,t,s,i){if(t==="!")return n[ce];const r=[];for(const a of n.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=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[ce])}l(va,"findScalarTagByName");function Aa({atKey:n,directives:e,schema:t},s,i,r){const o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(s))||t[ce];if(t.compat){const a=t.compat.find(c=>c.default&&c.test?.test(s))??t[ce];if(o.tag!==a.tag){const c=e.tagString(o.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${u}`;r(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}l(Aa,"findScalarTagByTest");function Oa(n,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let i=e[s];switch(i.type){case"space":case"comment":case"newline":n-=i.source.length;continue}for(i=e[++s];i?.type==="space";)n+=i.source.length,i=e[++s];break}}return n}l(Oa,"emptyScalarPosition");const Ea={composeNode:Fi,composeEmptyNode:Hn};function Fi(n,e,t,s){const i=n.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=t;let u,d=!0;switch(e.type){case"alias":u=Ta(n,e,s),(a||c)&&s(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=Bi(n,e,c,s),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=pa(Ea,n,e,t,s),a&&(u.anchor=a.source.substring(1));break;default:{const f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",f),u=Hn(n,e.offset,void 0,null,t,s),d=!1}}return a&&u.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&n.options.stringKeys&&(!R(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&s(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),n.options.keepSourceTokens&&d&&(u.srcToken=e),u}l(Fi,"composeNode");function Hn(n,e,t,s,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const d={type:"scalar",offset:Oa(e,t,s),indent:-1,source:""},f=Bi(n,d,a,u);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),r&&(f.comment=r,f.range[2]=c),f}l(Hn,"composeEmptyNode");function Ta({options:n},{offset:e,source:t,end:s},i){const r=new $t(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=lt(s,o,n.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(Ta,"composeAlias");function $a(n,e,{offset:t,start:s,value:i,end:r},o){const a=Object.assign({_directives:e},n),c=new Ze(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=ze(s,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Fi(u,i,d,o):Hn(u,d.end,s,null,d,o);const f=c.contents.range[2],h=lt(r,f,!1,o);return h.comment&&(c.comment=h.comment),c.range=[t,f,h.offset],c}l($a,"composeDoc");function ut(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];const{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}l(ut,"getErrorPos");function qi(n){let e="",t=!1,s=!1;for(let i=0;i<n.length;++i){const r=n[i];switch(r[0]){case"#":e+=(e===""?"":s?`
99
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}l(Ca,"foldNewline");const va={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 Ea(s,e,t,n){const i=s.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}l(Ea,"parseCharCode");function xi(s,e,t,n){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?Ii(s,e,n):$i(e,s.options.strict,n),c=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[he]:c?u=Ta(s.schema,i,c,t,n):e.type==="scalar"?u=Aa(s,i,e,n):u=s.schema[he];let f;try{const d=u.resolve(i,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);f=M(d)?d:new N(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),f=new N(i)}return f.range=a,f.source=i,r&&(f.type=r),c&&(f.tag=c),u.format&&(f.format=u.format),o&&(f.comment=o),f}l(xi,"composeScalar");function Ta(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])}l(Ta,"findScalarTagByName");function Aa({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(c=>c.default&&c.test?.test(n))??t[he];if(o.tag!==a.tag){const c=e.tagString(o.tag),u=e.tagString(a.tag),f=`Value may be parsed as either ${c} or ${u}`;r(i,"TAG_RESOLVE_FAILED",f,!0)}}return o}l(Aa,"findScalarTagByTest");function Oa(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let i=e[n];switch(i.type){case"space":case"comment":case"newline":s-=i.source.length;continue}for(i=e[++n];i?.type==="space";)s+=i.source.length,i=e[++n];break}}return s}l(Oa,"emptyScalarPosition");const Ia={composeNode:Li,composeEmptyNode:ss};function Li(s,e,t,n){const i=s.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=t;let u,f=!0;switch(e.type){case"alias":u=$a(s,e,n),(a||c)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=xi(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=ga(Ia,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=ss(s,e.offset,void 0,null,t,n),f=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&s.options.stringKeys&&(!M(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&f&&(u.srcToken=e),u}l(Li,"composeNode");function ss(s,e,t,n,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const f={type:"scalar",offset:Oa(e,t,n),indent:-1,source:""},d=xi(s,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(d.spaceBefore=!0),r&&(d.comment=r,d.range[2]=c),d}l(ss,"composeEmptyNode");function $a({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=yt(n,o,s.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l($a,"composeAlias");function Na(s,e,{offset:t,start:n,value:i,end:r},o){const a=Object.assign({_directives:e},s),c=new it(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=We(n,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?Li(u,i,f,o):ss(u,f.end,n,null,f,o);const d=c.contents.range[2],h=yt(r,d,!1,o);return h.comment&&(c.comment=h.comment),c.range=[t,d,h.offset],c}l(Na,"composeDoc");function wt(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}l(wt,"getErrorPos");function Pi(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,s=!1;break;case"%":n[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}l(qi,"parsePrelude");class Gn{static{l(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,i,r)=>{const o=ut(t);r?this.warnings.push(new Pi(o,s,i)):this.errors.push(new Ae(o,s,i))},this.directives=new Q({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:s,afterEmptyLine:i}=qi(this.prelude);if(s){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
- ${s}`:s;else if(i||e.directives.docStart||!r)e.commentBefore=s;else if(q(r)&&!r.flow&&r.items.length>0){let o=r.items[0];B(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${s}
105
- ${a}`:s}else{const o=r.commentBefore;r.commentBefore=o?`${s}
106
- ${o}`:s}}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:qi(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(const i of e)yield*this.next(i);yield*this.end(t,s)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,s,i)=>{const r=ut(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",s,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=$a(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,s=new Ae(ut(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){const s="Unexpected doc-end without preceding document";this.errors.push(new Ae(ut(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;const t=lt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const s=this.doc.comment;this.doc.comment=s?`${s}
107
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ae(ut(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 s=Object.assign({_directives:this.directives},this.options),i=new Ze(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function Ia(n,e=!0,t){if(n){const s=l((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new Ae([a,a+1],r,o)},"_onError");switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Mi(n,e,s);case"block-scalar":return Di({options:{strict:e}},n,s)}}return null}l(Ia,"resolveAsScalar");function Na(n,e){const{implicitKey:t=!1,indent:s,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=ot({type:o,value:n},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:s,source:`
103
+ `)+(r.substring(1)||" "),t=!0,n=!1;break;case"%":s[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}l(Pi,"parsePrelude");class is{static{l(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,i,r)=>{const o=wt(t);r?this.warnings.push(new Ti(o,n,i)):this.errors.push(new Ne(o,n,i))},this.directives=new te({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:i}=Pi(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(J(r)&&!r.flow&&r.items.length>0){let o=r.items[0];q(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
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:Pi(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=wt(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",n,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Na(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 Ne(wt(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 Ne(wt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=yt(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 Ne(wt(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 it(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 xa(s,e=!0,t){if(s){const n=l((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new Ne([a,a+1],r,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return $i(s,e,n);case"block-scalar":return Ii({options:{strict:e}},s,n)}}return null}l(xa,"resolveAsScalar");function La(s,e){const{implicitKey:t=!1,indent:n,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=pt({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
108
108
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
109
- `),d=a.substring(0,u),f=a.substring(u+1)+`
110
- `,h=[{type:"block-scalar-header",offset:r,indent:s,source:d}];return Ui(h,c)||h.push({type:"newline",offset:-1,indent:s,source:`
111
- `}),{type:"block-scalar",offset:r,indent:s,props:h,source:f}}case'"':return{type:"double-quoted-scalar",offset:r,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:s,source:a,end:c};default:return{type:"scalar",offset:r,indent:s,source:a,end:c}}}l(Na,"createScalarToken");function _a(n,e,t={}){let{afterKey:s=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in n?n.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=n.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=ot({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":La(n,c);break;case'"':Yn(n,c,"double-quoted-scalar");break;case"'":Yn(n,c,"single-quoted-scalar");break;default:Yn(n,c,"scalar")}}l(_a,"setScalarValue");function La(n,e){const t=e.indexOf(`
112
- `),s=e.substring(0,t),i=e.substring(t+1)+`
113
- `;if(n.type==="block-scalar"){const r=n.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=s,n.source=i}else{const{offset:r}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:s}];Ui(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
- `});for(const c of Object.keys(n))c!=="type"&&c!=="offset"&&delete n[c];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:i})}}l(La,"setBlockScalarValue");function Ui(n,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}l(Ui,"addEndtoBlockProps");function Yn(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{const s=n.props.slice(1);let i=e.length;n.props[0].type==="block-scalar-header"&&(i-=n.props[0].source.length);for(const r of s)r.offset+=i;delete n.props,Object.assign(n,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{const i={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
115
- `};delete n.items,Object.assign(n,{type:t,source:e,end:[i]});break}default:{const s="indent"in n?n.indent:-1,i="end"in n&&Array.isArray(n.end)?n.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(n))r!=="type"&&r!=="offset"&&delete n[r];Object.assign(n,{type:t,indent:s,source:e,end:i})}}}l(Yn,"setFlowScalarValue");const xa=l(n=>"type"in n?Wt(n):zt(n),"stringify$1");function Wt(n){switch(n.type){case"block-scalar":{let e="";for(const t of n.props)e+=Wt(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(const t of n.items)e+=zt(t);return e}case"flow-collection":{let e=n.start.source;for(const t of n.items)e+=zt(t);for(const t of n.end)e+=t.source;return e}case"document":{let e=zt(n);if(n.end)for(const t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(const t of n.end)e+=t.source;return e}}}l(Wt,"stringifyToken");function zt({start:n,key:e,sep:t,value:s}){let i="";for(const r of n)i+=r.source;if(e&&(i+=Wt(e)),t)for(const r of t)i+=r.source;return s&&(i+=Wt(s)),i}l(zt,"stringifyItem");const Zn=Symbol("break visit"),Pa=Symbol("skip children"),Ji=Symbol("remove item");function Oe(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Vi(Object.freeze([]),n,e)}l(Oe,"visit"),Oe.BREAK=Zn,Oe.SKIP=Pa,Oe.REMOVE=Ji,Oe.itemAtPath=(n,e)=>{let t=n;for(const[s,i]of e){const r=t?.[s];if(r&&"items"in r)t=r.items[i];else return}return t},Oe.parentCollection=(n,e)=>{const t=Oe.itemAtPath(n,e.slice(0,-1)),s=e[e.length-1][0],i=t?.[s];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function Vi(n,e,t){let s=t(e,n);if(typeof s=="symbol")return s;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(n.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Zn)return Zn;a===Ji&&(r.items.splice(o,1),o-=1)}}typeof s=="function"&&i==="key"&&(s=s(e,n))}}return typeof s=="function"?s(e,n):s}l(Vi,"_visit");const Ht="\uFEFF",Gt="",Yt="",ft="",ja=l(n=>!!n&&"items"in n,"isCollection"),Ka=l(n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar"),"isScalar");function Da(n){switch(n){case Ht:return"<BOM>";case Gt:return"<DOC>";case Yt:return"<FLOW_END>";case ft:return"<SCALAR>";default:return JSON.stringify(n)}}l(Da,"prettyToken");function Wi(n){switch(n){case Ht:return"byte-order-mark";case Gt:return"doc-mode";case Yt:return"flow-error-end";case ft:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
109
+ `),f=a.substring(0,u),d=a.substring(u+1)+`
110
+ `,h=[{type:"block-scalar-header",offset:r,indent:n,source:f}];return _i(h,c)||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:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:n,source:a,end:c};default:return{type:"scalar",offset:r,indent:n,source:a,end:c}}}l(La,"createScalarToken");function Pa(s,e,t={}){let{afterKey:n=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=pt({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":_a(s,c);break;case'"':rs(s,c,"double-quoted-scalar");break;case"'":rs(s,c,"single-quoted-scalar");break;default:rs(s,c,"scalar")}}l(Pa,"setScalarValue");function _a(s,e){const t=e.indexOf(`
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}];_i(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
114
+ `});for(const c of Object.keys(s))c!=="type"&&c!=="offset"&&delete s[c];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:i})}}l(_a,"setBlockScalarValue");function _i(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}l(_i,"addEndtoBlockProps");function rs(s,e,t){switch(s.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":s.type=t,s.source=e;break;case"block-scalar":{const n=s.props.slice(1);let i=e.length;s.props[0].type==="block-scalar-header"&&(i-=s.props[0].source.length);for(const r of n)r.offset+=i;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const i={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
115
+ `};delete s.items,Object.assign(s,{type:t,source:e,end:[i]});break}default:{const n="indent"in s?s.indent:-1,i="end"in s&&Array.isArray(s.end)?s.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(s))r!=="type"&&r!=="offset"&&delete s[r];Object.assign(s,{type:t,indent:n,source:e,end:i})}}}l(rs,"setFlowScalarValue");const Da=l(s=>"type"in s?Gt(s):Ht(s),"stringify$1");function Gt(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Gt(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Ht(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Ht(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Ht(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}l(Gt,"stringifyToken");function Ht({start:s,key:e,sep:t,value:n}){let i="";for(const r of s)i+=r.source;if(e&&(i+=Gt(e)),t)for(const r of t)i+=r.source;return n&&(i+=Gt(n)),i}l(Ht,"stringifyItem");const os=Symbol("break visit"),ja=Symbol("skip children"),Di=Symbol("remove item");function xe(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),ji(Object.freeze([]),s,e)}l(xe,"visit"),xe.BREAK=os,xe.SKIP=ja,xe.REMOVE=Di,xe.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},xe.parentCollection=(s,e)=>{const t=xe.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 ji(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=ji(Object.freeze(s.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===os)return os;a===Di&&(r.items.splice(o,1),o-=1)}}typeof n=="function"&&i==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}l(ji,"_visit");const Yt="\uFEFF",Zt="",Qt="",bt="",Ka=l(s=>!!s&&"items"in s,"isCollection"),Ra=l(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Ma(s){switch(s){case Yt:return"<BOM>";case Zt:return"<DOC>";case Qt:return"<FLOW_END>";case bt:return"<SCALAR>";default:return JSON.stringify(s)}}l(Ma,"prettyToken");function Ki(s){switch(s){case Yt:return"byte-order-mark";case Zt:return"doc-mode";case Qt:return"flow-error-end";case bt: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(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}l(Wi,"tokenType");var Ma=Object.freeze({__proto__:null,BOM:Ht,DOCUMENT:Gt,FLOW_END:Yt,SCALAR:ft,createScalarToken:Na,isCollection:ja,isScalar:Ka,prettyToken:Da,resolveAsScalar:Ia,setScalarValue:_a,stringify:xa,tokenType:Wi,visit:Oe});function re(n){switch(n){case void 0:case" ":case`
118
- `:case"\r":case" ":return!0;default:return!1}}l(re,"isEmpty");const zi=new Set("0123456789ABCDEFabcdef"),Ra=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Zt=new Set(",[]{}"),Ba=new Set(` ,[]{}
119
- \r `),Qn=l(n=>!n||Ba.has(n),"isNotAnchorChar");class Hi{static{l(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let s=this.next??"stream";for(;s&&(t||this.hasChars(1));)s=yield*this.parseNext(s)}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}l(Ki,"tokenType");var Ba=Object.freeze({__proto__:null,BOM:Yt,DOCUMENT:Zt,FLOW_END:Qt,SCALAR:bt,createScalarToken:La,isCollection:Ka,isScalar:Ra,prettyToken:Ma,resolveAsScalar:xa,setScalarValue:Pa,stringify:Da,tokenType:Ki,visit:xe});function ue(s){switch(s){case void 0:case" ":case`
118
+ `:case"\r":case" ":return!0;default:return!1}}l(ue,"isEmpty");const Ri=new Set("0123456789ABCDEFabcdef"),Fa=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Xt=new Set(",[]{}"),qa=new Set(` ,[]{}
119
+ \r `),as=l(s=>!s||qa.has(s),"isNotAnchorChar");class Mi{static{l(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
120
120
  `?!0:t==="\r"?this.buffer[e+1]===`
121
- `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){const i=this.buffer[s+e+1];if(i===`
122
- `||!i&&!this.atEnd)return e+s+1}return t===`
123
- `||s>=this.indentNext||!t&&!this.atEnd?e+s:-1}if(t==="-"||t==="."){const s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&re(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]===Ht&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){const r=e[s-1];if(r===" "||r===" "){t=s-1;break}else s=e.indexOf("#",s+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==="...")&&re(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&&!re(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===":")&&re(t)){const s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,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(Qn),"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,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&i[0]!=="#"||s===0&&(i.startsWith("---")||i.startsWith("..."))&&re(i[3]))&&!(s===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(Qn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||re(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 s=this.buffer.substring(0,t);let i=s.indexOf(`
125
- `,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=s.indexOf(`
126
- `,r)}i!==-1&&(t=i-(s[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=>re(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let r=this.pos;s=this.buffer[r];++r)switch(s){case" ":t+=1;break;case`
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
+ `||!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==="...")&&ue(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]===Yt&&(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 Zt,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==="...")&&ue(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&&!ue(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===":")&&ue(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(as),"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("..."))&&ue(i[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Qt,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(as),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ue(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let i=n.indexOf(`
125
+ `,this.pos);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=>ue(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
- `)break}default:break e}if(!s&&!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
- `,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(s=this.buffer[i];s===" ";)s=this.buffer[++i];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
130
- `;)s=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 ft,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,s=this.pos-1,i;for(;i=this.buffer[++s];)if(i===":"){const r=this.buffer[s+1];if(re(r)||e&&Zt.has(r))break;t=s}else if(re(i)){let r=this.buffer[s+1];if(i==="\r"&&(r===`
132
- `?(s+=1,i=`
133
- `,r=this.buffer[s+1]):t=s),r==="#"||e&&Zt.has(r))break;if(i===`
134
- `){const o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&Zt.has(i))break;t=s}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield ft,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 s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.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(Qn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(re(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(;!re(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(Ra.has(t))t=this.buffer[++e];else if(t==="%"&&zi.has(this.buffer[e+1])&&zi.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===`
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
+ `,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
+ `;)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 bt,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(ue(r)||e&&Xt.has(r))break;t=n}else if(ue(i)){let r=this.buffer[n+1];if(i==="\r"&&(r===`
132
+ `?(n+=1,i=`
133
+ `,r=this.buffer[n+1]):t=n),r==="#"||e&&Xt.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&&Xt.has(i))break;t=n}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield bt,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(as))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ue(t)||e&&Xt.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(;!ue(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(Fa.has(t))t=this.buffer[++e];else if(t==="%"&&Ri.has(this.buffer[e+1])&&Ri.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,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");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,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Gi{static{l(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,s=this.lineStarts.length;for(;t<s;){const r=t+s>>1;this.lineStarts[r]<e?t=r+1:s=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 ye(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}l(ye,"includesToken");function Yi(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}l(Yi,"findNonEmptyIndex");function Zi(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}l(Zi,"isFlowToken");function Qt(n){switch(n.type){case"document":return n.start;case"block-map":{const e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}l(Qt,"getPrevProps");function He(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}l(He,"getFirstKeyStartProps");function Qi(n){if(n.start.type==="flow-seq-start")for(const e of n.items)e.sep&&!e.value&&!ye(e.start,"explicit-key-ind")&&!ye(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Zi(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}l(Qi,"fixFlowSeqItems");class Xn{static{l(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Hi,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const s of this.lexer.lex(e,t))yield*this.next(s);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=Wi(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 s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,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 s=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in s?s.indent:0:t.type==="flow-collection"&&s.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Qi(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{const i=s.items[s.items.length-1];if(i.value){s.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=s.items[s.items.length-1];i.value?s.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=s.items[s.items.length-1];!i||i.value?s.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((s.type==="document"||s.type==="block-map"||s.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&&Yi(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(s.type==="document"?s.end=i.start:s.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":{Yi(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)),s=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:s,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 Bi{static{l(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function ve(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}l(ve,"includesToken");function Fi(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}l(Fi,"findNonEmptyIndex");function qi(s){switch(s?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}l(qi,"isFlowToken");function en(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}l(en,"getPrevProps");function ze(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}l(ze,"getFirstKeyStartProps");function Ui(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,qi(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}l(Ui,"fixFlowSeqItems");class cs{static{l(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new Mi,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=Ki(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"&&Ui(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&&Fi(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":{Fi(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=en(this.peek(2)),n=ze(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 s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.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 s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ye(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(Zi(t.key)&&!ye(t.sep,"newline")){const o=He(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ye(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]}):ye(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&&!ye(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 s&&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 s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.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||ye(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s&&s.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 s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{const s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){const i=Qt(s),r=He(i);Qi(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 c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ve(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(qi(t.key)&&!ve(t.sep,"newline")){const o=ze(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ve(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=ze(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=en(n),r=ze(i);Ui(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=Qt(e),s=He(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=Qt(e),s=He(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.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 Xi(n){const e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Gi||null,prettyErrors:e}}l(Xi,"parseOptions");function Fa(n,e={}){const{lineCounter:t,prettyErrors:s}=Xi(e),i=new Xn(t?.addNewLine),r=new Gn(e),o=Array.from(r.compose(i.parse(n)));if(s&&t)for(const a of o)a.errors.forEach(Vt(n,t)),a.warnings.forEach(Vt(n,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Fa,"parseAllDocuments");function er(n,e={}){const{lineCounter:t,prettyErrors:s}=Xi(e),i=new Xn(t?.addNewLine),r=new Gn(e);let o=null;for(const a of r.compose(i.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ae(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(Vt(n,t)),o.warnings.forEach(Vt(n,t))),o}l(er,"parseDocument");function qa(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=er(n,t);if(!i)return null;if(i.warnings.forEach(r=>fi(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:s},t))}l(qa,"parse");function Ua(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=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(n===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return Se(n)&&!s?n.toString(t):new Ze(n,s,t).toString(t)}l(Ua,"stringify");var Ja=Object.freeze({__proto__:null,Alias:$t,CST:Ma,Composer:Gn,Document:Ze,Lexer:Hi,LineCounter:Gi,Pair:Y,Parser:Xn,Scalar:_,Schema:nn,YAMLError:Un,YAMLMap:te,YAMLParseError:Ae,YAMLSeq:ge,YAMLWarning:Pi,isAlias:me,isCollection:q,isDocument:Se,isMap:De,isNode:U,isPair:B,isScalar:R,isSeq:Me,parse:qa,parseAllDocuments:Fa,parseDocument:er,stringify:Ua,visit:ke,visitAsync:Tt});const Va={ignored:fo,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Wa extends on{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=Es(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(j.existsSync(this.membraneDir)||j.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=Kr.watch(this.membraneDir,Va),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("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("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const s=J.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(s);const a={filePath:t,relativePath:s,data:void 0};this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(s,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(s,i),this.emit(e,o)}readFileContent(e){return j.readFileSync(e,"utf8")}processFileEvent(e,t){const s=J.relative(this.membraneDir,e);let i;try{i=t?Ja.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:s,data:i}}hasContentChanged(e,t,s){if(s==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return $r.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]})}}const za={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Ha={info:v.blue,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class N{static{l(this,"Logger")}static formatMessage(e,t,s={}){const i=s.timestamp?`${v.gray(new Date().toISOString())} `:"",r=s.prefix?`${v.gray(s.prefix)} `:"",o=s.suffix?` ${v.gray(s.suffix)}`:"",a=za[t],c=Ha[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let s=v.blue;if(t?.color&&(s=v[t.color.toLowerCase()]||v.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${v.gray(`[${i}]`)} ${s(e)}`)}else console.debug(s(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(v.gray(`[${t.prefix}] ${e}`),t.error?`
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=en(e),n=ze(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=en(e),n=ze(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 Ji(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Bi||null,prettyErrors:e}}l(Ji,"parseOptions");function Ua(s,e={}){const{lineCounter:t,prettyErrors:n}=Ji(e),i=new cs(t?.addNewLine),r=new is(e),o=Array.from(r.compose(i.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(zt(s,t)),a.warnings.forEach(zt(s,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l(Ua,"parseAllDocuments");function Vi(s,e={}){const{lineCounter:t,prettyErrors:n}=Ji(e),i=new cs(t?.addNewLine),r=new is(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 Ne(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(zt(s,t)),o.warnings.forEach(zt(s,t))),o}l(Vi,"parseDocument");function Ja(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Vi(s,t);if(!i)return null;if(i.warnings.forEach(r=>ni(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:n},t))}l(Ja,"parse");function Va(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 Ae(s)&&!n?s.toString(t):new it(s,n,t).toString(t)}l(Va,"stringify");var Wa=Object.freeze({__proto__:null,Alias:Nt,CST:Ba,Composer:is,Document:it,Lexer:Mi,LineCounter:Bi,Pair:Z,Parser:cs,Scalar:N,Schema:mn,YAMLError:Qn,YAMLMap:re,YAMLParseError:Ne,YAMLSeq:Ce,YAMLWarning:Ti,isAlias:ke,isCollection:J,isDocument:Ae,isMap:je,isNode:V,isPair:q,isScalar:M,isSeq:Ke,parse:Ja,parseAllDocuments:Ua,parseDocument:Vi,stringify:Va,visit:Oe,visitAsync:$t});const se={Added:"added",Changed:"changed",Deleted:"deleted",Stopped:"stopped"},za={ignored:Lo,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ga extends At{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=It(this.options.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=to.watch(this.membraneDir,za),this.watcher.on("add",e=>this.handleFileSystemEvent(se.Added,e)).on("change",e=>this.handleFileSystemEvent(se.Changed,e)).on("unlink",e=>this.handleFileSystemEvent(se.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(se.Stopped))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(e===se.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};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),this.emit(e,o)}readFileContent(e){return L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let i;try{i=t?Wa.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 bn.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]})}}const W={SYNCING:"syncing",CONFLICTS:"conflicts",READY:"ready",ERROR:"error"},ce={LogAdded:"logAdded",StatusChanged:"statusChanged",StatsChanged:"statsChanged",ChangesFound:"changesFound"},Y={UPDATE:"update",DELETE:"delete",CREATE:"create"},Ha={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Ya={info:v.blue,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class x{static{l(this,"Logger")}static formatMessage(e,t,n={}){const i=n.timestamp?`${v.gray(new Date().toISOString())} `:"",r=n.prefix?`${v.gray(n.prefix)} `:"",o=n.suffix?` ${v.gray(n.suffix)}`:"",a=Ha[t],c=Ya[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let n=v.blue;if(t?.color&&(n=v[t.color.toLowerCase()]||v.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${v.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(v.gray(`[${t.prefix}] ${e}`),t.error?`
141
141
  ${v.red(t.error)}`:""):console.debug(v.gray(e),t?.error?`
142
- ${v.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(v.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const s=t||Object.keys(e[0]),i=e.map(r=>{const o={};return s.forEach(a=>{o[a]=r[a]}),o});console.table(i,s)}static divider(){}}async function Ga(n,e="full"){const t={};N.info("Getting remote workspace data");const s=await n.integrations.findAll();t.integration=s.map(i=>es("integration",i));for(const i of Object.keys(H)){const r=H[i];if(r.exportable===!1)continue;const o=[];N.info(`Reading ${r.elements} from remote workspace`);const a=await n[r.elements].findAll();if(o.push(...a.map(c=>es(i,c))),r.integrationSpecific)for(const c of s){const u=await n[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>(d.integrationKey=c.key,es(i,d))))}o.length>0&&e=="full"&&(console.table(o.map(c=>({key:c.key,integrationKey:c.integrationKey,universal:!c.integrationKey})).reduce((c,u)=>(c||(c={}),c[u.key]||(c[u.key]={}),u.universal&&(c[u.key].universal=!0),u.integrationKey&&(c[u.key].integration?c[u.key].integration+=` ${u.integrationKey}`:c[u.key].integration=u.integrationKey),c),{})),console.groupEnd()),t[i]=o}return N.success("Remote workspace data retrieved successfully"),t}l(Ga,"getWorkspaceData");function Ya(n){const e={},t={};for(const s of Object.keys(n))if(e[s]=[],t[s]=[],H[s]?.integrationSpecific)for(const r of n[s])r.integrationKey||r.integration||r.integrationId?t[s].push(r):e[s].push(r);else e[s].push(...n[s]);return{universalElements:e,integrationSpecificElements:t}}l(Ya,"splitWorkspaceData");function es(n,e){return e=xo(e),H[n].exportCleanup?H[n].exportCleanup(e):e}l(es,"cleanUpForExport");function dt(n){return Object.keys(n).some(e=>/universal.*Id/g.test(e)||/parentId/g.test(e))}l(dt,"hasParent");function Z(n,e){console.debug("\x1B[0m",`\x1B[${{Reset:"\x1B[0m",Bright:"\x1B[1m",Dim:"\x1B[2m",Underscore:"\x1B[4m",Blink:"\x1B[5m",Reverse:"\x1B[7m",Hidden:"\x1B[8m",Black:"\x1B[30m",Red:"\x1B[31m",Green:"\x1B[32m",Yellow:"\x1B[33m",Blue:"\x1B[34m",Magenta:"\x1B[35m",Cyan:"\x1B[36m",White:"\x1B[37m",Gray:"\x1B[90m",BgBlack:"\x1B[40m",BgRed:"\x1B[41m",BgGreen:"\x1B[42m",BgYellow:"\x1B[43m",BgBlue:"\x1B[44m",BgMagenta:"\x1B[45m",BgCyan:"\x1B[46m",BgWhite:"\x1B[47m",BgGray:"\x1B[100m"}[e]}`,n,"\x1B[0m")}l(Z,"coloredLog");const tr="connectors",nr="development",ts={};async function Za({integrations:n,allConnectors:e=!1}){const t=Hr(),s=await On.getClient(process.cwd()),i=new Set,r={};for(const o of n){const a=o.connectorId,c=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await sc({client:s,connectorId:a});(!!u.workspaceId||e)&&(i.has(a)||(await ic({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(c)||(await rc({client:s,connector:u,connectorVersion:c,basePath:t}),r[a].add(c)))}}}l(Za,"pullConnectors");async function Qa({client:n,workspaceData:e,pushContext:t,workspaceId:s}){const i={};console.debug("[Push] Loading custom connectors");const r=n,o=await r.get(`/connectors?workspaceId=${s}`);console.debug("[Push] Loading public connectors"),e.connector=o;const a=ns(),c=P.existsSync(a)?P.readdirSync(a):[];for(const u of c){console.debug(`[Push] Loading connector from: ${u}`);const d=P.readdirSync(K.join(a,u)),f=await Xa(u);if(delete f.baseUri,f.uuid&&e.connector?.find(m=>m.uuid==f.uuid))i[f.id]=e.connector.find(m=>m.uuid==f.uuid).id,Z(`Matched ${f.name} uuid: ${f.uuid}`,"Blue");else if(!i[f.id]){console.debug(`Creating connector ${f.name} (${f.key})`);const m=await r.post("connectors",{...f,workspaceId:s});i[f.id]=m.id}const h=d.filter(m=>P.statSync(K.join(a,u,m)).isDirectory());for(const m of h)await nc({client:n,connector:f,version:m,connectorId:i[f.id]})}t.connectorsMapping=i}l(Qa,"pushConnectors");function ns(){const n=et();return K.join(n.membraneDirPath,tr)}l(ns,"getConnectorsPath");async function Xa(n){return oe.load(P.readFileSync(K.join(ns(),n,`${n}.yml`),"utf8"))}l(Xa,"readConnector");async function ec(n,e){return console.debug(`Zipping ${n} into ${e}`),new Promise((t,s)=>{const i=P.createWriteStream(e),r=Dr("zip",{zlib:{level:9}});i.on("close",()=>{Z(`Successfully created ${e}`,"Green"),t()}),i.on("end",()=>{console.debug("Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):s(a)}),r.on("error",a=>{s(a)}),r.pipe(i);const o=P.readdirSync(n);for(const a of o){const c=K.join(n,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(ec,"createZipArchive");async function tc(n,e){return console.debug(`Unzipping into ${e}`),new Promise((t,s)=>{const i=Rr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=K.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=K.join(e,o),u=K.dirname(c);P.mkdirSync(u,{recursive:!0});const d=P.createWriteStream(c);r.pipe(d),d.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{Z(`Successfully extracted to ${e}`,"Green"),t()}),i.on("error",r=>{s(r)}),i.write(n),i.end()})}l(tc,"extractZipArchive");async function nc({client:n,connector:e,version:t,connectorId:s}){const i=K.join(ns(),Xt(e),sr(t)),r=K.join(i,"src"),o=K.join(i,"src.zip");if(P.existsSync(r)&&(console.debug(`Archiving source code for ${e.name} version ${t}`),await ec(r,o)),!P.existsSync(o)){N.warning(`No source code found for ${e.name} version ${t}`);return}try{const a=new Mr;if(a.append("file",P.createReadStream(o),"file.zip"),console.debug(`Pushing connector version ${t} for ${e.name}`),t==nr)console.debug(`Uploading connector ${s}`),await n.post(`connectors/${s}/upload`,a,{headers:{...a.getHeaders()}});else{if(a.append("version",t),a.append("changelog","Imported Version"),(await n.get(`/connectors/${s}/versions`)).find(u=>u.version==t)){Z(`Version ${t} already published`,"Blue");return}console.debug(`Publishing version ${t} of connector ${s}`),await n.post(`connectors/${s}/publish-version`,a,{headers:{...a.getHeaders()}})}N.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(a){N.error(`Error pushing connector version ${t} for ${e.name}`,a)}finally{P.existsSync(o)&&P.unlinkSync(o)}}l(nc,"pushConnectorVersion");async function sc({client:n,connectorId:e}){if(ts[e])return ts[e];const t=await n.get(`connectors/${e}`);return ts[e]=t,t}l(sc,"getConnector");async function ic({basePath:n,connector:e}){const t=Xt(e),s=K.join(n,tr,t);P.mkdirSync(s,{recursive:!0});const i=K.join(s,`${Xt(e)}.yml`);P.writeFileSync(i,oe.dump(e)),N.info(`Pulled connector ${e.name}`)}l(ic,"pullConnector");async function rc({client:n,connector:e,connectorVersion:t,basePath:s}){const i=Xt(e),r=sr(t),o=K.join(s,"connectors",i,r),a=await n.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});P.mkdirSync(o,{recursive:!0});const c=K.join(o,"src.zip");P.writeFileSync(c,a);const u=K.join(o,"src");P.existsSync(u)&&await tc(a,u),N.info(`[Pull] Connector Version: ${e.name} (${r})`)}l(rc,"pullConnectorVersion");function Xt(n){return n.key}l(Xt,"getConnectorDirName");function sr(n){return n??nr}l(sr,"getConnectorVersionDirName");class oc extends on{static{l(this,"WorkspaceService")}localManager;remoteManager;_status="idle";_elementCounts={};constructor(){super(),this.remoteManager=new jo,this.localManager=new po,V.on("logAdded",()=>this.emit("logAdded"))}get status(){return this._status}get elementCounts(){return{...this._elementCounts}}get logs(){return V.logs}get latestLogs(){return V.latestLogs}setStatus(e){this._status!==e&&(this._status=e,this.emit("statusChanged"))}incrementCounter(e,t){this._elementCounts[e]=(this._elementCounts[e]||0)+t,this.emit("counterChanged")}resetPullState(){this._status="idle",this._elementCounts={},V.clear(),this.emit("statusChanged"),this.emit("counterChanged")}async start({cwd:e}){await this.pullWorkspace();const t=new Wa({cwd:e});t.on("added",s=>this.processElementChange(s,"added")),t.on("changed",s=>this.processElementChange(s,"changed")),t.on("deleted",s=>this.processElementChange(s,"deleted"))}async pullWorkspace({allConnectors:e=!1}={}){this.resetPullState(),this.setStatus("pulling"),V.info("Starting pull..."),V.info("Pulling remote elements...");try{const t=await this.remoteManager.pull();V.info("Pulling connectors..."),await Za({integrations:t[M.Integration],allConnectors:e});for(const s of Object.keys(t)){const i=t[s];this.incrementCounter(s,i.length);for(const r of i)await this.localManager.writeElement(s,r)}this.setStatus("finished"),V.success("Finished pulling workspace.")}catch(t){throw this.setStatus("error"),V.error(`Error: ${t.message||t}`),t}}async processElementChange(e,t){try{const s=mo(e.relativePath);if(!s||!s.key||!s.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${s.key} of type ${s.type}`),t){case"added":case"changed":await this.remoteManager.pushElement(s.type,{...e.data,key:s.key});break;case"deleted":break}}catch(s){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,s)}}}const W=new oc,ir=l(n=>{switch(n){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ac(n,e=30){return n.length<=e?n:n.slice(0,e-3)+"..."}l(ac,"truncateWorkspaceName");const cc=l(n=>{switch(n){case"pulling":return y(k,{color:"yellow",children:"pulling remote workspace"});case"finished":return y(k,{color:"green",children:"in sync"});case"error":return y(k,{color:"red",children:"error"});default:return y(k,{color:"green",children:"in sync"})}},"getStatusText"),lc=l((n,e)=>{const t=e-6;return n.length<=t?n:n.slice(0,t-3)+"..."},"truncateLogMessage"),uc=l(()=>{const{workspaceKey:n,cwd:e}=Os(),t=Math.min(100,process.stdout.columns||100),[s,i]=D({}),[r,o]=D([]),[a,c]=D(0),[,u]=D({}),d=5,{data:f}=ds("/account"),w=f?.workspaces?.find(O=>O.key===n)?.name,p=w?ac(w):n;pt(()=>{const O=l(()=>{u({})},"handleStatusChanged"),$=l(()=>{i(W.elementCounts)},"handleCounterChanged"),x=l(()=>{const E=W.logs,z=a===0;o(E),z&&c(0)},"handleLogAdded");return i(W.elementCounts),o(W.logs),W.on("statusChanged",O),W.on("counterChanged",$),W.on("logAdded",x),()=>{W.off("statusChanged",O),W.off("counterChanged",$),W.off("logAdded",x)}},[a]),Qe((O,$)=>{if(r.length!==0)if($.upArrow){const x=Math.max(0,r.length-d);c(E=>Math.min(x,E+1))}else $.downArrow?c(x=>Math.max(0,x-1)):(O==="G"||O==="g")&&c(0)});const g=Math.max(0,r.length-d-a),S=r.length-a,b=r.slice(g,S),C=a<r.length-d,T=a>0;return I(A,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[y(A,{marginTop:-1,marginBottom:1,children:I(k,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",cc(W.status)]})}),I(A,{children:[y(A,{width:12,children:y(k,{color:"grey",children:"Local:"})}),y(k,{color:"grey",children:e})]}),I(A,{children:[y(A,{width:12,children:y(k,{color:"grey",children:"Remote:"})}),n?I(k,{color:"grey",children:[p," [o: open in console] [w: change]"]}):I(k,{children:[y(k,{color:"yellow",children:"not selected"})," [w: select]"]})]}),Object.keys(s).length>0&&I(A,{flexDirection:"column",paddingTop:1,children:[y(A,{children:y(A,{width:12,children:y(k,{color:"grey",children:"Elements:"})})}),y(A,{flexDirection:"column",marginLeft:1,children:Object.entries(s).filter(([O,$])=>$>0).map(([O,$])=>I(A,{children:[y(A,{width:20,children:I(k,{children:[O,":"]})}),y(k,{color:"green",children:$})]},O))})]}),r.length>0&&I(A,{flexDirection:"column",paddingTop:1,children:[I(k,{color:"grey",children:["Recent Activity (",g+1,"-",S," of ",r.length,"):",r.length>5&&y(k,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),b.map((O,$)=>{const x=lc(O.message,t);return y(A,{marginLeft:1,children:y(k,{color:ir(O.type),children:x})},O.timestamp+$)}),r.length>5&&I(A,{marginLeft:1,flexDirection:"row",children:[C&&y(k,{color:"grey",children:"\u2191 "}),T&&y(k,{color:"grey",children:"\u2193 "})]})]})]})},"WorkspaceSync"),fc=l(()=>{const{isSetupComplete:n,workspaceKey:e,config:t}=Os(),[s,i]=D(!1),[r,o]=D(!1),[a,c]=D(!1),u=mn();return Qe(d=>{!s&&!r&&!a&&(d==="w"&&i(!0),d==="a"&&c(!0),d==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await Ys(u)}`,m=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Tr(`${m} "${h}"`)}catch(f){console.error("Failed to open workspace:",f)}})(),d==="s"&&o(!0))}),s?y(Cs,{onExit:l(()=>i(!1),"onExit")}):a?y(so,{onExit:l(()=>c(!1),"onExit"),onComplete:l(()=>c(!1),"onComplete")}):r||!n?y(As,{onComplete:l(()=>o(!1),"onComplete")},Date.now()):I(A,{flexDirection:"column",children:[y(A,{flexGrow:1,children:y(oo,{})}),y(uc,{}),y(A,{paddingLeft:2,children:y(k,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),rr=Cr(process.argv.slice(2)),or=rr.cwd?wr(rr.cwd):process.cwd();async function dc(){try{await W.start({cwd:or})}catch(n){N.error(n.toString()),process.exit(1)}}l(dc,"startBackgroundServices");const hc=l(()=>y(yn,{cwd:or,children:y(fc,{})}),"App");function pc(){dc(),sn(y(hc,{}))}l(pc,"runAgent");function mc(n){n.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
143
- `)).action(()=>{sn(ht.createElement(yn,null,ht.createElement(As,{onComplete:l(()=>process.exit(0),"onComplete")})))})}l(mc,"setupInitCommand");async function gc(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return gt.sign(t,e)}l(gc,"generateAdminAccessToken");async function yc(n,e){return(await fn.get(`${n}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(yc,"fetchOpenApiSchema");function ar(n,e=!0){if(!n)return e?F.string():F.string().optional();let t;switch(n.type){case"integer":t=F.coerce.number().int();break;case"number":t=F.coerce.number();break;case"boolean":t=F.coerce.boolean();break;case"string":default:t=F.string();break}return n.format==="uuid"?t=F.string().uuid():n.format==="email"?t=F.string().email():n.format==="date"?t=F.string().regex(/^\d{4}-\d{2}-\d{2}$/):n.format==="date-time"&&(t=F.string().datetime()),n.enum&&(t=F.enum(n.enum)),(n.type==="integer"||n.type==="number")&&(n.minimum!==void 0&&(t=t.min(n.minimum)),n.maximum!==void 0&&(t=t.max(n.maximum))),n.type==="string"&&(n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength))),e?t:t.optional()}l(ar,"convertOpenApiSchemaToZod");function cr(n){const e=n.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(cr,"extractPathParameters");function wc(n,e,t,s,i){const r=n.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,o=n.description||n.summary||`${t.toUpperCase()} ${e}`,a={},c={},u={};if(n.parameters){for(const f of n.parameters)if(f.in==="path")c[f.name]=ar(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const h=f.required===!0;u[f.name]=ar(f.schema,h).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(c).length>0&&(a.params=F.object(c).describe("Path parameters")),Object.keys(u).length>0&&(a.query=F.object(u).describe("Query parameters")),n.requestBody&&n.requestBody.content&&n.requestBody.content["application/json"]&&(a.body=F.any().describe("Request body"));const d=Object.keys(a).length>0?F.object(a):F.object({});return{name:r,description:o,parameters:d,async execute(f){try{const h=cr(e);if(h.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const b=h.filter(C=>!(C in f.params));if(b.length>0)throw new Error(`Missing required path parameters: ${b.join(", ")}`)}let m=`${s}${e}`;if(f.params)for(const[b,C]of Object.entries(f.params)){const T=`{${b}}`;m.includes(T)&&(m=m.replace(T,String(C)))}const w=cr(m);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const p=new URLSearchParams;if(f.query)for(const[b,C]of Object.entries(f.query))C!=null&&p.append(b,String(C));p.toString()&&(m+=`?${p.toString()}`);const g={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(g.data=f.body);const S=await fn.request({url:m,...g});return{content:[{type:"text",text:JSON.stringify(S.data,null,2)}]}}catch(h){return fn.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(wc,"createApiTool");function bc(n,e,t){const s=[];if(!n.paths)return s;for(const[i,r]of Object.entries(n.paths))if(typeof r=="object"&&r!==null){for(const[o,a]of Object.entries(r))if(["get","post","put","delete","patch"].includes(o)&&a&&typeof a=="object"){const c=wc(a,i,o,e,t);s.push(c)}}return s}l(bc,"convertOpenApiToTools");function Sc(n){n.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
144
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=be();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||hn,s=await gc(e.workspaceKey,e.workspaceSecret),i=await yc(t,s),r=bc(i,t,s),o=new qr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
142
+ ${v.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(v.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(){}}async function Za(s,e="full"){const t={};x.info("Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(i=>ls("integration",i));for(const i of Object.keys(H)){const r=H[i];if(r.exportable===!1)continue;const o=[];x.info(`Reading ${r.elements} from remote workspace`);const a=await s[r.elements].findAll();if(o.push(...a.map(c=>ls(i,c))),r.integrationSpecific)for(const c of n){const u=await s[r.elements].findAll({integrationId:c.id});o.push(...u.map(f=>(f.integrationKey=c.key,ls(i,f))))}o.length>0&&e=="full"&&(console.table(o.map(c=>({key:c.key,integrationKey:c.integrationKey,universal:!c.integrationKey})).reduce((c,u)=>(c||(c={}),c[u.key]||(c[u.key]={}),u.universal&&(c[u.key].universal=!0),u.integrationKey&&(c[u.key].integration?c[u.key].integration+=` ${u.integrationKey}`:c[u.key].integration=u.integrationKey),c),{})),console.groupEnd()),t[i]=o}return x.success("Remote workspace data retrieved successfully"),t}l(Za,"getWorkspaceData");function Qa(s){const e={},t={};for(const n of Object.keys(s))if(e[n]=[],t[n]=[],H[n]?.integrationSpecific)for(const r of s[n])r.integrationKey||r.integration||r.integrationId?t[n].push(r):e[n].push(r);else e[n].push(...s[n]);return{universalElements:e,integrationSpecificElements:t}}l(Qa,"splitWorkspaceData");function ls(s,e){return e=No(e),H[s].exportCleanup?H[s].exportCleanup(e):e}l(ls,"cleanUpForExport");function St(s){return Object.keys(s).some(e=>/universal.*Id/g.test(e)||/parentId/g.test(e))}l(St,"hasParent");function X(s,e){console.debug("\x1B[0m",`\x1B[${{Reset:"\x1B[0m",Bright:"\x1B[1m",Dim:"\x1B[2m",Underscore:"\x1B[4m",Blink:"\x1B[5m",Reverse:"\x1B[7m",Hidden:"\x1B[8m",Black:"\x1B[30m",Red:"\x1B[31m",Green:"\x1B[32m",Yellow:"\x1B[33m",Blue:"\x1B[34m",Magenta:"\x1B[35m",Cyan:"\x1B[36m",White:"\x1B[37m",Gray:"\x1B[90m",BgBlack:"\x1B[40m",BgRed:"\x1B[41m",BgGreen:"\x1B[42m",BgYellow:"\x1B[43m",BgBlue:"\x1B[44m",BgMagenta:"\x1B[45m",BgCyan:"\x1B[46m",BgWhite:"\x1B[47m",BgGray:"\x1B[100m"}[e]}`,s,"\x1B[0m")}l(X,"coloredLog");const Wi="connectors",zi="development",us={};async function Xa({integrations:s,allConnectors:e=!1}){const t=po(),n=await _n.getClient(process.cwd()),i=new Set,r={};for(const o of s){const a=o.connectorId,c=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await rc({client:n,connectorId:a});(!!u.workspaceId||e)&&(i.has(a)||(await oc({basePath:t,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(c)||(await ac({client:n,connector:u,connectorVersion:c,basePath:t}),r[a].add(c)))}}}l(Xa,"pullConnectors");async function ec({client:s,workspaceData:e,pushContext:t,workspaceId:n}){const i={};console.debug("[Push] Loading custom connectors");const r=s,o=await r.get(`/connectors?workspaceId=${n}`);console.debug("[Push] Loading public connectors"),e.connector=o;const a=fs(),c=D.existsSync(a)?D.readdirSync(a):[];for(const u of c){console.debug(`[Push] Loading connector from: ${u}`);const f=D.readdirSync(j.join(a,u)),d=await tc(u);if(delete d.baseUri,d.uuid&&e.connector?.find(m=>m.uuid==d.uuid))i[d.id]=e.connector.find(m=>m.uuid==d.uuid).id,X(`Matched ${d.name} uuid: ${d.uuid}`,"Blue");else if(!i[d.id]){console.debug(`Creating connector ${d.name} (${d.key})`);const m=await r.post("connectors",{...d,workspaceId:n});i[d.id]=m.id}const h=f.filter(m=>D.statSync(j.join(a,u,m)).isDirectory());for(const m of h)await ic({client:s,connector:d,version:m,connectorId:i[d.id]})}t.connectorsMapping=i}l(ec,"pushConnectors");function fs(){const s=ot();return j.join(s.membraneDirPath,Wi)}l(fs,"getConnectorsPath");async function tc(s){return fe.load(D.readFileSync(j.join(fs(),s,`${s}.yml`),"utf8"))}l(tc,"readConnector");async function nc(s,e){return console.debug(`Zipping ${s} into ${e}`),new Promise((t,n)=>{const i=D.createWriteStream(e),r=no("zip",{zlib:{level:9}});i.on("close",()=>{X(`Successfully created ${e}`,"Green"),t()}),i.on("end",()=>{console.debug("Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),r.on("error",a=>{n(a)}),r.pipe(i);const o=D.readdirSync(s);for(const a of o){const c=j.join(s,a),u=D.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(nc,"createZipArchive");async function sc(s,e){return console.debug(`Unzipping into ${e}`),new Promise((t,n)=>{const i=io.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=j.join(e,o);D.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=j.join(e,o),u=j.dirname(c);D.mkdirSync(u,{recursive:!0});const f=D.createWriteStream(c);r.pipe(f),f.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{X(`Successfully extracted to ${e}`,"Green"),t()}),i.on("error",r=>{n(r)}),i.write(s),i.end()})}l(sc,"extractZipArchive");async function ic({client:s,connector:e,version:t,connectorId:n}){const i=j.join(fs(),tn(e),Gi(t)),r=j.join(i,"src"),o=j.join(i,"src.zip");if(D.existsSync(r)&&(console.debug(`Archiving source code for ${e.name} version ${t}`),await nc(r,o)),!D.existsSync(o)){F.warning(`No source code found for ${e.name} version ${t}`);return}try{const a=new so;if(a.append("file",D.createReadStream(o),"file.zip"),console.debug(`Pushing connector version ${t} for ${e.name}`),t==zi)console.debug(`Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,a,{headers:{...a.getHeaders()}});else{if(a.append("version",t),a.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(u=>u.version==t)){X(`Version ${t} already published`,"Blue");return}console.debug(`Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,a,{headers:{...a.getHeaders()}})}F.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch{F.error(`Error pushing connector version ${t} for ${e.name}`)}finally{D.existsSync(o)&&D.unlinkSync(o)}}l(ic,"pushConnectorVersion");async function rc({client:s,connectorId:e}){if(us[e])return us[e];const t=await s.get(`connectors/${e}`);return us[e]=t,t}l(rc,"getConnector");async function oc({basePath:s,connector:e}){const t=tn(e),n=j.join(s,Wi,t);D.mkdirSync(n,{recursive:!0});const i=j.join(n,`${tn(e)}.yml`);D.writeFileSync(i,fe.dump(e)),F.info(`Pulled connector ${e.name}`)}l(oc,"pullConnector");async function ac({client:s,connector:e,connectorVersion:t,basePath:n}){const i=tn(e),r=Gi(t),o=j.join(n,"connectors",i,r),a=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});D.mkdirSync(o,{recursive:!0});const c=j.join(o,"src.zip");D.writeFileSync(c,a);const u=j.join(o,"src");D.existsSync(u)&&await sc(a,u),F.info(`[Pull] Connector Version: ${e.name} (${r})`)}l(ac,"pullConnectorVersion");function tn(s){return s.key}l(tn,"getConnectorDirName");function Gi(s){return s??zi}l(Gi,"getConnectorVersionDirName");class cc extends At{static{l(this,"WorkspaceService")}localManager;remoteManager;fileWatcher=void 0;status=W.SYNCING;stats={};unresolvedChanges=[];constructor(){super(),this.remoteManager=new Ko,this.localManager=new Do,F.on(Pn.NewLog,()=>this.emit(ce.LogAdded)),ut.on(Ot.Pull,e=>this.pull(e)),ut.on(Ot.Exit,()=>this.exit())}get currentStatus(){return this.status}get currentStats(){return{...this.stats}}get currentUnresolvedChanges(){return[...this.unresolvedChanges]}get logs(){return F.logs}async start({cwd:e}){this.fileWatcher=new Ga({cwd:e}),this.fileWatcher.on(se.Added,t=>this.handleFileChange(t,se.Added)),this.fileWatcher.on(se.Changed,t=>this.handleFileChange(t,se.Changed)),this.fileWatcher.on(se.Deleted,t=>this.handleFileChange(t,se.Deleted)),await this.pull()}async pull({allConnectors:e=!1,overwriteFromRemote:t=!1}={}){this.setStatus(W.SYNCING);try{if(await this.remoteManager.pull(),await this.localManager.read(),this.findChanges(),this.hasConflicts()&&!t){F.error("Out of sync with remote, use --force to overwrite changes from remote");return}this.isOutOfSync()&&await this.resolveChanges(),await Xa({integrations:this.remoteManager.elements.getElementsByType(P.Integration).map(n=>n.data),allConnectors:e}),this.updateStats(),this.setStatus(W.READY)}catch(n){throw this.setStatus(W.ERROR),n}}async exit(){F.info("Sync aborted by user"),process.exit(0)}async resolveChanges(){if(!this.isOutOfSync())return;F.warning("Resolving changes..."),this.setStatus(W.SYNCING);const e=this.unresolvedChanges.map(t=>{switch(t.type){case Y.DELETE:return F.info(`Removing ${t.element.key} (${t.element.type})`),this.localManager.deleteElement(t.element);case Y.CREATE:return F.info(`Adding ${t.element.key} (${t.element.type})`),this.localManager.writeElement(t.element);case Y.UPDATE:return F.info(`Updating ${t.element.key} (${t.element.type})`),this.localManager.writeElement(t.element)}});await Promise.all(e),await this.localManager.read(),this.unresolvedChanges=[],this.updateStats(),this.setStatus(W.READY),F.success("Changes resolved")}setStatus(e){this.status!==e&&(this.status=e,this.emit(ce.StatusChanged))}updateStats(){const e={};for(const t of this.localManager.elements.getAll())e[t.type]=(e[t.type]||0)+1;this.stats=e,this.emit(ce.StatsChanged)}async handleFileChange(e,t){if(this.status===W.READY)try{const n=Q.fromPathAndData(e.filePath,e.data);if(!n||!this.localManager.elements.get(n.id))return;switch(F.info(`${t}: ${n.key} (${n.type})`),t){case se.Added:case se.Changed:{await this.remoteManager.pushElement(n),this.localManager.elements.put(n);break}case se.Deleted:break}}catch{F.error(`Failed ${t} for ${e.relativePath}`)}}findChanges(){const e=this.localManager.elements,t=this.remoteManager.elements,n=[],i=e.getTypes(),r=t.getTypes(),o=new Set([...i,...r]);for(const u of o){const f=e.getElementIdsByType(u),d=t.getElementIdsByType(u);if(!f||f.size===0){if(d)for(const h of d){const m=t.get(h);n.push({type:Y.CREATE,element:m})}continue}if(!d||d.size===0){for(const h of f){const m=e.get(h);n.push({type:Y.DELETE,element:m})}continue}for(const h of d){const m=t.get(h);f.has(h)?(e.get(h).isEqual(m)||n.push({type:Y.UPDATE,element:m}),f.delete(h)):n.push({type:Y.CREATE,element:m})}for(const h of f){const m=e.get(h);n.push({type:Y.DELETE,element:m})}}if(this.unresolvedChanges=n,!this.hasConflicts())return;const a=this.unresolvedChanges.filter(u=>u.type!==Y.CREATE);this.emit(ce.ChangesFound,this.unresolvedChanges),this.setStatus(W.CONFLICTS);const c=l(u=>{switch(u){case Y.UPDATE:return"Element updated in remote";case Y.DELETE:return"Element does not exist in remote";default:return""}},"getConflictTypeLabel");F.warning(`Found ${a.length} conflicts with remote:`);for(const u of a)F.info(`${c(u.type)}: ${u.element.id} (${u.element.relativePath}) `)}hasConflicts(){return this.unresolvedChanges.some(e=>e.type!==Y.CREATE)}isOutOfSync(){return this.unresolvedChanges.length>0}}const ee=new cc,Hi=yn(null);function Yi({children:s}){const{config:e,isLoading:t}=at(),{data:n}=Es("/account"),[i,r]=R(ee.currentStatus),[o,a]=R(ee.currentStats),[c,u]=R(ee.logs),[f,d]=R(ee.currentUnresolvedChanges),m=n?.workspaces?.find(k=>k.key===e?.workspaceKey)||null,w=e?.workspaceKey&&e?.workspaceSecret;function p(){if(w)try{ut.pull({overwriteFromRemote:!0})}catch(k){console.error("Failed to resolve conflicts:",k)}}l(p,"resolveConflicts");function y(){if(w)try{ut.exit()}catch(k){console.error("Failed to exit:",k)}}l(y,"abort");function C({allConnectors:k=!1,overwriteFromRemote:O=!1}){if(w)try{ut.pull({allConnectors:k,overwriteFromRemote:O})}catch(T){console.error("Failed to pull:",T)}}return l(C,"pull"),me(()=>{const k=l(()=>r(ee.currentStatus),"handleStatusChanged"),O=l(()=>a(ee.currentStats),"handleStatsChanged"),T=l(()=>u(ee.logs),"handleLogAdded"),I=l($=>d($),"handleConflictsFound");return ee.on(ce.StatusChanged,k),ee.on(ce.StatsChanged,O),ee.on(ce.LogAdded,T),ee.on(ce.ChangesFound,I),()=>{ee.off(ce.StatusChanged,k),ee.off(ce.StatsChanged,O),ee.off(ce.LogAdded,T),ee.off(ce.ChangesFound,I)}},[]),t?null:w?g(Hi.Provider,{value:{status:i,stats:o,logs:c,currentWorkspace:m,unresolvedChanges:f,resolveConflicts:p,abort:y,pull:C},children:s}):g(b,{children:g(S,{children:"No workspace selected. Please run `membrane init` to select a workspace."})})}l(Yi,"WorkspaceServiceProvider");function Ge(){const s=wn(Hi);if(!s)throw new Error("useWorkspaceService must be used within WorkspaceServiceProvider");return s}l(Ge,"useWorkspaceService");function lc(){const{stats:s}=Ge(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(b,{flexDirection:"column",paddingTop:1,children:[g(b,{children:g(b,{width:12,children:g(S,{color:"grey",children:"Elements:"})})}),g(b,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(b,{children:[g(b,{width:20,children:E(S,{children:[t,":"]})}),g(S,{color:"green",children:n})]},t))})]})}l(lc,"ElementStats");const Zi=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Qi(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(Qi,"truncateText");const ds=5,uc=6;function fc(){const{logs:s}=Ge(),[e,t]=R(0),n=Math.min(100,process.stdout.columns||100),i=ds,r=Math.max(0,s.length-i-e),o=s.length-e,a=s.slice(r,o),c=n-uc,u=e<s.length-i,f=e>0;return Pe((d,h)=>{if(s.length!==0)if(h.upArrow){const m=Math.max(0,s.length-i);t(w=>Math.min(m,w+1))}else h.downArrow?t(m=>Math.max(0,m-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>ds&&g(S,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>g(b,{marginLeft:1,children:g(S,{color:Zi(d.type),children:Qi(d.message,c)})},d.timestamp+h)),s.length>ds&&E(b,{marginLeft:1,flexDirection:"row",children:[u&&g(S,{color:"grey",children:"\u2191 "}),f&&g(S,{color:"grey",children:"\u2193 "})]})]})}l(fc,"Logs");const nn=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}],Xi={[Y.UPDATE]:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},[Y.DELETE]:{label:"Elements not existing in remote",description:"(to be deleted locally)"}};function dc(){const{unresolvedChanges:s,status:e,resolveConflicts:t,abort:n}=Ge(),[i,r]=R(0),[o,a]=R(!1),c=Jr(()=>{const u={[Y.UPDATE]:[],[Y.DELETE]:[]};return s.forEach(f=>{f.type!==Y.CREATE&&u[f.type].push(f)}),u},[s]);return Pe((u,f)=>{o||(f.upArrow?r(d=>d>0?d-1:nn.length-1):f.downArrow?r(d=>d<nn.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(a(!0),nn[i].value==="sync"?t():n()))}),me(()=>{e!==W.CONFLICTS&&o&&a(!1)},[e,o]),E(b,{flexDirection:"column",paddingTop:1,children:[g(b,{children:g(b,{flexDirection:"row",gap:2,children:g(S,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(b,{children:g(S,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(b,{flexDirection:"column",marginTop:1,marginLeft:2,children:Object.entries(c).map(([u,f])=>f.length===0?null:E(b,{flexDirection:"column",marginBottom:1,children:[E(b,{flexDirection:"row",gap:1,children:[E(S,{color:"yellow",bold:!0,children:[Xi[u].label," (",f.length,")"]}),g(S,{color:"white",children:Xi[u].description})]}),f.map(d=>g(b,{marginLeft:2,children:E(S,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id))]},u))}),E(b,{marginTop:2,flexDirection:"row",gap:1,children:[g(S,{color:"white",bold:!0,children:"What would you like to do?"}),g(S,{color:"grey",children:"[up/down, enter]"})]}),g(b,{children:o?E(b,{flexDirection:"row",gap:1,children:[g(Ct,{type:"dots"}),g(S,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(b,{flexDirection:"column",children:nn.map((u,f)=>g(b,{flexDirection:"column",children:E(b,{flexDirection:"row",gap:1,children:[g(S,{color:i===f?"cyan":"grey",children:i===f?"\u25B6":" "}),g(S,{color:i===f?"cyan":"grey",bold:i===f,children:u.label})]})},u.value))})})]})}l(dc,"ResolveChangesUI");function hc(){const{config:s}=at(),{status:e,logs:t,currentWorkspace:n,pull:i}=Ge(),r=n?.name,o=r?Qi(r,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return me(()=>{i({allConnectors:!1,overwriteFromRemote:!1})},[]),E(b,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(b,{marginTop:-1,marginBottom:1,children:E(b,{flexDirection:"row",gap:1,children:[g(S,{bold:!0,children:"\u{1F504} Workspace"}),E(S,{color:mc(e),children:[" [",pc(e),"] "]})]})}),E(b,{children:[g(b,{width:12,children:g(S,{color:"grey",children:"Local:"})}),g(S,{color:"grey",children:process.cwd()})]}),E(b,{children:[g(b,{width:12,children:g(S,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(S,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(S,{children:[g(S,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===W.CONFLICTS?g(dc,{}):E(Dr,{children:[g(lc,{}),t.length>0&&g(fc,{})]})]})}l(hc,"Workspace");function pc(s){switch(s){case W.SYNCING:return"syncing";case W.CONFLICTS:return"conflicts";case W.READY:return"synced";case W.ERROR:return"error"}}l(pc,"getStatusDisplay");function mc(s){switch(s){case W.SYNCING:return"yellow";case W.CONFLICTS:return"yellow";case W.READY:return"green";case W.ERROR:return"red"}}l(mc,"getStatusColor");const gc=l(()=>{const{isSetupComplete:s}=Ks(),{config:e}=at();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e}},"useStatus");function yc(){const s=Ls(),{isSetupComplete:e,workspaceKey:t,config:n}=gc(),[i,r]=R(!1),[o,a]=R(!1),[c,u]=R(!1),f=vs(!0);return Pe(d=>{i||o||c||(d==="w"&&r(!0),d==="a"&&u(!0),d==="o"&&t&&n?.workspaceSecret&&(async()=>{try{const m=`https://console.integration.app/w/${await Fs(s)}`,w=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Wr(`${w} "${m}"`)}catch(h){console.error("Failed to open workspace:",h)}})(),d==="s"&&a(!0))}),me(()=>(f.current=!0,()=>{f.current=!1}),[]),i?g(js,{onExit:l(()=>r(!1),"onExit")}):c?g(Co,{onExit:l(()=>u(!1),"onExit"),onComplete:l(()=>u(!1),"onComplete")}):o||!e?g(Rs,{onComplete:l(()=>a(!1),"onComplete")},Date.now()):E(b,{flexDirection:"column",children:[g(b,{flexGrow:1,children:g(To,{})}),g(Yi,{children:g(hc,{})}),g(b,{paddingLeft:2,children:g(S,{color:"grey",children:"[s: (re-)setup]"})})]})}l(yc,"Main");const er=Br(process.argv.slice(2)),wc=er.cwd?jr(er.cwd):process.cwd(),bc=l(()=>g(On,{cwd:wc,children:g(yc,{})}),"App");function Sc(){gn(g(bc,{}))}l(Sc,"runAgent");function kc(s){s.command("init").description("Run interactive setup for Membrane project").addHelpText("after",["","Examples:"," membrane init # Run interactive setup",""].join(`
143
+ `)).action(()=>{gn(kt.createElement(On,null,kt.createElement(Rs,{onComplete:l(()=>process.exit(0),"onComplete")})))})}l(kc,"setupInitCommand");async function tr(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return Et.sign(t,e)}l(tr,"generateAdminAccessToken");async function Cc(s,e){return(await En.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(Cc,"fetchOpenApiSchema");function nr(s,e=!0){if(!s)return e?U.string():U.string().optional();let t;switch(s.type){case"integer":t=U.coerce.number().int();break;case"number":t=U.coerce.number();break;case"boolean":t=U.coerce.boolean();break;case"string":default:t=U.string();break}return s.format==="uuid"?t=U.string().uuid():s.format==="email"?t=U.string().email():s.format==="date"?t=U.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(t=U.string().datetime()),s.enum&&(t=U.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(t=t.min(s.minimum)),s.maximum!==void 0&&(t=t.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(t=t.min(s.minLength)),s.maxLength!==void 0&&(t=t.max(s.maxLength))),e?t:t.optional()}l(nr,"convertOpenApiSchemaToZod");function sr(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(sr,"extractPathParameters");function vc(s,e,t,n,i,r){const o=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,a=s.description||s.summary||`${t.toUpperCase()} ${e}`,c={},u={},f={};if(s.parameters){for(const h of s.parameters)if(h.in==="path")u[h.name]=nr(h.schema,!0).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const m=h.required===!0;f[h.name]=nr(h.schema,m).describe(h.description||`Query parameter: ${h.name}`)}}Object.keys(u).length>0&&(c.params=U.object(u).describe("Path parameters")),Object.keys(f).length>0&&(c.query=U.object(f).describe("Query parameters")),s.requestBody&&s.requestBody.content&&s.requestBody.content["application/json"]&&(c.body=U.any().describe("Request body"));const d=Object.keys(c).length>0?U.object(c):U.object({});return{name:o,description:a,parameters:d,async execute(h){try{const m=sr(e);if(m.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${m.join(", ")}`);const T=m.filter(I=>!(I in h.params));if(T.length>0)throw new Error(`Missing required path parameters: ${T.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[T,I]of Object.entries(h.params)){const $=`{${T}}`;w.includes($)&&(w=w.replace($,String(I)))}const p=sr(w);if(p.length>0)throw new Error(`Unresolved path parameters: ${p.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[T,I]of Object.entries(h.query))I!=null&&y.append(T,String(I));y.toString()&&(w+=`?${y.toString()}`);const C=await tr(i,r),k={method:t.toUpperCase(),headers:{Authorization:`Bearer ${C}`,"Content-Type":"application/json"}};h.body&&t.toLowerCase()!=="get"&&(k.data=h.body);const O=await En.request({url:w,...k});return{content:[{type:"text",text:JSON.stringify(O.data,null,2)}]}}catch(m){return En.isAxiosError(m)?{content:[{type:"text",text:`Error: ${m.response?.data?`HTTP ${m.response.status}: ${m.response.statusText} - ${JSON.stringify(m.response.data)}`:`HTTP ${m.response?.status||"unknown"}: ${m.message}`}`}],isError:!0}:m instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${m.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(vc,"createApiTool");function Ec(s,e,t,n){const i=[];if(!s.paths)return i;for(const[r,o]of Object.entries(s.paths))if(typeof o=="object"&&o!==null){for(const[a,c]of Object.entries(o))if(["get","post","put","delete","patch"].includes(a)&&c&&typeof c=="object"){const u=vc(c,r,a,e,t,n);i.push(u)}}return i}l(Ec,"convertOpenApiToTools");function Tc(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
144
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Te();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||An,n=await tr(e.workspaceKey,e.workspaceSecret),i=await Cc(t,n),r=Ec(i,t,e.workspaceKey,e.workspaceSecret),o=new ao({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
145
145
  Use it for anything related to Membrane or integrations.
146
- `,version:"1.0.0"});for(const u of r){const d=u.execute;u.execute=async f=>(io(process.pid,process.cwd()),d(f)),o.addTool(u)}kn({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(()=>{kn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),tt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await c(),process.exit(0)}),process.on("SIGTERM",async()=>{await c(),process.exit(0)}),process.on("exit",()=>{tt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await c(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await c(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}l(Sc,"setupMcpCommand");function kc(n){n.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
147
- `)).action(async()=>{try{N.header("Opening Workspace in Browser"),N.info("Loading configuration...");const e=be();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");N.info("Retrieving workspace ID...");const s=`https://console.integration.app/w/${await Ys(process.cwd())}`;N.info(`Opening ${s}...`);const{default:i}=await import("open");await i(s),N.success("Browser opened successfully")}catch(e){e instanceof Error&&(N.error(e.message),process.exit(1)),N.error("An unknown error occurred"),process.exit(1)}})}l(kc,"setupOpenCommand");const Cc=l(({allConnectors:n=!1,onComplete:e})=>{const[t,s]=D([]),[i,r]=D({}),[o,a]=D(!1);return pt(()=>{const c=l(()=>{const d=W.status;(d==="finished"||d==="error")&&(r(W.elementCounts),a(!0),e&&setTimeout(e,100))},"handleStatusChanged"),u=l(()=>{s(W.logs)},"handleLogAdded");return s(W.logs),r(W.elementCounts),W.on("statusChanged",c),W.on("logAdded",u),W.pullWorkspace({allConnectors:n}),()=>{W.off("statusChanged",c),W.off("logAdded",u)}},[n,e]),I(A,{flexDirection:"column",children:[t.slice().map((c,u)=>y(k,{color:ir(c.type),children:c.message},c.timestamp+u)),o&&Object.keys(i).length>0&&I(A,{flexDirection:"column",marginTop:1,children:[y(k,{bold:!0,children:"Workspace Elements Summary:"}),Object.entries(i).filter(([c,u])=>u>0).map(([c,u])=>I(A,{children:[y(A,{width:20,children:I(k,{children:[c,":"]})}),y(k,{color:"green",children:u})]},c))]})]})},"PullStandalone");function vc(n){n.command("pull").description("Pull workspace data from specified workspace").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 --all-connectors # Pull with all connectors",""].join(`
148
- `)).action(e=>{sn(ht.createElement(yn,null,ht.createElement(Cc,{allConnectors:e.allConnectors,onComplete:l(()=>process.exit(0),"onComplete")})))})}l(vc,"setupPullCommand");function en(n){return ee[n].apiPath}l(en,"getWorkspaceElementTypePath");function lr(n,e){for(const t of Object.keys(e))n[t]=[...n[t]||[],...e[t]];return n}l(lr,"mergeWorkspaceData");const ur=[M.Integration,M.Scenario,M.Action,M.Flow,M.AppDataSchema,M.AppEventType,M.DataLinkTable,M.DataSource,M.FieldMapping];async function Ac(){const n={};for(const e of ur){N.info(`Loading ${ee[e].namePlural}`);const t=[],i=et().membraneDirPath,r=[K.join(i,en(e))],o=K.join(i,je.toCamelCase(en(e)));r.includes(o)||r.push(o);for(const a of r)P.existsSync(a)&&t.push(...await fr(a));n[e]=[...n[e]||[],...t]}return n}l(Ac,"readTopLevelElements");async function Oc(){const n={},t=et().membraneDirPath,s=K.join(t,en(M.Integration)),i=P.readdirSync(s);for(const r of i)if(P.statSync(K.join(s,r)).isDirectory()){const o=await dr(s,r);for(const a of ur){const c=K.join(s,r,en(a)),u=await fr(c);u.forEach(d=>{d.integrationKey=o?.key}),n[a]=[...n[a]||[],...u]}}return n}l(Oc,"readIntegrationLevelElements");async function fr(n){const e=[];if(!P.existsSync(n))return e;N.info(`Reading ${n}`);const t=P.readdirSync(n);for(const s of t){const i=await dr(n,s);i&&(e.push(i),N.success(`Loaded ${s}`))}return e}l(fr,"readWorkspaceElementsFromDir");async function dr(n,e){const t=K.join(n,e),i=P.statSync(t).isDirectory()?K.join(t,`${e}.yaml`):t;if(P.existsSync(i))return oe.load(P.readFileSync(i,"utf8"))}l(dr,"readWorkspaceElementFromDirItem");async function Ec({client:n}){const t=(await n.get("org-workspace-id")).id,s=await Ga(n,"minified"),i={};N.info("Loading local workspace data");const r=await Ac();lr(i,r);const o=await Oc();lr(i,o);const{universalElements:a,integrationSpecificElements:c}=Ya(i),u={connectorsMapping:{}};return await Tc({sourceData:i,workspaceData:s,pushContext:u,iApp:n,workspaceId:t}),s.integration=await n.integrations.findAll(),Z("Syncing Universal Elements","BgBlue"),N.group("Syncing Universal Elements"),await hr(a,s,n),N.groupEnd(),Z("Syncing Integration Specific Elements","BgBlue"),N.group("Syncing Integration Specific Elements"),await hr(c,s,n),N.groupEnd(),N.success("Data written successfully."),u}l(Ec,"pushWorkspace");async function Tc({sourceData:n,workspaceData:e,pushContext:t,iApp:s,workspaceId:i}){Z("Matching imported integrations and connectors with existing ones","BgBlue"),await Qa({client:s,workspaceData:e,pushContext:t,workspaceId:i});const r=[];for(const o of n.integration){const a=e.integration.find(u=>u.key==o.key),c={connectorId:o.connectorId,connectorVersion:o.connectorVersion,name:o.name,key:o.key};t.connectorsMapping[o.connectorId]&&(c.connectorId=t.connectorsMapping[o.connectorId]),a?(console.debug(`[Push] Updating integration ${o.key}`),await s.integration(a.id).patch(c)):(console.debug(`[Push] Creating integration ${o.key}`),await s.integrations.create(c)),Z(`Imported integration ${o.name} (${o.key})`,"Green")}if(r.length>0)throw N.table(r.map(o=>({key:o.key,name:o.name}))),Z("Integration missmatch errors. Make sure you have those applications in your destination workspace","BgRed"),new Error("Integration missmatch errors")}l(Tc,"syncIntegrations");async function hr(n,e,t){for(const s of Object.keys(n))if(H[s]?.exportable!==!1)for(const r of n[s]){delete r.integrationId;const o=$c(r,s,e),a=je.toCamelCase(ee[s].name),c=je.toCamelCase(ee[s].namePlural);if(o)if(!dt(r)||pr(r)&&dt(r))await t[a](o.id).put(r),Z(`Updated ${r.integrationKey||"universal"} ${H[s].element} ${r.key}`,"Cyan");else if(dt(r)){try{await t[a](o.id).reset()}catch(u){throw console.debug(o,r),u}Z(`Customization reset ${r.integrationKey||"universal"} ${H[s].element} ${r.key}`,"Magenta")}else Z(`Corrupted. Migrate Manually ${r.integrationKey||"universal"} ${H[s].element} ${r.key}`,"Red");else if(dt(r)){try{await t[a]({key:r.key}).apply([r.integrationKey])}catch{try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch{await t[c].create({...r,integrationId:e.integration.find(f=>f.key==r.integrationKey).id})}}if(pr(r)){try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch(u){throw console.debug(o,r),u}Z(`Applied & Customized ${r.integrationKey||"universal"} ${H[s].element} ${r.key}`,"Green")}else Z(`Applied universal ${H[s].element} ${r.key} to ${r.integrationKey} `,"Green")}else{try{r.integrationKey&&(delete r.integration,r.integrationId=e.integration.find(u=>u.key==r.integrationKey).id),await t[c].create(r)}catch(u){throw console.debug(`Error creating element ${s}`,dt(r),r.integrationKey,r),u}Z(`Created ${r.integrationKey||"universal"} ${H[s].element} ${r.key}`,"Green")}}}l(hr,"syncElements");function pr(n){return n.integrationKey&&(n.customized||n.isCustomized)}l(pr,"elementIsCustomized");function $c(n,e,t){const s=t[e]?.filter(i=>i.key==n.key&&i.integrationKey==n.integrationKey&&!i.archivedAt);if(s.length>1)throw new Error(`More than one ${n.integrationKey||"universal"} ${e} with key ${n.key} found in the workspace`);if(s.length==1)return s[0]}l($c,"matchElement");async function Ic(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return gt.sign(t,e)}l(Ic,"generateAccessToken");function Nc(n){n.command("push").description("Push workspace data to specified workspace").addHelpText("after",["","Examples:"," membrane push # Push to default workspace",""].join(`
149
- `)).action(async()=>{try{N.header("Pushing Workspace Data"),N.info("Loading configuration...");const e=be();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");N.info("Preparing push configuration...");const t=new an({token:await Ic(e.workspaceKey,e.workspaceSecret),apiUri:e.apiUri});N.info("Pushing to remote workspace..."),await Ec({client:t}),N.success("Push to remote workspace completed successfully")}catch(e){e instanceof Error&&(N.error(e.message),process.exit(1)),N.error("An unknown error occurred"),process.exit(1)}})}l(Nc,"setupPushCommand");class _c{static{l(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=et(),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 Lc="claude-sonnet-4-20250514";class as{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:s,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=s,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:s}){const i=be();if(!i)throw new Error("No membrane.config.yml found. Please 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 an({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new Ur({apiKey:i.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const d=await o.messages.create({model:Lc,max_tokens:u,messages:[{role:"user",content:c}]});return d.content[0].type==="text"?d.content[0].text:""},"complete")};return new as({client:r,options:s,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const s of e)await s.run(),dn(t,s.getResult());this.writeResults(t)}async readYaml(e){const t=K.join(this.testsDir,this.testBasePath,this.connectionId,e);if(P.existsSync(t))return oe.load(P.readFileSync(t,"utf8"))}async writeYaml(e,t){const s=K.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync(K.dirname(s),{recursive:!0}),P.writeFileSync(s,oe.dump(t,{noRefs:!0}))}writeResults(e){const t=K.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const s=K.join(t,"test-results.yaml");P.writeFileSync(s,oe.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${s}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",s={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return gt.sign(s,e.workspaceSecret,i)}}Vr.interpolate=/{{([\s\S]+?)}}/g;function ss(n,e){if(typeof n=="string"){const t=Jr(n),s={state:e,random:{number:l(()=>Xe.number.int(),"number"),alphaNumeric:l(r=>Xe.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:l(()=>Xe.company.name(),"name"),catchPhrase:l(()=>Xe.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>Xe.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(s);return n.includes("{{")&&n.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${n}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(n)?n.map(t=>ss(t,e)):typeof n=="object"&&n!==null?Object.fromEntries(Object.entries(n).map(([t,s])=>[t,ss(s,e)])):n}l(ss,"processNode");function xc(n,e){return ss(n,e)}l(xc,"handleTemplate");class Pc{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${v.bold.cyan("[start]")} ${v.yellow(e.path)}`);let t=!1,s=!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(`${v.bold.yellow("[initialized]")} ${v.yellow(e.path)}`)),o=xc(r,this.environment.state),await e.run(o),console.debug(`${v.bold.green("[success]")} ${v.yellow(e.path)}`),t=!0,i=e.getResult(),cn(this.result,e.path,i)}catch(c){if(console.error(`${v.bold.red("[error]")} ${v.yellow(e.path)}: ${c}`),this.environment.options.fix&&!s){s=!0;try{await e.fix(c);continue}catch(u){console.error(`${v.bold.red("[fix fail]")} ${v.yellow(e.path)}: ${u}`)}}cn(this.result,e.path,{error:ae(c)}),t=!0,i={error:ae(c)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),dn(this.result,e.getResult())}}class we{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const s=await this.fixTestCase({config:t,error:e});console.debug(v.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),s)}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,s){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:s}))}catch(i){this.assertions.push({message:t,result:!1,details:ae(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function is(n,e){const t={};for(const s in e){if(!(s in n)){t[s]=e[s];continue}const i=n[s],r=e[s];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!rs(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));o.length>0&&(t[s]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=is(i,r);o!==null&&(t[s]=o)}else t[s]=r;continue}rs(i,r)||(t[s]=r)}return Object.keys(t).length===0?null:t}l(is,"getNotMatchingSubFields");function rs(n,e){if(n==e||n?.toString?.()===e?.toString?.())return!0;const t=new Date(n),s=new Date(e);return!isNaN(t.getTime())&&!isNaN(s.getTime())?t.getTime()===s.getTime():!1}l(rs,"softCompare");class jc extends we{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=s}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 s=ln(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=hs(s),a=mt(e.input.fields,o,{skipUnknownFields:!0}),c=mt(r.record.fields,o),u=is(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const i=Pr(s);if(i.length>0){const r={};i.forEach(a=>{const c=jr(e.input.fields,a);typeof c<"u"&&cn(r,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=ln(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 s=ae(t),i=ln(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
+ `,version:"1.0.0"});for(const u of r){const f=u.execute;u.execute=async d=>(vo(process.pid,process.cwd()),f(d)),o.addTool(u)}xn({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(()=>{xn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),ct(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await c(),process.exit(0)}),process.on("SIGTERM",async()=>{await c(),process.exit(0)}),process.on("exit",()=>{ct(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await c(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await c(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}l(Tc,"setupMcpCommand");function Ac(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{x.header("Opening Workspace in Browser"),x.info("Loading configuration...");const e=Te();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");x.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Fs(process.cwd())}`;x.info(`Opening ${n}...`);const{default:i}=await import("open");await i(n),x.success("Browser opened successfully")}catch(e){e instanceof Error&&(x.error(e.message),process.exit(1)),x.error("An unknown error occurred"),process.exit(1)}})}l(Ac,"setupOpenCommand");function Oc({allConnectors:s=!1,overwriteFromRemote:e=!1,onComplete:t}){return g(Yi,{children:g(Ic,{allConnectors:s,overwriteFromRemote:e,onComplete:t})})}l(Oc,"PullWrapper");function Ic({allConnectors:s=!1,overwriteFromRemote:e=!1,onComplete:t}){const n=vs(!0),{pull:i}=Ge(),{logs:r,stats:o,status:a}=Ge(),[c,u]=R(!1);return me(()=>(n.current=!0,()=>{n.current=!1}),[]),me(()=>{let f;return(a===W.READY||a===W.ERROR)&&(u(!0),t&&(f=setTimeout(()=>{n.current&&t&&t()},100))),()=>{f&&clearTimeout(f)}},[a,t]),me(()=>{i({allConnectors:s,overwriteFromRemote:e})},[]),E(b,{flexDirection:"column",children:[r.slice().map((f,d)=>g(S,{color:Zi(f.type),children:f.message},f.timestamp+d)),c&&Object.keys(o).length>0&&E(b,{flexDirection:"column",marginTop:1,children:[g(S,{bold:!0,children:"Workspace Elements Summary:"}),Object.entries(o).filter(([f,d])=>d>0).map(([f,d])=>E(b,{children:[g(b,{width:20,children:E(S,{children:[f,":"]})}),g(S,{color:"green",children:d})]},f))]})]})}l(Ic,"Pull");function $c(s){s.command("pull").description("Pull workspace data from specified workspace").option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --all-connectors # Pull with all connectors"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
148
+ `)).action(e=>{gn(kt.createElement(On,null,kt.createElement(Oc,{allConnectors:e.allConnectors,overwriteFromRemote:e.force,onComplete:l(()=>process.exit(0),"onComplete")})))})}l($c,"setupPullCommand");var _={},sn={},ir;function rr(){if(ir)return sn;ir=1,Object.defineProperty(sn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toCamelCase"),sn.default=s,sn}l(rr,"requireJsCamelcase");var rn={},or;function ar(){if(or)return rn;or=1,Object.defineProperty(rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(s,"toSnakeCase"),rn.default=s,rn}l(ar,"requireJsSnakecase");var on={},cr;function lr(){if(cr)return on;cr=1,Object.defineProperty(on,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,i){return i.toUpperCase()}):""}return l(s,"toPascalCase"),on.default=s,on}l(lr,"requireJsPascalcase");var an={},ur;function Nc(){if(ur)return an;ur=1,Object.defineProperty(an,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(s,"toDotCase"),an.default=s,an}l(Nc,"requireJsDotcase");var cn={},fr;function xc(){if(fr)return cn;fr=1,Object.defineProperty(cn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(s,"toPathCase"),cn.default=s,cn}l(xc,"requireJsPathcase");var ln={},dr;function Lc(){if(dr)return ln;dr=1,Object.defineProperty(ln,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(s,"toTextCase"),ln.default=s,ln}l(Lc,"requireJsTextcase");var un={},hr;function Pc(){if(hr)return un;hr=1,Object.defineProperty(un,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(s,"toSentenceCase"),un.default=s,un}l(Pc,"requireJsSentencecase");var fn={},pr;function _c(){if(pr)return fn;pr=1,Object.defineProperty(fn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,i,r){return n+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(s,"toHeaderCase"),fn.default=s,fn}l(_c,"requireJsHeadercase");var dn={},mr;function gr(){if(mr)return dn;mr=1,Object.defineProperty(dn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,i){return n+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(s,"toKebabCase"),dn.default=s,dn}l(gr,"requireJsKebabcase");var He={},hs={},yr;function Ye(){return yr||(yr=1,function(s){Object.defineProperty(s,"__esModule",{value:!0}),s.belongToTypes=s.isValidObject=s.isArrayObject=s.validateOptions=s.DefaultOption=void 0,s.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},s.validateOptions=function(e){return e===void 0&&(e=s.DefaultOption),e.recursive==null?e=s.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},s.isArrayObject=function(e){return e!=null&&Array.isArray(e)},s.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},s.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}}(hs)),hs}l(Ye,"requireUtils");var wr;function Dc(){if(wr)return He;wr=1;var s=He&&He.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(He,"__esModule",{value:!0});var e=Ye();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"lowerKeys"),He.default=t,He}l(Dc,"requireLowercaseKeysObject");var Ze={},br;function jc(){if(br)return Ze;br=1;var s=Ze&&Ze.__spreadArrays||function(){for(var n=0,i=0,r=arguments.length;i<r;i++)n+=arguments[i].length;for(var o=Array(n),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,f=c.length;u<f;u++,a++)o[a]=c[u];return o};Object.defineProperty(Ze,"__esModule",{value:!0});var e=Ye();function t(n,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(n))return null;i=e.validateOptions(i);var r={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=t(u,i));else if(e.isArrayObject(u)){var d=t({key:u},i);f=d.key}return f}))),r[c]=a}),r}return l(t,"upperKeys"),Ze.default=t,Ze}l(jc,"requireUppercaseKeysObject");var Qe={},Sr;function Kc(){if(Sr)return Qe;Sr=1;var s=Qe&&Qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Qe,"__esModule",{value:!0});var e=Ye(),t=rr();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var h=n({key:f},r);d=h.key}return d}))),o[u]=c}),o}return l(n,"camelKeys"),Qe.default=n,Qe}l(Kc,"requireCamelcaseKeysObject");var Xe={},kr;function Rc(){if(kr)return Xe;kr=1;var s=Xe&&Xe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(Xe,"__esModule",{value:!0});var e=Ye(),t=ar();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var h=n({key:f},r);d=h.key}return d}))),o[u]=c}),o}return l(n,"snakeKeys"),Xe.default=n,Xe}l(Rc,"requireSnakecaseKeysObject");var et={},Cr;function Mc(){if(Cr)return et;Cr=1;var s=et&&et.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(et,"__esModule",{value:!0});var e=Ye(),t=lr();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var h=n({key:f},r);d=h.key}return d}))),o[u]=c}),o}return l(n,"pascalKeys"),et.default=n,et}l(Mc,"requirePascalcaseKeysObject");var tt={},vr;function Bc(){if(vr)return tt;vr=1;var s=tt&&tt.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],f=0,d=u.length;f<d;f++,c++)a[c]=u[f];return a};Object.defineProperty(tt,"__esModule",{value:!0});var e=Ye(),t=gr();function n(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=n(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=n(f,r));else if(e.isArrayObject(f)){var h=n({key:f},r);d=h.key}return d}))),o[u]=c}),o}return l(n,"kebabKeys"),tt.default=n,tt}l(Bc,"requireKebabcaseKeysObject");var Er;function Fc(){if(Er)return _;Er=1,Object.defineProperty(_,"__esModule",{value:!0}),_.kebabKeys=_.pascalKeys=_.snakeKeys=_.camelKeys=_.upperKeys=_.lowerKeys=_.toLowerCase=_.toUpperCase=_.toKebabCase=_.toHeaderCase=_.toSentenceCase=_.toTextCase=_.toPathCase=_.toDotCase=_.toPascalCase=_.toSnakeCase=_.toCamelCase=void 0;var s=rr();_.toCamelCase=s.default;var e=ar();_.toSnakeCase=e.default;var t=lr();_.toPascalCase=t.default;var n=Nc();_.toDotCase=n.default;var i=xc();_.toPathCase=i.default;var r=Lc();_.toTextCase=r.default;var o=Pc();_.toSentenceCase=o.default;var a=_c();_.toHeaderCase=a.default;var c=gr();_.toKebabCase=c.default;var u=Dc();_.lowerKeys=u.default;var f=jc();_.upperKeys=f.default;var d=Kc();_.camelKeys=d.default;var h=Rc();_.snakeKeys=h.default;var m=Mc();_.pascalKeys=m.default;var w=Bc();_.kebabKeys=w.default;var p=l(function(k){return String(k||"").toLowerCase()},"toLowerCase");_.toLowerCase=p;var y=l(function(k){return String(k||"").toUpperCase()},"toUpperCase");_.toUpperCase=y;var C={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:p,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return _.default=C,_}l(Fc,"requireLib");var ps,Tr;function qc(){return Tr||(Tr=1,ps=Fc()),ps}l(qc,"requireJsConvertCase");var ms=qc();function hn(s){return ie[s].apiPath}l(hn,"getWorkspaceElementTypePath");function Ar(s,e){for(const t of Object.keys(e))s[t]=[...s[t]||[],...e[t]];return s}l(Ar,"mergeWorkspaceData");const Or=[P.Integration,P.Scenario,P.Action,P.Flow,P.AppDataSchema,P.AppEventType,P.DataLinkTable,P.DataSource,P.FieldMapping];async function Uc(){const s={};for(const e of Or){x.info(`Loading ${ie[e].namePlural}`);const t=[],i=ot().membraneDirPath,r=[j.join(i,hn(e))],o=j.join(i,ms.toCamelCase(hn(e)));r.includes(o)||r.push(o);for(const a of r)D.existsSync(a)&&t.push(...await Ir(a));s[e]=[...s[e]||[],...t]}return s}l(Uc,"readTopLevelElements");async function Jc(){const s={},t=ot().membraneDirPath,n=j.join(t,hn(P.Integration)),i=D.readdirSync(n);for(const r of i)if(D.statSync(j.join(n,r)).isDirectory()){const o=await $r(n,r);for(const a of Or){const c=j.join(n,r,hn(a)),u=await Ir(c);u.forEach(f=>{f.integrationKey=o?.key}),s[a]=[...s[a]||[],...u]}}return s}l(Jc,"readIntegrationLevelElements");async function Ir(s){const e=[];if(!D.existsSync(s))return e;x.info(`Reading ${s}`);const t=D.readdirSync(s);for(const n of t){const i=await $r(s,n);i&&(e.push(i),x.success(`Loaded ${n}`))}return e}l(Ir,"readWorkspaceElementsFromDir");async function $r(s,e){const t=j.join(s,e),i=D.statSync(t).isDirectory()?j.join(t,`${e}.yaml`):t;if(D.existsSync(i))return fe.load(D.readFileSync(i,"utf8"))}l($r,"readWorkspaceElementFromDirItem");async function Vc({client:s}){const t=(await s.get("org-workspace-id")).id,n=await Za(s,"minified"),i={};x.info("Loading local workspace data");const r=await Uc();Ar(i,r);const o=await Jc();Ar(i,o);const{universalElements:a,integrationSpecificElements:c}=Qa(i),u={connectorsMapping:{}};return await Wc({sourceData:i,workspaceData:n,pushContext:u,iApp:s,workspaceId:t}),n.integration=await s.integrations.findAll(),X("Syncing Universal Elements","BgBlue"),x.group("Syncing Universal Elements"),await Nr(a,n,s),x.groupEnd(),X("Syncing Integration Specific Elements","BgBlue"),x.group("Syncing Integration Specific Elements"),await Nr(c,n,s),x.groupEnd(),x.success("Data written successfully."),u}l(Vc,"pushWorkspace");async function Wc({sourceData:s,workspaceData:e,pushContext:t,iApp:n,workspaceId:i}){X("Matching imported integrations and connectors with existing ones","BgBlue"),await ec({client:n,workspaceData:e,pushContext:t,workspaceId:i});const r=[];for(const o of s.integration){const a=e.integration.find(u=>u.key==o.key),c={connectorId:o.connectorId,connectorVersion:o.connectorVersion,name:o.name,key:o.key};t.connectorsMapping[o.connectorId]&&(c.connectorId=t.connectorsMapping[o.connectorId]),a?(console.debug(`[Push] Updating integration ${o.key}`),await n.integration(a.id).patch(c)):(console.debug(`[Push] Creating integration ${o.key}`),await n.integrations.create(c)),X(`Imported integration ${o.name} (${o.key})`,"Green")}if(r.length>0)throw x.table(r.map(o=>({key:o.key,name:o.name}))),X("Integration missmatch errors. Make sure you have those applications in your destination workspace","BgRed"),new Error("Integration missmatch errors")}l(Wc,"syncIntegrations");async function Nr(s,e,t){for(const n of Object.keys(s))if(H[n]?.exportable!==!1)for(const r of s[n]){delete r.integrationId;const o=zc(r,n,e),a=ms.toCamelCase(ie[n].name),c=ms.toCamelCase(ie[n].namePlural);if(o)if(!St(r)||xr(r)&&St(r))await t[a](o.id).put(r),X(`Updated ${r.integrationKey||"universal"} ${H[n].element} ${r.key}`,"Cyan");else if(St(r)){try{await t[a](o.id).reset()}catch(u){throw console.debug(o,r),u}X(`Customization reset ${r.integrationKey||"universal"} ${H[n].element} ${r.key}`,"Magenta")}else X(`Corrupted. Migrate Manually ${r.integrationKey||"universal"} ${H[n].element} ${r.key}`,"Red");else if(St(r)){try{await t[a]({key:r.key}).apply([r.integrationKey])}catch{try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch{await t[c].create({...r,integrationId:e.integration.find(d=>d.key==r.integrationKey).id})}}if(xr(r)){try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch(u){throw console.debug(o,r),u}X(`Applied & Customized ${r.integrationKey||"universal"} ${H[n].element} ${r.key}`,"Green")}else X(`Applied universal ${H[n].element} ${r.key} to ${r.integrationKey} `,"Green")}else{try{r.integrationKey&&(delete r.integration,r.integrationId=e.integration.find(u=>u.key==r.integrationKey).id),await t[c].create(r)}catch(u){throw console.debug(`Error creating element ${n}`,St(r),r.integrationKey,r),u}X(`Created ${r.integrationKey||"universal"} ${H[n].element} ${r.key}`,"Green")}}}l(Nr,"syncElements");function xr(s){return s.integrationKey&&(s.customized||s.isCustomized)}l(xr,"elementIsCustomized");function zc(s,e,t){const n=t[e]?.filter(i=>i.key==s.key&&i.integrationKey==s.integrationKey&&!i.archivedAt);if(n.length>1)throw new Error(`More than one ${s.integrationKey||"universal"} ${e} with key ${s.key} found in the workspace`);if(n.length==1)return n[0]}l(zc,"matchElement");async function Gc(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Et.sign(t,e)}l(Gc,"generateAccessToken");function Hc(s){s.command("push").description("Push workspace data to specified workspace").addHelpText("after",["","Examples:"," membrane push # Push to default workspace",""].join(`
149
+ `)).action(async()=>{try{x.header("Pushing Workspace Data"),x.info("Loading configuration...");const e=Te();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");x.info("Preparing push configuration...");const t=new Sn({token:await Gc(e.workspaceKey,e.workspaceSecret),apiUri:e.apiUri});x.info("Pushing to remote workspace..."),await Vc({client:t}),x.success("Push to remote workspace completed successfully")}catch(e){e instanceof Error&&(x.error(e.message),process.exit(1)),x.error("An unknown error occurred"),process.exit(1)}})}l(Hc,"setupPushCommand");class Yc{static{l(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=ot(),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 Zc="claude-sonnet-4-20250514";class Ss{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:n}){const i=Te();if(!i)throw new Error("No membrane.config.yml found. Please 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 Sn({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new co({apiKey:i.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const f=await o.messages.create({model:Zc,max_tokens:u,messages:[{role:"user",content:c}]});return f.content[0].type==="text"?f.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(),Tn(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=j.join(this.testsDir,this.testBasePath,this.connectionId,e);if(D.existsSync(t))return fe.load(D.readFileSync(t,"utf8"))}async writeYaml(e,t){const n=j.join(this.testsDir,this.testBasePath,this.connectionId,e);D.mkdirSync(j.dirname(n),{recursive:!0}),D.writeFileSync(n,fe.dump(t,{noRefs:!0}))}writeResults(e){const t=j.join(this.testsDir,this.testBasePath,this.connectionId);D.mkdirSync(t,{recursive:!0});const n=j.join(t,"test-results.yaml");D.writeFileSync(n,fe.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 Et.sign(n,e.workspaceSecret,i)}}uo.interpolate=/{{([\s\S]+?)}}/g;function gs(s,e){if(typeof s=="string"){const t=lo(s),n={state:e,random:{number:l(()=>rt.number.int(),"number"),alphaNumeric:l(r=>rt.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:l(()=>rt.company.name(),"name"),catchPhrase:l(()=>rt.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>rt.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=>gs(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,gs(n,e)])):s}l(gs,"processNode");function Qc(s,e){return gs(s,e)}l(Qc,"handleTemplate");class Xc{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${v.bold.cyan("[start]")} ${v.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(`${v.bold.yellow("[initialized]")} ${v.yellow(e.path)}`)),o=Qc(r,this.environment.state),await e.run(o),console.debug(`${v.bold.green("[success]")} ${v.yellow(e.path)}`),t=!0,i=e.getResult(),kn(this.result,e.path,i)}catch(c){if(console.error(`${v.bold.red("[error]")} ${v.yellow(e.path)}: ${c}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(c);continue}catch(u){console.error(`${v.bold.red("[fix fail]")} ${v.yellow(e.path)}: ${u}`)}}kn(this.result,e.path,{error:de(c)}),t=!0,i={error:de(c)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Tn(this.result,e.getResult())}}class Ee{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const n=await this.fixTestCase({config:t,error:e});console.debug(v.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:de(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function ys(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const i=s[n],r=e[n];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!ws(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=ys(i,r);o!==null&&(t[n]=o)}else t[n]=r;continue}ws(i,r)||(t[n]=r)}return Object.keys(t).length===0?null:t}l(ys,"getNotMatchingSubFields");function ws(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}l(ws,"softCompare");class el extends Ee{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=Cn(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=Ts(n),a=vt(e.input.fields,o,{skipUnknownFields:!0}),c=vt(r.record.fields,o),u=ys(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const i=Xr(n);if(i.length>0){const r={};i.forEach(a=>{const c=eo(e.input.fields,a);typeof c<"u"&&kn(r,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Cn(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=de(t),i=Cn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
150
150
 
151
151
  ${JSON.stringify(i,null,2)}
152
152
 
@@ -156,7 +156,7 @@ ${JSON.stringify(e.input?.fields,null,2)}
156
156
 
157
157
  But got this error:
158
158
 
159
- ${JSON.stringify(s)}
159
+ ${JSON.stringify(n)}
160
160
 
161
161
  ${this.getExampleRecordsPrompt(r)}
162
162
 
@@ -170,7 +170,7 @@ Format your response as a JSON object with two fields:
170
170
  "fields": { ... fixed fields ... }
171
171
  }.
172
172
 
173
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),s=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
173
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
174
174
 
175
175
  ${this.getExampleRecordsPrompt(t)}
176
176
 
@@ -179,14 +179,14 @@ ${JSON.stringify(e,null,2)}.
179
179
 
180
180
  Do not populate fields with null or empty strings, unless the schema explicitly requires it.
181
181
 
182
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:s,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
182
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:n,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
183
183
 
184
- ${Object.entries(e).map(([s,i])=>`Example records from collection "${s}":
184
+ ${Object.entries(e).map(([n,i])=>`Example records from collection "${n}":
185
185
  ${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,s=[];return ps(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),s.push({key:r,parameters:o}))}return i}),s}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(s=>({id:s.id,fields:s.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),s={};for(const i of t){const r=ms(i);s[r]=await this.fetchExampleRecords(i)}return s}}class Kc extends we{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=s}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(s){throw s}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(s){if(s?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw s}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 s=ae(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 As(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=Os(i);n[r]=await this.fetchExampleRecords(i)}return n}}class tl extends Ee{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=de(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
 
@@ -194,7 +194,7 @@ ${JSON.stringify(e.input?.id,null,2)}
194
194
 
195
195
  But got this error:
196
196
 
197
- ${JSON.stringify(s)}
197
+ ${JSON.stringify(n)}
198
198
 
199
199
  Please analyze the error and provide:
200
200
  1. A fixed ID that would work (as a string)
@@ -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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Dc extends we{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=s}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 s=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!s.record,"Record is returned from findById"),await this.assert(()=>s.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 s=ae(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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class nl extends Ee{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=de(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
 
@@ -214,7 +214,7 @@ ${JSON.stringify(e.input?.id,null,2)}
214
214
 
215
215
  But got this error:
216
216
 
217
- ${JSON.stringify(s)}
217
+ ${JSON.stringify(n)}
218
218
 
219
219
  Please analyze the error and provide:
220
220
  1. A fixed ID that would work (as a string)
@@ -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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Mc extends we{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:s,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[s],c=r[o].fields[s];a==null||c==null||(i==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${s} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${s} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const s=ae(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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class sl extends Ee{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[n],c=r[o].fields[n];a==null||c==null||(i==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=de(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
 
@@ -234,7 +234,7 @@ ${JSON.stringify(e.input,null,2)}
234
234
 
235
235
  But got this error:
236
236
 
237
- ${JSON.stringify(s)}
237
+ ${JSON.stringify(n)}
238
238
 
239
239
  Please analyze the error and provide:
240
240
  1. Fixed parameters that would work (as a JSON object)
@@ -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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Rc extends we{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=s}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 s=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:s.id})).record;for(const[o,a]of Object.entries(e.input.query)){const c=r.fields[o];await this.assert(()=>rs(c,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const s={},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)s[o]=a;return{input:{query:s}}}async fixTestCase({config:e,error:t}){const s=ae(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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class il extends Ee{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const c=r.fields[o];await this.assert(()=>ws(c,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=de(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
 
@@ -254,7 +254,7 @@ ${JSON.stringify(e.input?.query,null,2)}
254
254
 
255
255
  But got this error:
256
256
 
257
- ${JSON.stringify(s)}
257
+ ${JSON.stringify(n)}
258
258
 
259
259
  Please analyze the error and provide:
260
260
  1. Fixed query that would work (as a JSON object)
@@ -266,12 +266,12 @@ 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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Bc extends we{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=s}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 s=t.records.some(i=>i.id===e.expectedRecordId);s||console.debug(v.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>s,"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],s=await this.getSearchQueryWithLLM(t.fields);if(!s)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:s},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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class rl extends Ee{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(i=>i.id===e.expectedRecordId);n||console.debug(v.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)}
273
273
 
274
- Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const s=ae(t),i=`I'm trying to search records in a data collection.
274
+ Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const n=de(t),i=`I'm trying to search records in a data collection.
275
275
 
276
276
  I tried to search records with these parameters:
277
277
 
@@ -279,7 +279,7 @@ ${JSON.stringify(e.input,null,2)}
279
279
 
280
280
  But got this error:
281
281
 
282
- ${JSON.stringify(s)}
282
+ ${JSON.stringify(n)}
283
283
 
284
284
  Please analyze the error and provide:
285
285
  1. Fixed parameters that would work (as a JSON object)
@@ -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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Fc extends we{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=s}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class qc extends we{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=s}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 s=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!s.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=s.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:s.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=un(this.dataCollection),o=hs(r),a=mt(e.input.fields,o,{skipUnknownFields:!0}),c=mt(i.record.fields,o),u=is(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=un(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const s=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:s}}}async fixTestCase({config:e,error:t}){const s=ae(t),i=un(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(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class ol extends Ee{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class al extends Ee{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=vn(this.dataCollection),o=Ts(r),a=vt(e.input.fields,o,{skipUnknownFields:!0}),c=vt(i.record.fields,o),u=ys(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=vn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=de(t),i=vn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
295
295
 
296
296
  ${JSON.stringify(i,null,2)}
297
297
 
@@ -301,7 +301,7 @@ ${JSON.stringify(e.input?.fields,null,2)}
301
301
 
302
302
  But got this error:
303
303
 
304
- ${JSON.stringify(s)}
304
+ ${JSON.stringify(n)}
305
305
 
306
306
  ${this.getExampleRecordsPrompt(r)}
307
307
 
@@ -315,7 +315,7 @@ Format your response as a JSON object with two fields:
315
315
  "fields": { ... fixed fields ... }
316
316
  }.
317
317
 
318
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{id:e.input.id,fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),s=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
318
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{id:e.input.id,fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),n=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
319
319
 
320
320
  ${this.getExampleRecordsPrompt(t)}
321
321
 
@@ -324,16 +324,16 @@ ${JSON.stringify(e,null,2)}.
324
324
 
325
325
  Do not populate fields with null or empty strings, unless the schema explicitly requires it.
326
326
 
327
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:s,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
327
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:n,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
328
328
 
329
- ${Object.entries(e).map(([s,i])=>`Example records from collection "${s}":
329
+ ${Object.entries(e).map(([n,i])=>`Example records from collection "${n}":
330
330
  ${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,s=[];return ps(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),s.push({key:r,parameters:o}))}return i}),s}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(s=>({id:s.id,fields:s.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),s={};for(const i of t){const r=ms(i);s[r]=await this.fetchExampleRecords(i)}return s}}const os={spec:{testerClass:Fc},create:{testerClass:jc,operationKey:"create"},"find-by-id":{testerClass:Dc,operationKey:"findById"},list:{testerClass:Mc,operationKey:"list"},match:{testerClass:Rc,operationKey:"match"},search:{testerClass:Bc,operationKey:"search"},update:{testerClass:qc,operationKey:"update"},delete:{testerClass:Kc,operationKey:"delete"}};class Uc extends Pc{static{l(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:s}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=s}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);N.info("\u{1F680} Running tests...");for(const s of t)await this.runTest(s);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 s=os[e];if(!s)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in s?s.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(s,t)}createAllAvailableTesters(e){return Object.entries(os).filter(([,t])=>{const s="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,s)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const s={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(s)}getAvailableTestMethods(e){return Object.entries(os).filter(([,t])=>{const s="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,s)}).map(([t])=>t)}displayTestSummary(e){N.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Jc extends _c{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){N.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:s}=this.options,i=e.split("/");i.length<2&&(N.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(N.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),N.error("Supported test types: connectors"),process.exit(1));const c=o,u=r,d=[...a,...t?t.split("/"):[]].join("/"),f=await as.create({connectionId:c,testBasePath:u,options:{fix:s}}),m=await f.client.get(`connections/${c}/data`),w=[],p=d?d.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let S,b;p.length>=1&&(b=p[0],p.length>=2&&p[1].trim()!==""&&(S=p[1]));for(const C of m){if(b&&b!==C.key)continue;const T=new Uc({environment:f,dataCollectionKey:C.key,testMethod:S});w.push(T)}}w.length===0&&(N.error(`No test suites found for path: ${e}${d?"/"+d:""}`),process.exit(1));const g={};for(const S of w){await S.run();const b=S.getResult();N.debug(`Suite ${S.constructor.name} result:`,{prefix:"TestRunner"}),dn(g,b)}console.debug("[TestRunner] All results collected:",Object.keys(g)),f.writeResults(g)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const tn=l(()=>[v.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"),v.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),v.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"),v.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),v.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),v.yellow("\u2502 Use in production environments is not recommended. \u2502"),v.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 Vc(n){n.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",tn()).action(async()=>{console.warn(tn()),N.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",["",v.bold("Examples:"),` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",v.gray("For more information, visit:"),v.blue(" https://docs.integration.app/cli"),"",tn()].join(`
336
- `)).action(async(t,s)=>{try{console.warn(tn()),t||(N.error("Test path is required"),process.exit(1)),N.header(`Testing: ${t}`);const i=new Jc({testPath:t,path:s.path,fix:s.fix});await i.initialize(),await i.run(),N.success("Tests completed")}catch(i){i instanceof Error&&(N.error(i.message),process.exit(1)),N.error("An unknown error occurred"),process.exit(1)}})}l(Vc,"setupTestCommand");const Wc=l(()=>{try{const n=Br(import.meta.url),e=br(n),t=Sr(e,"..","package.json");return JSON.parse(Er(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),mr=Wc();function zc(){const n=new Fr().name("membrane").description("Command-line interface for Membrane Agent").version(mr,"-v, --version","Output the version number");n.configureHelp({sortSubcommands:!0,subcommandTerm:l(e=>v.cyan(e.name()),"subcommandTerm"),commandUsage:l(e=>e.name()==="membrane"?`${v.cyan(e.name())} ${v.gray("[options]")} ${v.cyan("[command]")}`:e.usage(),"commandUsage"),optionTerm:l(e=>{const t=e.flags;return`${v.gray("\u25B8")} ${v.cyan(t)}`},"optionTerm"),subcommandDescription:l(e=>v.gray(e.description()),"subcommandDescription"),optionDescription:l(e=>v.gray(e.description),"optionDescription"),commandDescription:l(e=>v.gray(e.description()),"commandDescription")}),n.addHelpText("beforeAll",`
337
- ${v.bold.cyan("Membrane Agent CLI")} ${v.gray(`v${mr}`)}
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 As(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=Os(i);n[r]=await this.fetchExampleRecords(i)}return n}}const bs={spec:{testerClass:ol},create:{testerClass:el,operationKey:"create"},"find-by-id":{testerClass:nl,operationKey:"findById"},list:{testerClass:sl,operationKey:"list"},match:{testerClass:il,operationKey:"match"},search:{testerClass:rl,operationKey:"search"},update:{testerClass:al,operationKey:"update"},delete:{testerClass:tl,operationKey:"delete"}};class cl extends Xc{static{l(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);x.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=bs[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(bs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const n={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(n)}getAvailableTestMethods(e){return Object.entries(bs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){x.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class ll extends Yc{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){x.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,i=e.split("/");i.length<2&&(x.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(x.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),x.error("Supported test types: connectors"),process.exit(1));const c=o,u=r,f=[...a,...t?t.split("/"):[]].join("/"),d=await Ss.create({connectionId:c,testBasePath:u,options:{fix:n}}),m=await d.client.get(`connections/${c}/data`),w=[],p=f?f.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let C,k;p.length>=1&&(k=p[0],p.length>=2&&p[1].trim()!==""&&(C=p[1]));for(const O of m){if(k&&k!==O.key)continue;const T=new cl({environment:d,dataCollectionKey:O.key,testMethod:C});w.push(T)}}w.length===0&&(x.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const C of w){await C.run();const k=C.getResult();x.debug(`Suite ${C.constructor.name} result:`,{prefix:"TestRunner"}),Tn(y,k)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const pn=l(()=>[v.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"),v.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),v.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"),v.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),v.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),v.yellow("\u2502 Use in production environments is not recommended. \u2502"),v.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 ul(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",pn()).action(async()=>{console.warn(pn()),x.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",["",v.bold("Examples:"),` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${v.gray("\u25B8")} ${v.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",v.gray("For more information, visit:"),v.blue(" https://docs.integration.app/cli"),"",pn()].join(`
336
+ `)).action(async(t,n)=>{try{console.warn(pn()),t||(x.error("Test path is required"),process.exit(1)),x.header(`Testing: ${t}`);const i=new ll({testPath:t,path:n.path,fix:n.fix});await i.initialize(),await i.run(),x.success("Tests completed")}catch(i){i instanceof Error&&(x.error(i.message),process.exit(1)),x.error("An unknown error occurred"),process.exit(1)}})}l(ul,"setupTestCommand");const fl=l(()=>{try{const s=ro(import.meta.url),e=Kr(s),t=Rr(e,"..","package.json");return JSON.parse(Vr(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Lr=fl();function dl(){const s=new oo().name("membrane").description("Command-line interface for Membrane Agent").version(Lr,"-v, --version","Output the version number");s.configureHelp({sortSubcommands:!0,subcommandTerm:l(e=>v.cyan(e.name()),"subcommandTerm"),commandUsage:l(e=>e.name()==="membrane"?`${v.cyan(e.name())} ${v.gray("[options]")} ${v.cyan("[command]")}`:e.usage(),"commandUsage"),optionTerm:l(e=>{const t=e.flags;return`${v.gray("\u25B8")} ${v.cyan(t)}`},"optionTerm"),subcommandDescription:l(e=>v.gray(e.description()),"subcommandDescription"),optionDescription:l(e=>v.gray(e.description),"optionDescription"),commandDescription:l(e=>v.gray(e.description()),"commandDescription")}),s.addHelpText("beforeAll",`
337
+ ${v.bold.cyan("Membrane Agent CLI")} ${v.gray(`v${Lr}`)}
338
338
 
339
- `),vc(n),Nc(n),Vc(n),kc(n),Sc(n),mc(n),process.argv.length===2&&(n.outputHelp(),process.exit(0)),n.parse()}l(zc,"runCLI");const gr=["--cwd"];function Hc(){const n=process.argv.slice(2);return n.some((e,t)=>t>0&&gr.includes(n[t-1])?!1:!gr.includes(e))}l(Hc,"hasCLIArguments"),Hc()?zc():pc();
339
+ `),$c(s),Hc(s),ul(s),Ac(s),Tc(s),kc(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse()}l(dl,"runCLI");const Pr=["--cwd"];function hl(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Pr.includes(s[t-1])?!1:!Pr.includes(e))}l(hl,"hasCLIArguments"),hl()?dl():Sc();