@membranehq/cli 1.2.9 → 1.2.12

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 +107 -107
  2. package/package.json +2 -2
package/dist/index.js CHANGED
@@ -1,131 +1,131 @@
1
1
  #!/usr/bin/env node
2
- var vo=Object.defineProperty;var c=(s,e)=>vo(s,"name",{value:e,configurable:!0});import*as O from"node:fs";import{mkdirSync as ko,writeFileSync as To,readFileSync as Eo}from"node:fs";import*as x from"node:path";import{join as $n,dirname as Io}from"node:path";import{fileURLToPath as Oo}from"node:url";import v from"chalk";import{Command as Ao}from"commander";import{WorkspaceElementType as N,MembraneConfigLoader as $o,MembraneAxiosInstance as No,MembraneClient as Ys,WorkspaceElementSpecs as ye,WorkspaceSyncEventType as xo,ConnectorFileUpdateType as Nn,NotFoundError as Po,getMembraneElementPath as Lo,parseMembraneElementPath as De,CONNECTOR_VERSION_DEVELOPMENT as Zs,compareWorkspaceExports as Do,WorkspaceElementChangeType as we,setValueAtLocator as xn,extractMembraneErrorData as he,getDataCollectionCreateFields as Pn,excludeWriteOnlyFieldsFromSchema as Qs,valueToSchema as Rt,getRequiredFieldsFromSchema as Ro,getValueAtLocator as Mo,walkSchema as Xs,makeDataLocationPath as er,getDataCollectionUpdateFields as Ln}from"@membranehq/sdk";import Dn from"lodash/camelCase.js";import Rn from"lodash/upperFirst.js";import jo from"code-block-writer";import _o from"lodash/uniqBy.js";import Re,{createContext as Mn,useState as U,useEffect as ze,useContext as jn,useId as Fo,useRef as _n,useLayoutEffect as Mt,useMemo as Ko}from"react";import{Box as S,Text as C,useInput as Me,render as Fn,Newline as qo}from"ink";import{jsx as m,jsxs as E,Fragment as jt}from"react/jsx-runtime";import tr from"swr/immutable";import nr from"os";import _ from"path";import Bo from"conf";import Kn from"jsonwebtoken";import{AsyncLocalStorage as Uo}from"async_hooks";import Jo from"lodash/isEqual.js";import le from"js-yaml";import*as Wo from"node:crypto";import{createHash as Vo}from"node:crypto";import Go from"chokidar";import{EventEmitter as zo}from"events";import{EventSource as Ho}from"eventsource";import F from"fs";import sr from"archiver";import rr from"form-data";import ir from"unzipper";import*as Yo from"node:os";import"node:events";import or from"ink-text-input";import{SWRConfig as Zo}from"swr";import _t from"ink-spinner";import{TextInput as Qo,Select as Xo,Spinner as ea}from"@inkjs/ui";import{FastMCP as ta}from"fastmcp";import Ct from"axios";import{z as B}from"zod";import ar from"ora";import cr from"jszip";import{minimatch as na}from"minimatch";import{exec as sa}from"node:child_process";import qn from"lodash/merge.js";import ra from"@anthropic-ai/sdk";import{faker as vt}from"@faker-js/faker";import ia from"lodash/template.js";import oa from"lodash/templateSettings.js";function je(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>je({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?je(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=je(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(je)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=je(s.additionalProperties)),s.required&&(e.required=s.required),e}c(je,"convertDataSchemaToOpenAPI");function aa(s){const{membraneInterfaces:{actions:e}}=s,t=ca(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}c(aa,"generateOpenAPIContent");function ca(s){const e={};return s.forEach(t=>{const n=Rn(Dn(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=je(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=je(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(ca,"generateOpenAPISchemas");function la(s){const{membraneInterfaces:{actions:e}}=s,t=_o(e,"key"),n=new jo({indentNumberOfSpaces:2,newLine:`
3
- `});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),ua(n,t),n.toString()}c(la,"generateTypeScriptContent");function ua(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Un(t),r=t?.inputSchema;Ft(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Jn(t),o=t?.customOutputSchema||t?.outputSchema;Ft(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),Ft(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Un(t),r=Jn(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),Ft(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Un(t),r=Jn(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(ua,"generateModuleAugmentation");function Ft(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&fa(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,l)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),l<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}c(Ft,"generateTypeScriptInterface");function fa(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=Bn(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(fa,"generateTypeScriptProperties");function Bn(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?Bn(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=Bn(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(Bn,"convertJsonSchemaToTypeScript");function Un(s){return`${Rn(Dn(s.key))}Input`}c(Un,"getInputTypeName");function Jn(s){return`${Rn(Dn(s.key))}Output`}c(Jn,"getOutputTypeName");async function Wn(s){const{out:e}=s;await O.promises.mkdir(e,{recursive:!0});const t=da(s);for(const[n,r]of Object.entries(t)){const i=x.join(e,n);await O.promises.writeFile(i,r,"utf-8")}}c(Wn,"generateCode");function da(s){switch(s.target){case"openapi":return{"openapi.json":aa(s)};case"typescript":return{"generated.d.ts":la(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(da,"generateContent");const Vn=c(()=>[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 codegen 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(`
4
- `),"createExperimentalWarning$2");function ha(s,e){s.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Vn()).addHelpText("after",["",v.bold("Examples:"),` ${v.gray("\u25B8")} ${v.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${v.gray("\u25B8")} ${v.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Vn()].join(`
5
- `)).action(async t=>{try{console.warn(Vn()),console.error(v.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await pa(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await Wn(r),console.error(v.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(v.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(ha,"setupCodegenCommand");async function pa(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(N.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(pa,"loadMembraneInterfaces");const ma="membrane",ga="membrane.config.yml",Gn="https://api.integration.app",ya="https://console.integration.app";function zn(){const s=process.cwd(),e=x.join(s,ma),t=x.join(s,ga),n=e,r=x.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(zn,"getPaths");function lr(){return zn().membraneDirPath}c(lr,"getBasePath");const wa={pat:{type:"string"},workspace:{type:"object"}},ur=new Bo({schema:wa,configName:"config",cwd:_.join(nr.homedir(),".membrane")}),ba=c(s=>{ur.set("pat",s)},"setPat"),fr=c(()=>ur.get("pat"),"getPat");class dr{static{c(this,"AccountApiClient")}constructor(e=Gn){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=fr();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const Sa=c(s=>{const e=new dr(Gn);return t=>e.get(t)},"createAccountApiFetcher");class yt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new $o}static getInstance(){return yt.instance||(yt.instance=new yt),yt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const _e=yt.getInstance();function Kt(s){return _e.loadConfig(s)}c(Kt,"readProjectConfig");const Ca="membrane",va=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ie(s){return x.join(s,Ca)}c(ie,"getMembraneDir");const hr=$n(ie(process.cwd()),".logs");class ka{static{c(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;ko(hr,{recursive:!0});const i=$n(hr,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
6
- `);return To(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new ka,pr=new Uo;class mr{static{c(this,"RequestLogger")}constructor(e=No){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=c(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=pr.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.debug(`[Request]: ${r} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return pr.run(!0,e)}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){if(e.config?.metadata?.skipErrorLog)return;const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class Ta{static{c(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new mr,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=c(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():mr.withSkipErrorLog(r)}async generateAccessToken(e,t){return Kn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=Kt(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 Ys({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let l=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=l*.25*(Math.random()*2-1);l=Math.max(0,l+u)}await new Promise(u=>setTimeout(u,l))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const R=new Ta;async function gr(s){const e=await R.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(gr,"getWorkspaceId");var K={},qt={},yr;function wr(){if(yr)return qt;yr=1,Object.defineProperty(qt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toCamelCase"),qt.default=s,qt}c(wr,"requireJsCamelcase");var Bt={},br;function Sr(){if(br)return Bt;br=1,Object.defineProperty(Bt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return c(s,"toSnakeCase"),Bt.default=s,Bt}c(Sr,"requireJsSnakecase");var Ut={},Cr;function vr(){if(Cr)return Ut;Cr=1,Object.defineProperty(Ut,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return c(s,"toPascalCase"),Ut.default=s,Ut}c(vr,"requireJsPascalcase");var Jt={},kr;function Ea(){if(kr)return Jt;kr=1,Object.defineProperty(Jt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),Jt.default=s,Jt}c(Ea,"requireJsDotcase");var Wt={},Tr;function Ia(){if(Tr)return Wt;Tr=1,Object.defineProperty(Wt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Wt.default=s,Wt}c(Ia,"requireJsPathcase");var Vt={},Er;function Oa(){if(Er)return Vt;Er=1,Object.defineProperty(Vt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Vt.default=s,Vt}c(Oa,"requireJsTextcase");var Gt={},Ir;function Aa(){if(Ir)return Gt;Ir=1,Object.defineProperty(Gt,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return c(s,"toSentenceCase"),Gt.default=s,Gt}c(Aa,"requireJsSentencecase");var zt={},Or;function $a(){if(Or)return zt;Or=1,Object.defineProperty(zt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),zt.default=s,zt}c($a,"requireJsHeadercase");var Ht={},Ar;function $r(){if(Ar)return Ht;Ar=1,Object.defineProperty(Ht,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return c(s,"toKebabCase"),Ht.default=s,Ht}c($r,"requireJsKebabcase");var He={},Hn={},Nr;function Ye(){return Nr||(Nr=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})}}(Hn)),Hn}c(Ye,"requireUtils");var xr;function Na(){if(xr)return He;xr=1;var s=He&&He.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(He,"__esModule",{value:!0});var e=Ye();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"lowerKeys"),He.default=t,He}c(Na,"requireLowercaseKeysObject");var Ze={},Pr;function xa(){if(Pr)return Ze;Pr=1;var s=Ze&&Ze.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var l=arguments[r],u=0,f=l.length;u<f;u++,a++)o[a]=l[u];return o};Object.defineProperty(Ze,"__esModule",{value:!0});var e=Ye();function t(n,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],l=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[l]=a}),i}return c(t,"upperKeys"),Ze.default=t,Ze}c(xa,"requireUppercaseKeysObject");var Qe={},Lr;function Pa(){if(Lr)return Qe;Lr=1;var s=Qe&&Qe.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(Qe,"__esModule",{value:!0});var e=Ye(),t=wr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=l}),o}return c(n,"camelKeys"),Qe.default=n,Qe}c(Pa,"requireCamelcaseKeysObject");var Xe={},Dr;function La(){if(Dr)return Xe;Dr=1;var s=Xe&&Xe.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(Xe,"__esModule",{value:!0});var e=Ye(),t=Sr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=l}),o}return c(n,"snakeKeys"),Xe.default=n,Xe}c(La,"requireSnakecaseKeysObject");var et={},Rr;function Da(){if(Rr)return et;Rr=1;var s=et&&et.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(et,"__esModule",{value:!0});var e=Ye(),t=vr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=l}),o}return c(n,"pascalKeys"),et.default=n,et}c(Da,"requirePascalcaseKeysObject");var tt={},Mr;function Ra(){if(Mr)return tt;Mr=1;var s=tt&&tt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),l=0,i=0;i<o;i++)for(var u=arguments[i],f=0,d=u.length;f<d;f++,l++)a[l]=u[f];return a};Object.defineProperty(tt,"__esModule",{value:!0});var e=Ye(),t=$r();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var l=r[a],u=t.default(a);i.recursive&&(e.isValidObject(l)?e.belongToTypes(l,i.keepTypesOnRecursion)||(l=n(l,i)):i.recursiveInArray&&e.isArrayObject(l)&&(l=s(l).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=l}),o}return c(n,"kebabKeys"),tt.default=n,tt}c(Ra,"requireKebabcaseKeysObject");var jr;function Ma(){if(jr)return K;jr=1,Object.defineProperty(K,"__esModule",{value:!0}),K.kebabKeys=K.pascalKeys=K.snakeKeys=K.camelKeys=K.upperKeys=K.lowerKeys=K.toLowerCase=K.toUpperCase=K.toKebabCase=K.toHeaderCase=K.toSentenceCase=K.toTextCase=K.toPathCase=K.toDotCase=K.toPascalCase=K.toSnakeCase=K.toCamelCase=void 0;var s=wr();K.toCamelCase=s.default;var e=Sr();K.toSnakeCase=e.default;var t=vr();K.toPascalCase=t.default;var n=Ea();K.toDotCase=n.default;var r=Ia();K.toPathCase=r.default;var i=Oa();K.toTextCase=i.default;var o=Aa();K.toSentenceCase=o.default;var a=$a();K.toHeaderCase=a.default;var l=$r();K.toKebabCase=l.default;var u=Na();K.lowerKeys=u.default;var f=xa();K.upperKeys=f.default;var d=Pa();K.camelKeys=d.default;var h=La();K.snakeKeys=h.default;var g=Da();K.pascalKeys=g.default;var y=Ra();K.kebabKeys=y.default;var p=c(function(T){return String(T||"").toLowerCase()},"toLowerCase");K.toLowerCase=p;var w=c(function(T){return String(T||"").toUpperCase()},"toUpperCase");K.toUpperCase=w;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:l.default,toUpperCase:w,toLowerCase:p,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return K.default=k,K}c(Ma,"requireLib");var Yn,_r;function ja(){return _r||(_r=1,Yn=Ma()),Yn}c(ja,"requireJsConvertCase");var _a=ja();const be={UPDATE:"update",DELETE:"delete",CREATE:"create"},te={INCOMING:"incoming",OUTGOING:"outgoing"},pe={[N.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[N.Connector]:{element:"connector",elements:"connectors",exportable:!1},[N.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[N.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[N.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[N.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[N.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[N.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[N.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[N.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},Fa=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Fr=[N.Action,N.FieldMapping,N.Flow,N.DataSource,N.Package];class z{static{c(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||z.extractIntegrationKey(r)}get id(){return z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[N.Integration].apiPath;return x.join(t,this.integrationKey,e,this.key)}return x.join(e,this.key)}get path(){return x.join(this.dirPath,"spec.yaml")}get relativePath(){return x.relative(ie(process.cwd()),this.path)}get absolutePath(){return x.resolve(x.join(ie(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Jo(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Fa.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return pe?.[this.type]?.parentKey&&(e=pe?.[this.type]?.parentKey),e}static new(e,t,n,r){return new z(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new z(e,t.key,n,t)}static fromPathAndData(e,t){const n=z.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?z.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new z(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=z.parsePath(e);if(t)return z.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===N.Integration?`${e}:${t}`:z.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).map(l=>l.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:l,elementKey:u}=i.groups,f=this.getElementTypeFromPath(l);if(f)return{type:f,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:l,elementType:u,elementKey:f}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:f,integrationKey:l}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(N).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return x.relative(ie(process.cwd()),e)}static isIntegrationSpecific(e){return Fr.includes(e)}static canBeIntegrationSpecific(e){return Fr.includes(e)}}class Kr{static{c(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[N.Integration,N.Connector],r=Object.keys(pe),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}function Zn(s,e=!0){if(O.existsSync(s))try{const t=O.readFileSync(s,"utf8");return le.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=x.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Zn,"readYaml$1");function Ka(s,e,t){try{const n=le.dump(e,t);O.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=x.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Ka,"writeYaml$1");class qa extends Kr{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ie(process.cwd())}async getElementsByType(e,t){const n=[],r=x.join(this.basePath,ye[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=x.join(this.basePath,ye[N.Integration].apiPath,o.key,ye[e].apiPath),l=await this.readElementsInDir(a);n.push(...l)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=x.join(this.basePath,t.dirPath),r=x.join(this.basePath,t.path);return O.existsSync(n)||O.mkdirSync(n,{recursive:!0}),Ka(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=x.join(this.basePath,e.path),n=x.join(this.basePath,e.dirPath);O.existsSync(t)&&O.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=x.join(this.basePath,ye[N.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Zn(e);if(t)return z.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!O.existsSync(e))return t;const n=O.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=x.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!O.existsSync(e)||O.readdirSync(e).length>0)return;O.rmdirSync(e),this.pruneEmptyDir(x.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Ba extends Kr{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=z.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!z.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,l=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...l)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await R.withClient(n=>n[pe[e.type].element](e.data.id).get());return z.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const o=e.getParentKey(),a=new Set(["uuid","integrationId",o,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(l=>{a.has(l)||delete n[l]})}const r=await R.withClient(o=>o[pe[e.type].elements].create(n)),i=z.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await R.withClient(a=>a[pe[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return b.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await R.withClient(a=>a[pe[e.type].element](t.data.id).put(r)),o=z.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await R.withClient(t=>t[pe[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await R.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>z.fromData(N.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await R.withClient(r=>r[pe[t].element](e).get(),!1),!!n)return z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==N.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const l=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!l)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:l.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await R.withClient(i=>i[pe[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),z.fromData(e,i))):[]}}const Qn=Symbol.for("yaml.alias"),Xn=Symbol.for("yaml.document"),Ee=Symbol.for("yaml.map"),qr=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),nt=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Ie=c(s=>!!s&&typeof s=="object"&&s[oe]===Qn,"isAlias"),Fe=c(s=>!!s&&typeof s=="object"&&s[oe]===Xn,"isDocument"),st=c(s=>!!s&&typeof s=="object"&&s[oe]===Ee,"isMap"),W=c(s=>!!s&&typeof s=="object"&&s[oe]===qr,"isPair"),J=c(s=>!!s&&typeof s=="object"&&s[oe]===me,"isScalar$1"),rt=c(s=>!!s&&typeof s=="object"&&s[oe]===nt,"isSeq");function V(s){if(s&&typeof s=="object")switch(s[oe]){case Ee:case nt:return!0}return!1}c(V,"isCollection$1");function G(s){if(s&&typeof s=="object")switch(s[oe]){case Qn:case Ee:case me:case nt:return!0}return!1}c(G,"isNode");const Br=c(s=>(J(s)||V(s))&&!!s.anchor,"hasAnchor"),ne=Symbol("break visit"),Ur=Symbol("skip children"),ge=Symbol("remove node");function Ke(s,e){const t=Jr(e);Fe(s)?it(null,s.contents,t,Object.freeze([s]))===ge&&(s.contents=null):it(null,s,t,Object.freeze([]))}c(Ke,"visit$1"),Ke.BREAK=ne,Ke.SKIP=Ur,Ke.REMOVE=ge;function it(s,e,t,n){const r=Wr(s,e,t,n);if(G(r)||W(r))return Vr(s,n,r),it(s,r,t,n);if(typeof r!="symbol"){if(V(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=it(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===ge&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){n=Object.freeze(n.concat(e));const i=it("key",e.key,t,n);if(i===ne)return ne;i===ge&&(e.key=null);const o=it("value",e.value,t,n);if(o===ne)return ne;o===ge&&(e.value=null)}}return r}c(it,"visit_");async function Yt(s,e){const t=Jr(e);Fe(s)?await ot(null,s.contents,t,Object.freeze([s]))===ge&&(s.contents=null):await ot(null,s,t,Object.freeze([]))}c(Yt,"visitAsync"),Yt.BREAK=ne,Yt.SKIP=Ur,Yt.REMOVE=ge;async function ot(s,e,t,n){const r=await Wr(s,e,t,n);if(G(r)||W(r))return Vr(s,n,r),ot(s,r,t,n);if(typeof r!="symbol"){if(V(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await ot(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===ge&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){n=Object.freeze(n.concat(e));const i=await ot("key",e.key,t,n);if(i===ne)return ne;i===ge&&(e.key=null);const o=await ot("value",e.value,t,n);if(o===ne)return ne;o===ge&&(e.value=null)}}return r}c(ot,"visitAsync_");function Jr(s){return typeof s=="object"&&(s.Collection||s.Node||s.Value)?Object.assign({Alias:s.Node,Map:s.Node,Scalar:s.Node,Seq:s.Node},s.Value&&{Map:s.Value,Scalar:s.Value,Seq:s.Value},s.Collection&&{Map:s.Collection,Seq:s.Collection},s):s}c(Jr,"initVisitor");function Wr(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(st(e))return t.Map?.(s,e,n);if(rt(e))return t.Seq?.(s,e,n);if(W(e))return t.Pair?.(s,e,n);if(J(e))return t.Scalar?.(s,e,n);if(Ie(e))return t.Alias?.(s,e,n)}c(Wr,"callVisitor");function Vr(s,e,t){const n=e[e.length-1];if(V(n))n.items[s]=t;else if(W(n))s==="key"?n.key=t:n.value=t;else if(Fe(n))n.contents=t;else{const r=Ie(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(Vr,"replaceNode");const Ua={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ja=c(s=>s.replace(/[!,[\]{}]/g,e=>Ua[e]),"escapeTagName");class ee{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ee.defaultYaml,e),this.tags=Object.assign({},ee.defaultTags,t)}clone(){const e=new ee(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new ee(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ee.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ee.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:ee.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ee.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Ja(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&G(e.contents)){const i={};Ke(e.contents,(o,a)=>{G(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
7
- `)}}ee.defaultYaml={explicit:!1,version:"1.2"},ee.defaultTags={"!!":"tag:yaml.org,2002:"};function Gr(s){if(/[\x00-\x19\s,[\]{}]/.test(s)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(s)}`;throw new Error(t)}return!0}c(Gr,"anchorIsValid");function zr(s){const e=new Set;return Ke(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(zr,"anchorNames");function Hr(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(Hr,"findNewAnchor");function Wa(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=zr(s));const o=Hr(e,r);return r.add(o),o},"onAnchor"),setAnchors:c(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(J(o.node)||V(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}c(Wa,"createNodeAnchors");function at(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=at(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=at(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=at(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=at(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(at,"applyReviver");function ae(s,e,t){if(Array.isArray(s))return s.map((n,r)=>ae(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!Br(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}c(ae,"toJS");class es{static{c(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:r,reviver:i}={}){if(!Fe(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 r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?at(i,{"":a},"",a):a}}class Zt extends es{static{c(this,"Alias")}constructor(e){super(Qn),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=[],Ke(e,{Node:c((i,o)=>{(Ie(o)||Br(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=n.get(o);if(a||(ae(o,null,t),a=n.get(o)),!a||a.res===void 0){const l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Qt(r,o,n)),a.count*a.aliasCount>i)){const l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(Gr(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Qt(s,e,t){if(Ie(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(V(e)){let n=0;for(const r of e.items){const i=Qt(s,r,t);i>n&&(n=i)}return n}else if(W(e)){const n=Qt(s,e.key,t),r=Qt(s,e.value,t);return Math.max(n,r)}return 1}c(Qt,"getAliasCount");const Yr=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class D extends es{static{c(this,"Scalar")}constructor(e){super(me),this.value=e}toJSON(e,t){return t?.keep?this.value:ae(this.value,e,t)}toString(){return String(this.value)}}D.BLOCK_FOLDED="BLOCK_FOLDED",D.BLOCK_LITERAL="BLOCK_LITERAL",D.PLAIN="PLAIN",D.QUOTE_DOUBLE="QUOTE_DOUBLE",D.QUOTE_SINGLE="QUOTE_SINGLE";const Va="tag:yaml.org,2002:";function Ga(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}c(Ga,"findTagObject");function kt(s,e,t){if(Fe(s)&&(s=s.contents),G(s))return s;if(W(s)){const d=t.schema[Ee].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let l;if(n&&s&&typeof s=="object"){if(l=a.get(s),l)return l.anchor??(l.anchor=r(s)),new Zt(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Va+e.slice(2));let u=Ga(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new D(s);return l&&(l.node=d),d}u=s instanceof Map?o[Ee]:Symbol.iterator in Object(s)?o[nt]:o[Ee]}i&&(i(u),delete t.onTagObj);const f=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new D(s);return e?f.tag=e:u.default||(f.tag=u.tag),l&&(l.node=f),f}c(kt,"createNode");function Xt(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return kt(n,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:c(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:s,sourceObjects:new Map})}c(Xt,"collectionFromPath");const Tt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Zr extends es{static{c(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(n=>G(n)||W(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Tt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(V(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Xt(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(V(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&J(i)?i.value:i:V(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!W(t))return!1;const n=t.value;return n==null||e&&J(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return V(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(V(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Xt(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const za=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Se(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Se,"indentComment");const qe=c((s,e,t)=>s.endsWith(`
2
+ var Co=Object.defineProperty;var l=(s,e)=>Co(s,"name",{value:e,configurable:!0});import*as O from"node:fs";import{mkdirSync as vo,writeFileSync as ko,readFileSync as Eo}from"node:fs";import*as x from"node:path";import{join as $n,dirname as To}from"node:path";import{fileURLToPath as Io}from"node:url";import v from"chalk";import{Command as Oo}from"commander";import{WorkspaceElementType as N,MembraneConfigLoader as Ao,MembraneAxiosInstance as $o,MembraneClient as Ys,WorkspaceElementSpecs as ye,WorkspaceSyncEventType as No,ConnectorFileUpdateType as Nn,NotFoundError as xo,getMembraneElementPath as Po,parseMembraneElementPath as Re,CONNECTOR_VERSION_DEVELOPMENT as Zs,compareWorkspaceExports as Lo,WorkspaceElementChangeType as we,setValueAtLocator as xn,extractMembraneErrorData as he,getDataCollectionCreateFields as Pn,excludeWriteOnlyFieldsFromSchema as Qs,valueToSchema as Dt,getRequiredFieldsFromSchema as Ro,getValueAtLocator as Do,walkSchema as Xs,makeDataLocationPath as er,getDataCollectionUpdateFields as Ln}from"@membranehq/sdk";import Rn from"lodash/camelCase.js";import Dn from"lodash/upperFirst.js";import Mo from"code-block-writer";import jo from"lodash/uniqBy.js";import De,{createContext as Mn,useState as q,useEffect as ze,useContext as jn,useId as _o,useRef as _n,useLayoutEffect as Mt,useMemo as Fo}from"react";import{Box as S,Text as C,useInput as Me,render as Fn,Newline as Ko}from"ink";import{jsx as m,jsxs as T,Fragment as jt}from"react/jsx-runtime";import tr from"swr/immutable";import nr from"os";import _ from"path";import Bo from"conf";import Kn from"jsonwebtoken";import{AsyncLocalStorage as qo}from"async_hooks";import Uo from"lodash/isEqual.js";import le from"js-yaml";import*as Jo from"node:crypto";import{createHash as Wo}from"node:crypto";import Vo from"chokidar";import{EventEmitter as Go}from"events";import{EventSource as zo}from"eventsource";import F from"fs";import sr from"archiver";import rr from"form-data";import ir from"unzipper";import*as Ho from"node:os";import"node:events";import or from"ink-text-input";import{SWRConfig as Yo}from"swr";import _t from"ink-spinner";import{TextInput as Zo,Select as Qo,Spinner as Xo}from"@inkjs/ui";import{FastMCP as ea}from"fastmcp";import Ct from"axios";import{z as B}from"zod";import ar from"ora";import cr from"jszip";import{minimatch as ta}from"minimatch";import{exec as na}from"node:child_process";import Bn from"lodash/merge.js";import sa from"@anthropic-ai/sdk";import{faker as vt}from"@faker-js/faker";import ra from"lodash/template.js";import ia from"lodash/templateSettings.js";function je(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>je({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?je(s.items):{type:"object"}};return s.title&&(t.title=s.title),s.description&&(t.description=s.description),s.minItems!==void 0&&(t.minItems=s.minItems),s.maxItems!==void 0&&(t.maxItems=s.maxItems),s.uniqueItems!==void 0&&(t.uniqueItems=s.uniqueItems),t}}const e={};if(s.type&&!Array.isArray(s.type)&&(e.type=s.type),s.title&&(e.title=s.title),s.description&&(e.description=s.description),s.format&&(e.format=s.format),s.enum&&(e.enum=s.enum),s.default!==void 0&&(e.default=s.default),s.minimum!==void 0&&(e.minimum=s.minimum),s.maximum!==void 0&&(e.maximum=s.maximum),s.minLength!==void 0&&(e.minLength=s.minLength),s.maxLength!==void 0&&(e.maxLength=s.maxLength),s.maxItems!==void 0&&(e.maxItems=s.maxItems),s.readOnly!==void 0&&(e.readOnly=s.readOnly),s.writeOnly!==void 0&&(e.writeOnly=s.writeOnly),s.examples&&s.examples.length>0&&(e.example=s.examples[0]),s.properties){e.properties={};for(const[t,n]of Object.entries(s.properties))e.properties[t]=je(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(je)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=je(s.additionalProperties)),s.required&&(e.required=s.required),e}l(je,"convertDataSchemaToOpenAPI");function oa(s){const{membraneInterfaces:{actions:e}}=s,t=aa(e);return JSON.stringify({openapi:"3.0.0",info:{title:"Membrane Actions API",version:"1.0.0",description:"Generated OpenAPI specification for Membrane actions"},paths:{},components:{schemas:t}},null,2)}l(oa,"generateOpenAPIContent");function aa(s){const e={};return s.forEach(t=>{const n=Dn(Rn(t.key)),r={type:"object",properties:{id:{type:"string",description:"Request ID"},action:{type:"string",enum:[t.key]}},required:["id","action"]};if(t?.inputSchema){const a=je(t.inputSchema);a.properties&&(r.properties={...r.properties,...a.properties}),a.required&&(r.required=[...r.required||[],...a.required])}e[`${n}Request`]=r;const i={type:"object",properties:{id:{type:"string",description:"Response ID"},success:{type:"boolean"},data:{type:"object"}},required:["id","success"]},o=t?.customOutputSchema||t?.outputSchema;if(o){const a=je(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}l(aa,"generateOpenAPISchemas");function ca(s){const{membraneInterfaces:{actions:e}}=s,t=jo(e,"key"),n=new Mo({indentNumberOfSpaces:2,newLine:`
3
+ `});return n.writeLine("// Generated TypeScript definitions for Membrane actions"),n.newLine(),n.writeLine("import type {"),n.writeLine(" ActionAccessor,"),n.writeLine(" ConnectionLevelActionAccessor,"),n.writeLine('} from "@membranehq/sdk";'),n.newLine(),la(n,t),n.toString()}l(ca,"generateTypeScriptContent");function la(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Un(t),r=t?.inputSchema;Ft(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Jn(t),o=t?.customOutputSchema||t?.outputSchema;Ft(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),Ft(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Un(t),r=Jn(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),Ft(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Un(t),r=Jn(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}l(la,"generateModuleAugmentation");function Ft(s,e){const{interfaceName:t,properties:n,required:r=[],methods:i,fallbackContent:o}=e;s.writeLine(`interface ${t} {`),s.indent(()=>{n&&Object.keys(n).length>0&&ua(s,n,r),i&&i.length>0&&(n&&Object.keys(n).length>0&&s.newLine(),i.forEach((a,c)=>{s.writeLine(`${a.name}(${a.parameters}): ${a.returnType};`),c<i.length-1&&s.newLine()})),o&&(!n||Object.keys(n).length===0)&&(!i||i.length===0)&&s.writeLine(o)}),s.writeLine("}")}l(Ft,"generateTypeScriptInterface");function ua(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=qn(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}l(ua,"generateTypeScriptProperties");function qn(s){return s.type==="string"?s.enum?s.enum.map(e=>`'${e}'`).join(" | "):"string":s.type==="number"||s.type==="integer"?"number":s.type==="boolean"?"boolean":s.type==="array"?`${s.items?qn(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=qn(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}l(qn,"convertJsonSchemaToTypeScript");function Un(s){return`${Dn(Rn(s.key))}Input`}l(Un,"getInputTypeName");function Jn(s){return`${Dn(Rn(s.key))}Output`}l(Jn,"getOutputTypeName");async function Wn(s){const{out:e}=s;await O.promises.mkdir(e,{recursive:!0});const t=fa(s);for(const[n,r]of Object.entries(t)){const i=x.join(e,n);await O.promises.writeFile(i,r,"utf-8")}}l(Wn,"generateCode");function fa(s){switch(s.target){case"openapi":return{"openapi.json":oa(s)};case"typescript":return{"generated.d.ts":ca(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}l(fa,"generateContent");const Vn=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 codegen 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(`
4
+ `),"createExperimentalWarning$2");function da(s,e){s.command("codegen").description("\u26A0\uFE0F EXPERIMENTAL: Generate code for easy integration within projects - This feature is experimental and will be changing rapidly. Use at your own risk.").requiredOption("--actions <actions>",'Comma-separated list of action names (e.g., "list-files,get-file-by-id")').requiredOption("--out <path>","Output directory for generated files").requiredOption("--target <type>","Target format: openapi or typescript").requiredOption("--schemasOnly","Generate only schemas without implementation").addHelpText("after",Vn()).addHelpText("after",["",v.bold("Examples:"),` ${v.gray("\u25B8")} ${v.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${v.gray("\u25B8")} ${v.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Vn()].join(`
5
+ `)).action(async t=>{try{console.warn(Vn()),console.error(v.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await ha(e,t),r={out:t.out,target:t.target,schemasOnly:t.schemasOnly,membraneInterfaces:n};console.error(`Output: ${r.out}`),console.error(`Target: ${r.target}`),console.error(`Schemas Only: ${r.schemasOnly?"Yes":"No"}`),console.error(`Loaded ${n.actions.length} membrane interfaces`),console.error("Status: Generating code..."),await Wn(r),console.error(v.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(v.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}l(da,"setupCodegenCommand");async function ha(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(N.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}l(ha,"loadMembraneInterfaces");const pa="membrane",ma="membrane.config.yml",Gn="https://api.integration.app",ga="https://console.integration.app";function zn(){const s=process.cwd(),e=x.join(s,pa),t=x.join(s,ma),n=e,r=x.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}l(zn,"getPaths");function lr(){return zn().membraneDirPath}l(lr,"getBasePath");const ya={pat:{type:"string"},workspace:{type:"object"}},ur=new Bo({schema:ya,configName:"config",cwd:_.join(nr.homedir(),".membrane")}),wa=l(s=>{ur.set("pat",s)},"setPat"),fr=l(()=>ur.get("pat"),"getPat");class dr{static{l(this,"AccountApiClient")}constructor(e=Gn){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=fr();if(!o)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${o}`)}t.body&&!n.has("Content-Type")&&n.set("Content-Type","application/json");const r=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:n});if(!r.ok){const o=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${o}`)}if(r.status===204)return{};const i=await r.text();return JSON.parse(i)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const ba=l(s=>{const e=new dr(Gn);return t=>e.get(t)},"createAccountApiFetcher");class yt{static{l(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Ao}static getInstance(){return yt.instance||(yt.instance=new yt),yt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const _e=yt.getInstance();function Kt(s){return _e.loadConfig(s)}l(Kt,"readProjectConfig");const Sa="membrane",Ca=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ie(s){return x.join(s,Sa)}l(ie,"getMembraneDir");const hr=$n(ie(process.cwd()),".logs");class va{static{l(this,"WorkspaceLogger")}_logs;verboseMode=!1;notificationHandler=null;constructor(){this._logs=[]}setNotificationHandler(e){this.notificationHandler=e}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.notificationHandler&&this.notificationHandler.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;vo(hr,{recursive:!0});const i=$n(hr,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
6
+ `);return ko(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new va,pr=new qo;class mr{static{l(this,"RequestLogger")}constructor(e=$o){this.axiosInstance=e}interceptorsConfigured=!1;setup(){if(this.interceptorsConfigured)return;const e=l(t=>(this.logError(t),Promise.reject(t)),"errorHandler");this.axiosInstance.interceptors.request.use(t=>{const n=pr.getStore();t.metadata={startTime:Date.now(),skipErrorLog:n};const{method:r,url:i}=this.getRequestDetails(t);return b.debug(`[Request]: ${r} ${i}`),t},e),this.axiosInstance.interceptors.response.use(t=>{const{method:n,url:r}=this.getRequestDetails(t.config),i=this.getDuration(t.config),{status:o,statusText:a}=t;return b.debug(`[Response]: ${n} ${r} - ${o} ${a} (${i}ms)`),t},e),this.interceptorsConfigured=!0}static withSkipErrorLog(e){return pr.run(!0,e)}getRequestDetails(e){const t=e?.method?.toUpperCase()??"UNKNOWN";if(!e?.url)return{method:t,url:"unknown"};if(e.url.startsWith("http"))return{method:t,url:e.url};const r=`${e.baseURL??""}/${e.url}`.replace(/\/+/g,"/").replace(/:\//,"://");return{method:t,url:r}}getDuration(e){return Date.now()-(e?.metadata?.startTime??Date.now())}logError(e){if(e.config?.metadata?.skipErrorLog)return;const{method:t,url:n}=this.getRequestDetails(e.config),r=this.getDuration(e.config);if(e.response){const{status:i,statusText:o}=e.response;b.error(`[Response]: ${t} ${n} - ${i} ${o} (${r}ms)`),e.response.data&&b.error(`[Response Data]: ${JSON.stringify(e.response.data,null,2)}`)}}}class ka{static{l(this,"MembraneAPIManager")}client=null;currentConfig=null;tokenExpiry=0;requestTimes=[];maxRequestsPerSecond=80;windowSizeMs=1e3;semaphore=0;maxConcurrentRequests;maxRetries;retryDelay;requestTimeout;enableJitter;semaphoreQueue=[];rateLimitMutex=Promise.resolve();requestLogger=null;constructor(e={}){this.init(e)}init(e={}){this.windowSizeMs=e.windowSizeMs??1e3,this.maxRequestsPerSecond=e.maxRequestsPerSecond??80,this.maxConcurrentRequests=e.maxConcurrentRequests??Math.max(1,Math.min(Math.floor(this.maxRequestsPerSecond/4),20)),this.maxRetries=e.maxRetries??3,this.retryDelay=e.retryDelay??1e3,this.requestTimeout=e.requestTimeout??12e4,this.enableJitter=e.enableJitter!==!1,this.requestLogger=new mr,this.requestLogger.setup()}async withClient(e,t=!0,n=process.cwd()){const r=l(async()=>{try{return await this.withRetry(async()=>{const i=await this.getClient(n);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(i),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}catch(i){if(t)throw i;return}},"executeRequest");return t?r():mr.withSkipErrorLog(r)}async generateAccessToken(e,t){return Kn.sign({name:"Membrane Agent",isAdmin:!0,exp:Math.floor(Date.now()/1e3)+3600,iss:e},t,{algorithm:"HS512"})}isTokenValid(){return Date.now()<this.tokenExpiry}getCurrentConfig(e){const t=Kt(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 Ys({token:t,apiUri:e.apiUri})}async getClient(e=process.cwd()){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create MembraneClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,r=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||n||r)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0,this.requestTimes=[],this.semaphore=0,this.semaphoreQueue=[],this.rateLimitMutex=Promise.resolve()}getCurrentConfigInfo(){return this.currentConfig}async waitIfNeeded(){this.rateLimitMutex=this.rateLimitMutex.then(async()=>{for(this.cleanOldRequests();this.requestTimes.length>=this.maxRequestsPerSecond;){const t=this.requestTimes[0]+this.windowSizeMs-Date.now()+10;if(t>0)await new Promise(n=>setTimeout(n,t)),this.cleanOldRequests();else break}}),await this.rateLimitMutex}recordRequest(){this.requestTimes.push(Date.now())}cleanOldRequests(){const e=Date.now()-this.windowSizeMs;this.requestTimes=this.requestTimes.filter(t=>t>e)}getRequestCount(){return this.cleanOldRequests(),this.requestTimes.length}async acquireSemaphore(){if(this.semaphore<this.maxConcurrentRequests){this.semaphore++;return}return new Promise(e=>{this.semaphoreQueue.push(e)})}releaseSemaphore(){if(this.semaphore--,this.semaphoreQueue.length>0){const e=this.semaphoreQueue.shift();this.semaphore++,e()}}async withRetry(e,t="operation"){let n;for(let r=0;r<=this.maxRetries;r++)try{return await e()}catch(i){if(n=i,!this.isRetryableError(i)||r===this.maxRetries)throw i;const o=new Date().toISOString(),a=r+2;b.debug(`[${o}] Retrying ${t} (attempt ${a}/${this.maxRetries+1})`);let c=this.retryDelay*Math.pow(2,r);if(this.enableJitter){const u=c*.25*(Math.random()*2-1);c=Math.max(0,c+u)}await new Promise(u=>setTimeout(u,c))}throw n||new Error("Unknown error occurred during retry attempts")}isRetryableError(e){if(!e)return!1;const t=(e.message||e.toString()||"").toLowerCase(),n=e.code;return n&&["econnrefused","enotfound","econnreset","etimedout","ehostunreach","enetunreach"].includes(n.toLowerCase())?!0:["econnrefused","connection refused","network error","timeout","socket hang up","request timeout","dns lookup failed"].some(o=>t.includes(o))}async withTimeout(e,t){let n;const r=new Promise((i,o)=>{n=setTimeout(()=>o(new Error(`Request timeout after ${t}ms`)),t)});try{const i=await Promise.race([e,r]);return n&&clearTimeout(n),i}catch(i){throw n&&clearTimeout(n),i}}}const D=new ka;async function gr(s){const e=await D.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}l(gr,"getWorkspaceId");var K={},Bt={},yr;function wr(){if(yr)return Bt;yr=1,Object.defineProperty(Bt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w)/g,function(t,n,r){return r.toUpperCase()}):""}return l(s,"toCamelCase"),Bt.default=s,Bt}l(wr,"requireJsCamelcase");var qt={},br;function Sr(){if(br)return qt;br=1,Object.defineProperty(qt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(s,"toSnakeCase"),qt.default=s,qt}l(Sr,"requireJsSnakecase");var Ut={},Cr;function vr(){if(Cr)return Ut;Cr=1,Object.defineProperty(Ut,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"$"+r}).toLowerCase().replace(/(\$)(\w?)/g,function(t,n,r){return r.toUpperCase()}):""}return l(s,"toPascalCase"),Ut.default=s,Ut}l(vr,"requireJsPascalcase");var Jt={},kr;function Ea(){if(kr)return Jt;kr=1,Object.defineProperty(Jt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(s,"toDotCase"),Jt.default=s,Jt}l(Ea,"requireJsDotcase");var Wt={},Er;function Ta(){if(Er)return Wt;Er=1,Object.defineProperty(Wt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(s,"toPathCase"),Wt.default=s,Wt}l(Ta,"requireJsPathcase");var Vt={},Tr;function Ia(){if(Tr)return Vt;Tr=1,Object.defineProperty(Vt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(s,"toTextCase"),Vt.default=s,Vt}l(Ia,"requireJsTextcase");var Gt={},Ir;function Oa(){if(Ir)return Gt;Ir=1,Object.defineProperty(Gt,"__esModule",{value:!0});function s(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(n,r,i){return r+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(s,"toSentenceCase"),Gt.default=s,Gt}l(Oa,"requireJsSentencecase");var zt={},Or;function Aa(){if(Or)return zt;Or=1,Object.defineProperty(zt,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return l(s,"toHeaderCase"),zt.default=s,zt}l(Aa,"requireJsHeadercase");var Ht={},Ar;function $r(){if(Ar)return Ht;Ar=1,Object.defineProperty(Ht,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(s,"toKebabCase"),Ht.default=s,Ht}l($r,"requireJsKebabcase");var He={},Hn={},Nr;function Ye(){return Nr||(Nr=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})}}(Hn)),Hn}l(Ye,"requireUtils");var xr;function $a(){if(xr)return He;xr=1;var s=He&&He.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var c=arguments[r],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,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toLowerCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[c]=a}),i}return l(t,"lowerKeys"),He.default=t,He}l($a,"requireLowercaseKeysObject");var Ze={},Pr;function Na(){if(Pr)return Ze;Pr=1;var s=Ze&&Ze.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var o=Array(n),a=0,r=0;r<i;r++)for(var c=arguments[r],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,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(n))return null;r=e.validateOptions(r);var i={};return Object.keys(n).forEach(function(o){var a=n[o],c=o.toUpperCase();r.recursive&&(e.isValidObject(a)?e.belongToTypes(a,r.keepTypesOnRecursion)||(a=t(a,r)):r.recursiveInArray&&e.isArrayObject(a)&&(a=s(a).map(function(u){var f=u;if(e.isValidObject(u))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=t(u,r));else if(e.isArrayObject(u)){var d=t({key:u},r);f=d.key}return f}))),i[c]=a}),i}return l(t,"upperKeys"),Ze.default=t,Ze}l(Na,"requireUppercaseKeysObject");var Qe={},Lr;function xa(){if(Lr)return Qe;Lr=1;var s=Qe&&Qe.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),c=0,i=0;i<o;i++)for(var u=arguments[i],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=wr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var c=r[a],u=t.default(a);i.recursive&&(e.isValidObject(c)?e.belongToTypes(c,i.keepTypesOnRecursion)||(c=n(c,i)):i.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=c}),o}return l(n,"camelKeys"),Qe.default=n,Qe}l(xa,"requireCamelcaseKeysObject");var Xe={},Rr;function Pa(){if(Rr)return Xe;Rr=1;var s=Xe&&Xe.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),c=0,i=0;i<o;i++)for(var u=arguments[i],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=Sr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var c=r[a],u=t.default(a);i.recursive&&(e.isValidObject(c)?e.belongToTypes(c,i.keepTypesOnRecursion)||(c=n(c,i)):i.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=c}),o}return l(n,"snakeKeys"),Xe.default=n,Xe}l(Pa,"requireSnakecaseKeysObject");var et={},Dr;function La(){if(Dr)return et;Dr=1;var s=et&&et.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),c=0,i=0;i<o;i++)for(var u=arguments[i],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=vr();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var c=r[a],u=t.default(a);i.recursive&&(e.isValidObject(c)?e.belongToTypes(c,i.keepTypesOnRecursion)||(c=n(c,i)):i.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=c}),o}return l(n,"pascalKeys"),et.default=n,et}l(La,"requirePascalcaseKeysObject");var tt={},Mr;function Ra(){if(Mr)return tt;Mr=1;var s=tt&&tt.__spreadArrays||function(){for(var r=0,i=0,o=arguments.length;i<o;i++)r+=arguments[i].length;for(var a=Array(r),c=0,i=0;i<o;i++)for(var u=arguments[i],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=$r();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var o={};return Object.keys(r).forEach(function(a){var c=r[a],u=t.default(a);i.recursive&&(e.isValidObject(c)?e.belongToTypes(c,i.keepTypesOnRecursion)||(c=n(c,i)):i.recursiveInArray&&e.isArrayObject(c)&&(c=s(c).map(function(f){var d=f;if(e.isValidObject(f))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=n(f,i));else if(e.isArrayObject(f)){var h=n({key:f},i);d=h.key}return d}))),o[u]=c}),o}return l(n,"kebabKeys"),tt.default=n,tt}l(Ra,"requireKebabcaseKeysObject");var jr;function Da(){if(jr)return K;jr=1,Object.defineProperty(K,"__esModule",{value:!0}),K.kebabKeys=K.pascalKeys=K.snakeKeys=K.camelKeys=K.upperKeys=K.lowerKeys=K.toLowerCase=K.toUpperCase=K.toKebabCase=K.toHeaderCase=K.toSentenceCase=K.toTextCase=K.toPathCase=K.toDotCase=K.toPascalCase=K.toSnakeCase=K.toCamelCase=void 0;var s=wr();K.toCamelCase=s.default;var e=Sr();K.toSnakeCase=e.default;var t=vr();K.toPascalCase=t.default;var n=Ea();K.toDotCase=n.default;var r=Ta();K.toPathCase=r.default;var i=Ia();K.toTextCase=i.default;var o=Oa();K.toSentenceCase=o.default;var a=Aa();K.toHeaderCase=a.default;var c=$r();K.toKebabCase=c.default;var u=$a();K.lowerKeys=u.default;var f=Na();K.upperKeys=f.default;var d=xa();K.camelKeys=d.default;var h=Pa();K.snakeKeys=h.default;var g=La();K.pascalKeys=g.default;var w=Ra();K.kebabKeys=w.default;var p=l(function(E){return String(E||"").toLowerCase()},"toLowerCase");K.toLowerCase=p;var y=l(function(E){return String(E||"").toUpperCase()},"toUpperCase");K.toUpperCase=y;var k={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:p,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:w.default};return K.default=k,K}l(Da,"requireLib");var Yn,_r;function Ma(){return _r||(_r=1,Yn=Da()),Yn}l(Ma,"requireJsConvertCase");var ja=Ma();const be={UPDATE:"update",DELETE:"delete",CREATE:"create"},te={INCOMING:"incoming",OUTGOING:"outgoing"},pe={[N.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")},[N.Connector]:{element:"connector",elements:"connectors",exportable:!1},[N.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(s=>(delete s.integration,s),"exportCleanup")},[N.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[N.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[N.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[N.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[N.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:l(s=>(delete s.dataSourceId,s),"exportCleanup")},[N.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[N.Package]:{element:"package",elements:"packages",integrationSpecific:!0}},_a=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Fr=[N.Action,N.FieldMapping,N.Flow,N.DataSource,N.Package];class z{static{l(this,"Element")}type;key;integrationKey;data;constructor(e,t,n,r){if(!r)throw new Error("Element must always contain data");if(!t)throw new Error("Element must have a key");this.type=e,this.key=t,this.data=r,this.integrationKey=n||z.extractIntegrationKey(r)}get id(){return z.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=ye[this.type].apiPath;if(this.integrationKey){const t=ye[N.Integration].apiPath;return x.join(t,this.integrationKey,e,this.key)}return x.join(e,this.key)}get path(){return x.join(this.dirPath,"spec.yaml")}get relativePath(){return x.relative(ie(process.cwd()),this.path)}get absolutePath(){return x.resolve(x.join(ie(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Uo(t,n)}hasParent(){if(this.data?.parentUuid)return!0;const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return _a.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return pe?.[this.type]?.parentKey&&(e=pe?.[this.type]?.parentKey),e}static new(e,t,n,r){return new z(e,t,n,r)}static fromData(e,t){if(!t?.key)throw new Error(`Element missing key: ${JSON.stringify(t)}`);const n=this.extractIntegrationKey(t);return new z(e,t.key,n,t)}static fromPathAndData(e,t){const n=z.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?z.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new z(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=z.parsePath(e);if(t)return z.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===N.Integration?`${e}:${t}`:z.isIntegrationSpecific(e)?`${n||"universal"}:${e}:${t}`:`${e}:${t}`}static parsePath(e){const t=this.getRelativePath(e);if(!this.isElementFile(t))return;const n=Object.values(ye).map(c=>c.apiPath).join("|"),r=new RegExp(`^(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),i=t.match(r);if(i?.groups){const{elementType:c,elementKey:u}=i.groups,f=this.getElementTypeFromPath(c);if(f)return{type:f,key:u}}const o=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementType>${n})/(?<elementKey>[^/]+)/spec\\.ya?ml$`),a=t.match(o);if(a?.groups){const{integrationKey:c,elementType:u,elementKey:f}=a.groups,d=this.getElementTypeFromPath(u);if(d)return{type:d,key:f,integrationKey:c}}}static extractIntegrationKey(e){return e?.integrationKey||e?.integration?.key||e?.integration_key||void 0}static isElementFile(e){return e.endsWith(".yml")||e.endsWith(".yaml")}static getElementTypeFromPath(e){return Object.values(N).find(t=>ye[t].apiPath===e)}static getRelativePath(e){return x.relative(ie(process.cwd()),e)}static isIntegrationSpecific(e){return Fr.includes(e)}static canBeIntegrationSpecific(e){return Fr.includes(e)}}class Kr{static{l(this,"BaseWorkspaceElementsRepository")}constructor(e){this.cache=e}connectorsMapping;sourceCache;setConnectorsMapping(e){this.connectorsMapping=e}setSourceCache(e){this.sourceCache=e}async getElements(){const e=[];try{const t=await this.getIntegrations();e.push(...t);const n=[N.Integration,N.Connector],r=Object.keys(pe),i=await Promise.all(r.filter(o=>!n.includes(o)).map(async o=>this.getElementsByType(o,t)));for(const o of i)e.push(...o)}catch(t){throw b.error(`Failed to get elements: ${t}`),t}return e}async putElement(e){let t=this.cache.get(e.id);return t&&!e.data.id&&t.data.id&&(e.data.id=t.data.id),!t&&e.data.id&&(t=await this.getByInternalId(e.data.id,e.type,!1)),e.data.id&&t?t=await this.updateElement(e,t,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}):t=await this.createElement(e,{elements:this.cache.getAll(),connectorsMapping:this.connectorsMapping,sourceElements:this.sourceCache?.getAll()}),t}async getElementsByType(e,t){return[]}async createElement(e,t){return e}async updateElement(e,t,n){return t}async getElement(e){}async getIntegrations(){return[]}async getByInternalId(e,t,n=!0){}async deleteElement(e,t){}}function Zn(s,e=!0){if(O.existsSync(s))try{const t=O.readFileSync(s,"utf8");return le.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=x.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}l(Zn,"readYaml$1");function Fa(s,e,t){try{const n=le.dump(e,t);O.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=x.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}l(Fa,"writeYaml$1");class Ka extends Kr{static{l(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ie(process.cwd())}async getElementsByType(e,t){const n=[],r=x.join(this.basePath,ye[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=x.join(this.basePath,ye[N.Integration].apiPath,o.key,ye[e].apiPath),c=await this.readElementsInDir(a);n.push(...c)}return n.length>0&&b.debug(`[local] Fetched ${n.length} ${e}${n.length!==1?"s":""}`),n}async getElement(e){return this.readElement(e.path)}async createElement(e){return this.updateElement(e,e)}async updateElement(e,t){if(!e.data)throw new Error("Element must have data to write");const n=x.join(this.basePath,t.dirPath),r=x.join(this.basePath,t.path);return O.existsSync(n)||O.mkdirSync(n,{recursive:!0}),Fa(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=x.join(this.basePath,e.path),n=x.join(this.basePath,e.dirPath);O.existsSync(t)&&O.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=x.join(this.basePath,ye[N.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Zn(e);if(t)return z.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!O.existsSync(e))return t;const n=O.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=x.join(e,o,"spec.yaml");return this.readElement(a)});return(await Promise.all(r)).filter(o=>o!=null)}pruneEmptyDir(e){try{if(!e.startsWith(this.basePath)||e===this.basePath||!O.existsSync(e)||O.readdirSync(e).length>0)return;O.rmdirSync(e),this.pruneEmptyDir(x.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Ba extends Kr{static{l(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=z.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!z.canBeIntegrationSpecific(e))return r;for(const i of t){const o=i.key,a=i.data.id,c=await this.findAll(e,a?{integrationId:a}:{integrationKey:o},o);r.push(...c)}return r.length>0&&b.debug(`[remote] Fetched ${r.length} ${e}${r.length!==1?"s":""}`),r}async getElement(e){const t=await D.withClient(n=>n[pe[e.type].element](e.data.id).get());return z.fromData(e.type,t)}async createElement(e,t){const n=e.clean();if(this.transformElementForCreate(e,n,t),e.hasParent()&&n.integrationId&&!n.isCustomized){const o=e.getParentKey(),a=new Set(["uuid","integrationId",o,"meta","integrationUuid","parentUuid"]);Object.keys(n).forEach(c=>{a.has(c)||delete n[c]})}const r=await D.withClient(o=>o[pe[e.type].elements].create(n)),i=z.fromData(e.type,r);return b.debug(`[remote] Created ${i.id}`),i}async updateElement(e,t,n){if(!e.data.id)throw new Error("Element must have an id to update");t.data.archivedAt&&await D.withClient(a=>a[pe[e.type].element](t.data.id).restore());const r=e.clean();if(this.transformElementForUpdate(e,r,n),e.hasParent()&&r.integrationId&&!r.isCustomized)return b.debug(`[remote] Skipped update for ${t.id} (non-customized)`),t;const i=await D.withClient(a=>a[pe[e.type].element](t.data.id).put(r)),o=z.fromData(t.type,i);return b.debug(`[remote] Updated ${t.id}`),o}async deleteElement(e){if(!e.data.id)throw new Error("Element must have an id to delete");await D.withClient(t=>t[pe[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await D.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>z.fromData(N.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await D.withClient(r=>r[pe[t].element](e).get(),!1),!!n)return z.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformElementForUpdate(e,t,n){if(e.type===N.Integration){const r=n.connectorsMapping?.[t.connectorId];r&&(t.connectorId=r)}if(e.integrationKey){t.integrationKey=e.integrationKey;const r=n.elements.find(i=>i.type===N.Integration&&i.key===e.integrationKey);if(r)t.integrationId=r.data.id;else throw new Error(`Dependency integration ${e.integrationKey} not found for ${e.id}`)}this.transformPackageDependencies(e,t,n),this.transformParentDependency(e,t,n)}transformPackageDependencies(e,t,n){if(e.type!==N.Package||!t.elements)return;const r=t.elements.map(i=>{const a=(n.sourceElements||n.elements).find(u=>u.data.id===i.id&&u.type===i.type);if(!a)throw new Error(`Package element ${i.type} with id ${i.id} not found in source workspace for package ${e.id}`);const c=n.elements.find(u=>u.type===i.type&&u.key===a.key&&u.integrationKey===a.integrationKey);if(!c)throw new Error(`Package element ${i.type} with key ${a.key} not found in target workspace for package ${e.id}`);return{id:c.data.id,type:i.type}});t.elements=r}transformParentDependency(e,t,n){if(!e.hasParent())return;const r=e.getParentKey();if(!r)return;const i=n.elements.find(o=>o.type===e.type&&o.key===e.key&&!o.hasParent());if(i)t[r]=i.data.id;else throw new Error(`Parent ${e.getParentKey()} not found for ${e.id}`)}async findAll(e,t={},n){const r=await D.withClient(i=>i[pe[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),z.fromData(e,i))):[]}}const Qn=Symbol.for("yaml.alias"),Xn=Symbol.for("yaml.document"),Te=Symbol.for("yaml.map"),Br=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),nt=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Ie=l(s=>!!s&&typeof s=="object"&&s[oe]===Qn,"isAlias"),Fe=l(s=>!!s&&typeof s=="object"&&s[oe]===Xn,"isDocument"),st=l(s=>!!s&&typeof s=="object"&&s[oe]===Te,"isMap"),W=l(s=>!!s&&typeof s=="object"&&s[oe]===Br,"isPair"),U=l(s=>!!s&&typeof s=="object"&&s[oe]===me,"isScalar$1"),rt=l(s=>!!s&&typeof s=="object"&&s[oe]===nt,"isSeq");function V(s){if(s&&typeof s=="object")switch(s[oe]){case Te:case nt:return!0}return!1}l(V,"isCollection$1");function G(s){if(s&&typeof s=="object")switch(s[oe]){case Qn:case Te:case me:case nt:return!0}return!1}l(G,"isNode");const qr=l(s=>(U(s)||V(s))&&!!s.anchor,"hasAnchor"),ne=Symbol("break visit"),Ur=Symbol("skip children"),ge=Symbol("remove node");function Ke(s,e){const t=Jr(e);Fe(s)?it(null,s.contents,t,Object.freeze([s]))===ge&&(s.contents=null):it(null,s,t,Object.freeze([]))}l(Ke,"visit$1"),Ke.BREAK=ne,Ke.SKIP=Ur,Ke.REMOVE=ge;function it(s,e,t,n){const r=Wr(s,e,t,n);if(G(r)||W(r))return Vr(s,n,r),it(s,r,t,n);if(typeof r!="symbol"){if(V(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=it(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===ge&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){n=Object.freeze(n.concat(e));const i=it("key",e.key,t,n);if(i===ne)return ne;i===ge&&(e.key=null);const o=it("value",e.value,t,n);if(o===ne)return ne;o===ge&&(e.value=null)}}return r}l(it,"visit_");async function Yt(s,e){const t=Jr(e);Fe(s)?await ot(null,s.contents,t,Object.freeze([s]))===ge&&(s.contents=null):await ot(null,s,t,Object.freeze([]))}l(Yt,"visitAsync"),Yt.BREAK=ne,Yt.SKIP=Ur,Yt.REMOVE=ge;async function ot(s,e,t,n){const r=await Wr(s,e,t,n);if(G(r)||W(r))return Vr(s,n,r),ot(s,r,t,n);if(typeof r!="symbol"){if(V(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await ot(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ne)return ne;o===ge&&(e.items.splice(i,1),i-=1)}}}else if(W(e)){n=Object.freeze(n.concat(e));const i=await ot("key",e.key,t,n);if(i===ne)return ne;i===ge&&(e.key=null);const o=await ot("value",e.value,t,n);if(o===ne)return ne;o===ge&&(e.value=null)}}return r}l(ot,"visitAsync_");function Jr(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(Jr,"initVisitor");function Wr(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(st(e))return t.Map?.(s,e,n);if(rt(e))return t.Seq?.(s,e,n);if(W(e))return t.Pair?.(s,e,n);if(U(e))return t.Scalar?.(s,e,n);if(Ie(e))return t.Alias?.(s,e,n)}l(Wr,"callVisitor");function Vr(s,e,t){const n=e[e.length-1];if(V(n))n.items[s]=t;else if(W(n))s==="key"?n.key=t:n.value=t;else if(Fe(n))n.contents=t;else{const r=Ie(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}l(Vr,"replaceNode");const qa={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ua=l(s=>s.replace(/[!,[\]{}]/g,e=>qa[e]),"escapeTagName");class ee{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},ee.defaultYaml,e),this.tags=Object.assign({},ee.defaultTags,t)}clone(){const e=new ee(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new ee(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:ee.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},ee.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:ee.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},ee.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),r=n.shift();switch(r){case"%TAG":{if(n.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),n.length<2))return!1;const[i,o]=n;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,n.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[i]=n;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{const o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);const i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return n==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+Ua(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&G(e.contents)){const i={};Ke(e.contents,(o,a)=>{G(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,o]of n)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
7
+ `)}}ee.defaultYaml={explicit:!1,version:"1.2"},ee.defaultTags={"!!":"tag:yaml.org,2002:"};function Gr(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(Gr,"anchorIsValid");function zr(s){const e=new Set;return Ke(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}l(zr,"anchorNames");function Hr(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}l(Hr,"findNewAnchor");function Ja(s,e){const t=[],n=new Map;let r=null;return{onAnchor:l(i=>{t.push(i),r??(r=zr(s));const o=Hr(e,r);return r.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const i of t){const o=n.get(i);if(typeof o=="object"&&o.anchor&&(U(o.node)||V(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},"setAnchors"),sourceObjects:n}}l(Ja,"createNodeAnchors");function at(s,e,t,n){if(n&&typeof n=="object")if(Array.isArray(n))for(let r=0,i=n.length;r<i;++r){const o=n[r],a=at(s,n,String(r),o);a===void 0?delete n[r]:a!==o&&(n[r]=a)}else if(n instanceof Map)for(const r of Array.from(n.keys())){const i=n.get(r),o=at(s,n,r,i);o===void 0?n.delete(r):o!==i&&n.set(r,o)}else if(n instanceof Set)for(const r of Array.from(n)){const i=at(s,n,r,r);i===void 0?n.delete(r):i!==r&&(n.delete(r),n.add(i))}else for(const[r,i]of Object.entries(n)){const o=at(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}l(at,"applyReviver");function ae(s,e,t){if(Array.isArray(s))return s.map((n,r)=>ae(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!qr(s))return s.toJSON(e,t);const n={aliasCount:0,count:1,res:void 0};t.anchors.set(s,n),t.onCreate=i=>{n.res=i,delete t.onCreate};const r=s.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof s=="bigint"&&!t?.keep?Number(s):s}l(ae,"toJS");class es{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:r,reviver:i}={}){if(!Fe(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 r=="function")for(const{count:c,res:u}of o.anchors.values())r(u,c);return typeof i=="function"?at(i,{"":a},"",a):a}}class Zt extends es{static{l(this,"Alias")}constructor(e){super(Qn),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=[],Ke(e,{Node:l((i,o)=>{(Ie(o)||qr(o))&&n.push(o)},"Node")}),t&&(t.aliasResolveCache=n));let r;for(const i of n){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};const{anchors:n,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){const 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(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Qt(r,o,n)),a.count*a.aliasCount>i)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,n){const r=`*${this.source}`;if(e){if(Gr(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}}function Qt(s,e,t){if(Ie(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(V(e)){let n=0;for(const r of e.items){const i=Qt(s,r,t);i>n&&(n=i)}return n}else if(W(e)){const n=Qt(s,e.key,t),r=Qt(s,e.value,t);return Math.max(n,r)}return 1}l(Qt,"getAliasCount");const Yr=l(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class L extends es{static{l(this,"Scalar")}constructor(e){super(me),this.value=e}toJSON(e,t){return t?.keep?this.value:ae(this.value,e,t)}toString(){return String(this.value)}}L.BLOCK_FOLDED="BLOCK_FOLDED",L.BLOCK_LITERAL="BLOCK_LITERAL",L.PLAIN="PLAIN",L.QUOTE_DOUBLE="QUOTE_DOUBLE",L.QUOTE_SINGLE="QUOTE_SINGLE";const Wa="tag:yaml.org,2002:";function Va(s,e,t){if(e){const n=t.filter(i=>i.tag===e),r=n.find(i=>!i.format)??n[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(n=>n.identify?.(s)&&!n.format)}l(Va,"findTagObject");function kt(s,e,t){if(Fe(s)&&(s=s.contents),G(s))return s;if(W(s)){const d=t.schema[Te].createNode?.(t.schema,null,t);return d.items.push(s),d}(s instanceof String||s instanceof Number||s instanceof Boolean||typeof BigInt<"u"&&s instanceof BigInt)&&(s=s.valueOf());const{aliasDuplicateObjects:n,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t;let c;if(n&&s&&typeof s=="object"){if(c=a.get(s),c)return c.anchor??(c.anchor=r(s)),new Zt(c.anchor);c={anchor:null,node:null},a.set(s,c)}e?.startsWith("!!")&&(e=Wa+e.slice(2));let u=Va(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new L(s);return c&&(c.node=d),d}u=s instanceof Map?o[Te]:Symbol.iterator in Object(s)?o[nt]:o[Te]}i&&(i(u),delete t.onTagObj);const f=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new L(s);return e?f.tag=e:u.default||(f.tag=u.tag),c&&(c.node=f),f}l(kt,"createNode");function Xt(s,e,t){let n=t;for(let r=e.length-1;r>=0;--r){const i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){const o=[];o[i]=n,n=o}else n=new Map([[i,n]])}return kt(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(Xt,"collectionFromPath");const Et=l(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Zr extends es{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=>G(n)||W(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Et(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(V(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Xt(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){const[t,...n]=e;if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(V(r))return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){const[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&U(i)?i.value:i:V(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!W(t))return!1;const n=t.value;return n==null||e&&U(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){const[t,...n]=e;if(n.length===0)return this.has(t);const r=this.get(t,!0);return V(r)?r.hasIn(n):!1}setIn(e,t){const[n,...r]=e;if(r.length===0)this.set(n,t);else{const i=this.get(n,!0);if(V(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Xt(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Ga=l(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Se(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}l(Se,"indentComment");const Be=l((s,e,t)=>s.endsWith(`
8
8
  `)?Se(t,e):t.includes(`
9
9
  `)?`
10
- `+Se(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Qr="flow",ts="block",en="quoted";function tn(s,e,t="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return s;r<i&&(i=0);const l=Math.max(1+i,1+r-e.length);if(s.length<=l)return s;const u=[],f={};let d=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):d=r-n);let h,g,y=!1,p=-1,w=-1,k=-1;t===ts&&(p=Xr(s,p,e.length),p!==-1&&(d=p+l));for(let $;$=s[p+=1];){if(t===en&&$==="\\"){switch(w=p,s[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}k=p}if($===`
11
- `)t===ts&&(p=Xr(s,p,e.length)),d=p+e.length+l,h=void 0;else{if($===" "&&g&&g!==" "&&g!==`
10
+ `+Se(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),Qr="flow",ts="block",en="quoted";function tn(s,e,t="flow",{indentAtStart:n,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return s;r<i&&(i=0);const c=Math.max(1+i,1+r-e.length);if(s.length<=c)return s;const u=[],f={};let d=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):d=r-n);let h,g,w=!1,p=-1,y=-1,k=-1;t===ts&&(p=Xr(s,p,e.length),p!==-1&&(d=p+c));for(let A;A=s[p+=1];){if(t===en&&A==="\\"){switch(y=p,s[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}k=p}if(A===`
11
+ `)t===ts&&(p=Xr(s,p,e.length)),d=p+e.length+c,h=void 0;else{if(A===" "&&g&&g!==" "&&g!==`
12
12
  `&&g!==" "){const I=s[p+1];I&&I!==" "&&I!==`
13
- `&&I!==" "&&(h=p)}if(p>=d)if(h)u.push(h),d=h+l,h=void 0;else if(t===en){for(;g===" "||g===" ";)g=$,$=s[p+=1],y=!0;const I=p>k+1?p-2:w-1;if(f[I])return s;u.push(I),f[I]=!0,d=I+l,h=void 0}else y=!0}g=$}if(y&&a&&a(),u.length===0)return s;o&&o();let T=s.slice(0,u[0]);for(let $=0;$<u.length;++$){const I=u[$],P=u[$+1]||s.length;I===0?T=`
14
- ${e}${s.slice(0,P)}`:(t===en&&f[I]&&(T+=`${s[I]}\\`),T+=`
15
- ${e}${s.slice(I+1,P)}`)}return T}c(tn,"foldFlowLines");function Xr(s,e,t){let n=e,r=e+1,i=s[r];for(;i===" "||i===" ";)if(e<r+t)i=s[++e];else{do i=s[++e];while(i&&i!==`
16
- `);n=e,r=e+1,i=s[r]}return n}c(Xr,"consumeMoreIndentedLines");const nn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),sn=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function Ha(s,e,t){if(!e||e<0)return!1;const n=e-t,r=s.length;if(r<=n)return!1;for(let i=0,o=0;i<r;++i)if(s[i]===`
17
- `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(Ha,"lineLengthOverLimit");function Et(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(sn(s)?" ":"");let o="",a=0;for(let l=0,u=t[l];u;u=t[++l])if(u===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,u="\\"),u==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);const f=t.substr(l+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(l,6)}l+=5,a=l+1}break;case"n":if(n||t[l+2]==='"'||t.length<r)l+=1;else{for(o+=t.slice(a,l)+`
18
-
19
- `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
20
- `,l+=2;o+=i,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,n?o:tn(o,i,en,nn(e,!1))}c(Et,"doubleQuotedString");function ns(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
21
- `)||/[ \t]\n|\n[ \t]/.test(s))return Et(s,e);const t=e.indent||(sn(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
22
- ${t}`)+"'";return e.implicitKey?n:tn(n,t,Qr,nn(e,!1))}c(ns,"singleQuotedString");function ct(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Et;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=ns:i&&!r?n=Et:n=t?ns:Et}return n(s,e)}c(ct,"quotedString");let ss;try{ss=new RegExp(`(^|(?<!
13
+ `&&I!==" "&&(h=p)}if(p>=d)if(h)u.push(h),d=h+c,h=void 0;else if(t===en){for(;g===" "||g===" ";)g=A,A=s[p+=1],w=!0;const I=p>k+1?p-2:y-1;if(f[I])return s;u.push(I),f[I]=!0,d=I+c,h=void 0}else w=!0}g=A}if(w&&a&&a(),u.length===0)return s;o&&o();let E=s.slice(0,u[0]);for(let A=0;A<u.length;++A){const I=u[A],P=u[A+1]||s.length;I===0?E=`
14
+ ${e}${s.slice(0,P)}`:(t===en&&f[I]&&(E+=`${s[I]}\\`),E+=`
15
+ ${e}${s.slice(I+1,P)}`)}return E}l(tn,"foldFlowLines");function Xr(s,e,t){let n=e,r=e+1,i=s[r];for(;i===" "||i===" ";)if(e<r+t)i=s[++e];else{do i=s[++e];while(i&&i!==`
16
+ `);n=e,r=e+1,i=s[r]}return n}l(Xr,"consumeMoreIndentedLines");const nn=l((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),sn=l(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function za(s,e,t){if(!e||e<0)return!1;const n=e-t,r=s.length;if(r<=n)return!1;for(let i=0,o=0;i<r;++i)if(s[i]===`
17
+ `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}l(za,"lineLengthOverLimit");function Tt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(sn(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<r)c+=1;else{for(o+=t.slice(a,c)+`
18
+
19
+ `;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
20
+ `,c+=2;o+=i,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,n?o:tn(o,i,en,nn(e,!1))}l(Tt,"doubleQuotedString");function ns(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
21
+ `)||/[ \t]\n|\n[ \t]/.test(s))return Tt(s,e);const t=e.indent||(sn(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
22
+ ${t}`)+"'";return e.implicitKey?n:tn(n,t,Qr,nn(e,!1))}l(ns,"singleQuotedString");function ct(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Tt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=ns:i&&!r?n=Tt:n=t?ns:Tt}return n(s,e)}l(ct,"quotedString");let ss;try{ss=new RegExp(`(^|(?<!
23
23
  ))
24
24
  +(?!
25
- |$)`,"g")}catch{ss=/\n+(?!\n|$)/g}function rn({comment:s,type:e,value:t},n,r,i){const{blockQuote:o,commentString:a,lineWidth:l}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return ct(t,n);const u=n.indent||(n.forceBlockIndent||sn(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===D.BLOCK_FOLDED?!1:e===D.BLOCK_LITERAL?!0:!Ha(t,l,u.length);if(!t)return f?`|
25
+ |$)`,"g")}catch{ss=/\n+(?!\n|$)/g}function rn({comment:s,type:e,value:t},n,r,i){const{blockQuote:o,commentString:a,lineWidth:c}=n.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return ct(t,n);const u=n.indent||(n.forceBlockIndent||sn(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===L.BLOCK_FOLDED?!1:e===L.BLOCK_LITERAL?!0:!za(t,c,u.length);if(!t)return f?`|
26
26
  `:`>
27
27
  `;let d,h;for(h=t.length;h>0;--h){const P=t[h-1];if(P!==`
28
- `&&P!==" "&&P!==" ")break}let g=t.substring(h);const y=g.indexOf(`
29
- `);y===-1?d="-":t===g||y!==g.length-1?(d="+",i&&i()):d="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
30
- `&&(g=g.slice(0,-1)),g=g.replace(ss,`$&${u}`));let p=!1,w,k=-1;for(w=0;w<t.length;++w){const P=t[w];if(P===" ")p=!0;else if(P===`
31
- `)k=w;else break}let T=t.substring(0,k<w?k+1:w);T&&(t=t.substring(T.length),T=T.replace(/\n+/g,`$&${u}`));let I=(p?u?"2":"1":"")+d;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){const P=t.replace(/\n+/g,`
32
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let L=!1;const q=nn(n,!0);o!=="folded"&&e!==D.BLOCK_FOLDED&&(q.onOverflow=()=>{L=!0});const A=tn(`${T}${P}${g}`,u,ts,q);if(!L)return`>${I}
33
- ${u}${A}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
34
- ${u}${T}${t}${g}`}c(rn,"blockString");function Ya(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:f}=e;if(a&&i.includes(`
28
+ `&&P!==" "&&P!==" ")break}let g=t.substring(h);const w=g.indexOf(`
29
+ `);w===-1?d="-":t===g||w!==g.length-1?(d="+",i&&i()):d="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
30
+ `&&(g=g.slice(0,-1)),g=g.replace(ss,`$&${u}`));let p=!1,y,k=-1;for(y=0;y<t.length;++y){const P=t[y];if(P===" ")p=!0;else if(P===`
31
+ `)k=y;else break}let E=t.substring(0,k<y?k+1:y);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${u}`));let I=(p?u?"2":"1":"")+d;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){const P=t.replace(/\n+/g,`
32
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let R=!1;const J=nn(n,!0);o!=="folded"&&e!==L.BLOCK_FOLDED&&(J.onOverflow=()=>{R=!0});const $=tn(`${E}${P}${g}`,u,ts,J);if(!R)return`>${I}
33
+ ${u}${$}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
34
+ ${u}${E}${t}${g}`}l(rn,"blockString");function Ha(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:f}=e;if(a&&i.includes(`
35
35
  `)||f&&/[[\]{},]/.test(i))return ct(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
36
- `)?ct(i,e):rn(s,e,t,n);if(!a&&!f&&r!==D.PLAIN&&i.includes(`
37
- `))return rn(s,e,t,n);if(sn(i)){if(l==="")return e.forceBlockIndent=!0,rn(s,e,t,n);if(a&&l===u)return ct(i,e)}const d=i.replace(/\n+/g,`$&
38
- ${l}`);if(o){const h=c(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),"test"),{compat:g,tags:y}=e.doc.schema;if(y.some(h)||g?.some(h))return ct(i,e)}return a?d:tn(d,l,Qr,nn(e,!1))}c(Ya,"plainString");function It(s,e,t,n){const{implicitKey:r,inFlow:i}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==D.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=D.QUOTE_DOUBLE);const l=c(f=>{switch(f){case D.BLOCK_FOLDED:case D.BLOCK_LITERAL:return r||i?ct(o.value,e):rn(o,e,t,n);case D.QUOTE_DOUBLE:return Et(o.value,e);case D.QUOTE_SINGLE:return ns(o.value,e);case D.PLAIN:return Ya(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,h=r&&f||d;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(It,"stringifyString");function ei(s,e){const t=Object.assign({blockQuote:!0,commentString:za,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},s.schema.toStringOptions,e);let n;switch(t.collectionStyle){case"block":n=!1;break;case"flow":n=!0;break;default:n=null}return{anchors:new Set,doc:s,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:n,options:t}}c(ei,"createStringifyContext");function Za(s,e){if(e.tag){const r=s.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,n;if(J(e)){n=e.value;let r=s.filter(i=>i.identify?.(n));if(r.length>1){const i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,t=s.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!t){const r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return t}c(Za,"getTagObject");function Qa(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(J(s)||V(s))&&s.anchor;i&&Gr(i)&&(t.add(i),r.push(`&${i}`));const o=s.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}c(Qa,"stringifyProps");function lt(s,e,t,n){if(W(s))return s.toString(e,t,n);if(Ie(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 r;const i=G(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=Za(e.doc.schema.tags,i));const o=Qa(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof r.stringify=="function"?r.stringify(i,e,t,n):J(i)?It(i,e,t,n):i.toString(e,t,n);return o?J(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
39
- ${e.indent}${a}`:a}c(lt,"stringify$2");function Xa({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:f,simpleKeys:d}}=t;let h=G(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(V(s)||!G(s)&&typeof s=="object"){const q="With simple keys, collection cannot be used as a key value";throw new Error(q)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||V(s)||(J(s)?s.type===D.BLOCK_FOLDED||s.type===D.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!i),indent:a+l});let y=!1,p=!1,w=lt(s,t,()=>y=!0,()=>p=!0);if(!g&&!t.inFlow&&w.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":g?`? ${w}`:w}else if(i&&!d||e==null&&g)return w=`? ${w}`,h&&!y?w+=qe(w,t.indent,u(h)):p&&r&&r(),w;y&&(h=null),g?(h&&(w+=qe(w,t.indent,u(h))),w=`? ${w}
40
- ${a}:`):(w=`${w}:`,h&&(w+=qe(w,t.indent,u(h))));let k,T,$;G(e)?(k=!!e.spaceBefore,T=e.commentBefore,$=e.comment):(k=!1,T=null,$=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&J(e)&&(t.indentAtStart=w.length+1),p=!1,!f&&l.length>=2&&!t.inFlow&&!g&&rt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const P=lt(e,t,()=>I=!0,()=>p=!0);let L=" ";if(h||k||T){if(L=k?`
41
- `:"",T){const q=u(T);L+=`
42
- ${Se(q,t.indent)}`}P===""&&!t.inFlow?L===`
43
- `&&(L=`
44
-
45
- `):L+=`
46
- ${t.indent}`}else if(!g&&V(e)){const q=P[0],A=P.indexOf(`
47
- `),Y=A!==-1,Te=t.inFlow??e.flow??e.items.length===0;if(Y||!Te){let Ge=!1;if(Y&&(q==="&"||q==="!")){let Z=P.indexOf(" ");q==="&"&&Z!==-1&&Z<A&&P[Z+1]==="!"&&(Z=P.indexOf(" ",Z+1)),(Z===-1||A<Z)&&(Ge=!0)}Ge||(L=`
36
+ `)?ct(i,e):rn(s,e,t,n);if(!a&&!f&&r!==L.PLAIN&&i.includes(`
37
+ `))return rn(s,e,t,n);if(sn(i)){if(c==="")return e.forceBlockIndent=!0,rn(s,e,t,n);if(a&&c===u)return ct(i,e)}const d=i.replace(/\n+/g,`$&
38
+ ${c}`);if(o){const h=l(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(d),"test"),{compat:g,tags:w}=e.doc.schema;if(w.some(h)||g?.some(h))return ct(i,e)}return a?d:tn(d,c,Qr,nn(e,!1))}l(Ha,"plainString");function It(s,e,t,n){const{implicitKey:r,inFlow:i}=e,o=typeof s.value=="string"?s:Object.assign({},s,{value:String(s.value)});let{type:a}=s;a!==L.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=L.QUOTE_DOUBLE);const c=l(f=>{switch(f){case L.BLOCK_FOLDED:case L.BLOCK_LITERAL:return r||i?ct(o.value,e):rn(o,e,t,n);case L.QUOTE_DOUBLE:return Tt(o.value,e);case L.QUOTE_SINGLE:return ns(o.value,e);case L.PLAIN:return Ha(o,e,t,n);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,h=r&&f||d;if(u=c(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}l(It,"stringifyString");function ei(s,e){const t=Object.assign({blockQuote:!0,commentString:Ga,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(ei,"createStringifyContext");function Ya(s,e){if(e.tag){const r=s.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,n;if(U(e)){n=e.value;let r=s.filter(i=>i.identify?.(n));if(r.length>1){const i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else n=e,t=s.find(r=>r.nodeClass&&n instanceof r.nodeClass);if(!t){const r=n?.constructor?.name??(n===null?"null":typeof n);throw new Error(`Tag not resolved for ${r} value`)}return t}l(Ya,"getTagObject");function Za(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(U(s)||V(s))&&s.anchor;i&&Gr(i)&&(t.add(i),r.push(`&${i}`));const o=s.tag??(e.default?null:e.tag);return o&&r.push(n.directives.tagString(o)),r.join(" ")}l(Za,"stringifyProps");function lt(s,e,t,n){if(W(s))return s.toString(e,t,n);if(Ie(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 r;const i=G(s)?s:e.doc.createNode(s,{onTagObj:l(c=>r=c,"onTagObj")});r??(r=Ya(e.doc.schema.tags,i));const o=Za(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof r.stringify=="function"?r.stringify(i,e,t,n):U(i)?It(i,e,t,n):i.toString(e,t,n);return o?U(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
39
+ ${e.indent}${a}`:a}l(lt,"stringify$2");function Qa({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:f,simpleKeys:d}}=t;let h=G(s)&&s.comment||null;if(d){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(V(s)||!G(s)&&typeof s=="object"){const J="With simple keys, collection cannot be used as a key value";throw new Error(J)}}let g=!d&&(!s||h&&e==null&&!t.inFlow||V(s)||(U(s)?s.type===L.BLOCK_FOLDED||s.type===L.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(d||!i),indent:a+c});let w=!1,p=!1,y=lt(s,t,()=>w=!0,()=>p=!0);if(!g&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");g=!0}if(t.inFlow){if(i||e==null)return w&&n&&n(),y===""?"?":g?`? ${y}`:y}else if(i&&!d||e==null&&g)return y=`? ${y}`,h&&!w?y+=Be(y,t.indent,u(h)):p&&r&&r(),y;w&&(h=null),g?(h&&(y+=Be(y,t.indent,u(h))),y=`? ${y}
40
+ ${a}:`):(y=`${y}:`,h&&(y+=Be(y,t.indent,u(h))));let k,E,A;G(e)?(k=!!e.spaceBefore,E=e.commentBefore,A=e.comment):(k=!1,E=null,A=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&U(e)&&(t.indentAtStart=y.length+1),p=!1,!f&&c.length>=2&&!t.inFlow&&!g&&rt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const P=lt(e,t,()=>I=!0,()=>p=!0);let R=" ";if(h||k||E){if(R=k?`
41
+ `:"",E){const J=u(E);R+=`
42
+ ${Se(J,t.indent)}`}P===""&&!t.inFlow?R===`
43
+ `&&(R=`
44
+
45
+ `):R+=`
46
+ ${t.indent}`}else if(!g&&V(e)){const J=P[0],$=P.indexOf(`
47
+ `),Y=$!==-1,Ee=t.inFlow??e.flow??e.items.length===0;if(Y||!Ee){let Ge=!1;if(Y&&(J==="&"||J==="!")){let Z=P.indexOf(" ");J==="&"&&Z!==-1&&Z<$&&P[Z+1]==="!"&&(Z=P.indexOf(" ",Z+1)),(Z===-1||$<Z)&&(Ge=!0)}Ge||(R=`
48
48
  ${t.indent}`)}}else(P===""||P[0]===`
49
- `)&&(L="");return w+=L+P,t.inFlow?I&&n&&n():$&&!I?w+=qe(w,t.indent,u($)):p&&r&&r(),w}c(Xa,"stringifyPair");function ti(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(ti,"warn");const on="<<",Ce={identify:c(s=>s===on||typeof s=="symbol"&&s.description===on,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new D(Symbol(on)),{addToJSMap:ni}),"resolve"),stringify:c(()=>on,"stringify")},ec=c((s,e)=>(Ce.identify(e)||J(e)&&(!e.type||e.type===D.PLAIN)&&Ce.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===Ce.tag&&t.default),"isMergeKey");function ni(s,e,t){if(t=s&&Ie(t)?t.resolve(s.doc):t,rt(t))for(const n of t.items)rs(s,e,n);else if(Array.isArray(t))for(const n of t)rs(s,e,n);else rs(s,e,t)}c(ni,"addMergeToJSMap");function rs(s,e,t){const n=s&&Ie(t)?t.resolve(s.doc):t;if(!st(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,s,Map);for(const[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}c(rs,"mergeValue");function si(s,e,{key:t,value:n}){if(G(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(ec(s,t))ni(s,e,n);else{const r=ae(t,"",s);if(e instanceof Map)e.set(r,ae(n,r,s));else if(e instanceof Set)e.add(r);else{const i=tc(t,r,s),o=ae(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c(si,"addPairToJSMap");function tc(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(G(s)&&t?.doc){const n=ei(t.doc,{});n.anchors=new Set;for(const i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;const r=s.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),ti(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}c(tc,"stringifyKey");function is(s,e,t){const n=kt(s,void 0,t),r=kt(e,void 0,t);return new X(n,r)}c(is,"createPair");class X{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,oe,{value:qr}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return G(t)&&(t=t.clone(e)),G(n)&&(n=n.clone(e)),new X(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return si(t,n,this)}toString(e,t,n){return e?.doc?Xa(this,e,t,n):JSON.stringify(this)}}function ri(s,e,t){return(e.inFlow??s.flow?sc:nc)(s,e,t)}c(ri,"stringifyCollection");function nc({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,f=Object.assign({},t,{indent:i,type:null});let d=!1;const h=[];for(let y=0;y<e.length;++y){const p=e[y];let w=null;if(G(p))!d&&p.spaceBefore&&h.push(""),an(t,h,p.commentBefore,d),p.comment&&(w=p.comment);else if(W(p)){const T=G(p.key)?p.key:null;T&&(!d&&T.spaceBefore&&h.push(""),an(t,h,T.commentBefore,d))}d=!1;let k=lt(p,f,()=>w=null,()=>d=!0);w&&(k+=qe(k,i,u(w))),d&&w&&(d=!1),h.push(n+k)}let g;if(h.length===0)g=r.start+r.end;else{g=h[0];for(let y=1;y<h.length;++y){const p=h[y];g+=p?`
50
- ${l}${p}`:`
49
+ `)&&(R="");return y+=R+P,t.inFlow?I&&n&&n():A&&!I?y+=Be(y,t.indent,u(A)):p&&r&&r(),y}l(Qa,"stringifyPair");function ti(s,e){(s==="debug"||s==="warn")&&console.warn(e)}l(ti,"warn");const on="<<",Ce={identify:l(s=>s===on||typeof s=="symbol"&&s.description===on,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new L(Symbol(on)),{addToJSMap:ni}),"resolve"),stringify:l(()=>on,"stringify")},Xa=l((s,e)=>(Ce.identify(e)||U(e)&&(!e.type||e.type===L.PLAIN)&&Ce.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===Ce.tag&&t.default),"isMergeKey");function ni(s,e,t){if(t=s&&Ie(t)?t.resolve(s.doc):t,rt(t))for(const n of t.items)rs(s,e,n);else if(Array.isArray(t))for(const n of t)rs(s,e,n);else rs(s,e,t)}l(ni,"addMergeToJSMap");function rs(s,e,t){const n=s&&Ie(t)?t.resolve(s.doc):t;if(!st(n))throw new Error("Merge sources must be maps or map aliases");const r=n.toJSON(null,s,Map);for(const[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(rs,"mergeValue");function si(s,e,{key:t,value:n}){if(G(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Xa(s,t))ni(s,e,n);else{const r=ae(t,"",s);if(e instanceof Map)e.set(r,ae(n,r,s));else if(e instanceof Set)e.add(r);else{const i=ec(t,r,s),o=ae(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}l(si,"addPairToJSMap");function ec(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(G(s)&&t?.doc){const n=ei(t.doc,{});n.anchors=new Set;for(const i of t.anchors.keys())n.anchors.add(i.anchor);n.inFlow=!0,n.inStringifyKey=!0;const r=s.toString(n);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),ti(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}l(ec,"stringifyKey");function is(s,e,t){const n=kt(s,void 0,t),r=kt(e,void 0,t);return new X(n,r)}l(is,"createPair");class X{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,oe,{value:Br}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return G(t)&&(t=t.clone(e)),G(n)&&(n=n.clone(e)),new X(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return si(t,n,this)}toString(e,t,n){return e?.doc?Qa(this,e,t,n):JSON.stringify(this)}}function ri(s,e,t){return(e.inFlow??s.flow?nc:tc)(s,e,t)}l(ri,"stringifyCollection");function tc({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,f=Object.assign({},t,{indent:i,type:null});let d=!1;const h=[];for(let w=0;w<e.length;++w){const p=e[w];let y=null;if(G(p))!d&&p.spaceBefore&&h.push(""),an(t,h,p.commentBefore,d),p.comment&&(y=p.comment);else if(W(p)){const E=G(p.key)?p.key:null;E&&(!d&&E.spaceBefore&&h.push(""),an(t,h,E.commentBefore,d))}d=!1;let k=lt(p,f,()=>y=null,()=>d=!0);y&&(k+=Be(k,i,u(y))),d&&y&&(d=!1),h.push(n+k)}let g;if(h.length===0)g=r.start+r.end;else{g=h[0];for(let w=1;w<h.length;++w){const p=h[w];g+=p?`
50
+ ${c}${p}`:`
51
51
  `}}return s?(g+=`
52
- `+Se(u(s),l),a&&a()):d&&o&&o(),g}c(nc,"stringifyBlockCollection");function sc({items:s},e,{flowChars:t,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;const l=Object.assign({},e,{indent:n,inFlow:!0,type:null});let u=!1,f=0;const d=[];for(let y=0;y<s.length;++y){const p=s[y];let w=null;if(G(p))p.spaceBefore&&d.push(""),an(e,d,p.commentBefore,!1),p.comment&&(w=p.comment);else if(W(p)){const T=G(p.key)?p.key:null;T&&(T.spaceBefore&&d.push(""),an(e,d,T.commentBefore,!1),T.comment&&(u=!0));const $=G(p.value)?p.value:null;$?($.comment&&(w=$.comment),$.commentBefore&&(u=!0)):p.value==null&&T?.comment&&(w=T.comment)}w&&(u=!0);let k=lt(p,l,()=>w=null);y<s.length-1&&(k+=","),w&&(k+=qe(k,n,a(w))),!u&&(d.length>f||k.includes(`
53
- `))&&(u=!0),d.push(k),f=d.length}const{start:h,end:g}=t;if(d.length===0)return h+g;if(!u){const y=d.reduce((p,w)=>p+w.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=h;for(const p of d)y+=p?`
52
+ `+Se(u(s),c),a&&a()):d&&o&&o(),g}l(tc,"stringifyBlockCollection");function nc({items:s},e,{flowChars:t,itemIndent:n}){const{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;n+=i;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(G(p))p.spaceBefore&&d.push(""),an(e,d,p.commentBefore,!1),p.comment&&(y=p.comment);else if(W(p)){const E=G(p.key)?p.key:null;E&&(E.spaceBefore&&d.push(""),an(e,d,E.commentBefore,!1),E.comment&&(u=!0));const A=G(p.value)?p.value:null;A?(A.comment&&(y=A.comment),A.commentBefore&&(u=!0)):p.value==null&&E?.comment&&(y=E.comment)}y&&(u=!0);let k=lt(p,c,()=>y=null);w<s.length-1&&(k+=","),y&&(k+=Be(k,n,a(y))),!u&&(d.length>f||k.includes(`
53
+ `))&&(u=!0),d.push(k),f=d.length}const{start:h,end:g}=t;if(d.length===0)return h+g;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?`
54
54
  ${i}${r}${p}`:`
55
- `;return`${y}
56
- ${r}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}c(sc,"stringifyFlowCollection");function an({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Se(e(n),s);t.push(i.trimStart())}}c(an,"addCommentBefore");function Be(s,e){const t=J(e)?e.value:e;for(const n of s)if(W(n)&&(n.key===e||n.key===t||J(n.key)&&n.key.value===t))return n}c(Be,"findPair");class se extends Zr{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ee,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,o=new this(e),a=c((l,u)=>{if(typeof i=="function")u=i.call(t,l,u);else if(Array.isArray(i)&&!i.includes(l))return;(u!==void 0||r)&&o.items.push(is(l,u,n))},"add");if(t instanceof Map)for(const[l,u]of t)a(l,u);else if(t&&typeof t=="object")for(const l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;W(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new X(e,e?.value):n=new X(e.key,e.value);const r=Be(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);J(r.value)&&Yr(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=Be(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=Be(this.items,e)?.value;return(!t&&J(r)?r.value:r)??void 0}has(e){return!!Be(this.items,e)}set(e,t){this.add(new X(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const i of this.items)si(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!W(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} 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 ut={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return st(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>se.from(s,e,t),"createNode")};class Oe extends Zr{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(nt,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=cn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=cn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&J(r)?r.value:r}has(e){const t=cn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=cn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];J(r)&&Yr(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const i of this.items)n.push(ae(i,String(r++),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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){const l=t instanceof Set?a:String(o++);a=r.call(t,l,a)}i.items.push(kt(a,void 0,n))}}return i}}function cn(s){let e=J(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(cn,"asItemIndex");const ft={collection:"seq",default:!0,nodeClass:Oe,tag:"tag:yaml.org,2002:seq",resolve(s,e){return rt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Oe.from(s,e,t),"createNode")},ln={identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify(s,e,t,n){return e=Object.assign({actualString:!0},e),It(s,e,t,n)}},un={identify:c(s=>s==null,"identify"),createNode:c(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new D(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&un.test.test(s)?s:e.options.nullStr,"stringify")},os={identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:c(s=>new D(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&os.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 ue({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}c(ue,"stringifyNumber");const ii={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ue},oi={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ue(s)}},ai={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new D(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ue},fn=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),as=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function ci(s,e,t){const{value:n}=s;return fn(n)&&n>=0?t+n.toString(e):ue(s)}c(ci,"intStringify$1");const li={identify:c(s=>fn(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>as(s,2,8,t),"resolve"),stringify:c(s=>ci(s,8,"0o"),"stringify")},ui={identify:fn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>as(s,0,10,t),"resolve"),stringify:ue},fi={identify:c(s=>fn(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:c((s,e,t)=>as(s,2,16,t),"resolve"),stringify:c(s=>ci(s,16,"0x"),"stringify")},rc=[ut,ft,ln,un,os,li,ui,fi,ii,oi,ai];function di(s){return typeof s=="bigint"||Number.isInteger(s)}c(di,"intIdentify$1");const dn=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),ic=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:dn},{identify:c(s=>s==null,"identify"),createNode:c(()=>new D(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:dn},{identify:c(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:c(s=>s==="true","resolve"),stringify:dn},{identify:di,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:c((s,e,{intAsBigInt:t})=>t?BigInt(s):parseInt(s,10),"resolve"),stringify:c(({value:s})=>di(s)?s.toString():JSON.stringify(s),"stringify")},{identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:c(s=>parseFloat(s),"resolve"),stringify:dn}],oc={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},ac=[ut,ft].concat(ic,oc),cs={identify:c(s=>s instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(s,e){if(typeof atob=="function"){const t=atob(s.replace(/[\n\r]/g,"")),n=new Uint8Array(t.length);for(let r=0;r<t.length;++r)n[r]=t.charCodeAt(r);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,r,i){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let l="";for(let u=0;u<o.length;++u)l+=String.fromCharCode(o[u]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=D.BLOCK_LITERAL),e!==D.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),f=new Array(u);for(let d=0,h=0;d<u;++d,h+=l)f[d]=a.substr(h,l);a=f.join(e===D.BLOCK_LITERAL?`
57
- `:" ")}return It({comment:s,type:e,value:a},n,r,i)}};function hi(s,e){if(rt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!W(n)){if(st(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new X(new D(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
55
+ `;return`${w}
56
+ ${r}${g}`}else return`${h}${o}${d.join(" ")}${o}${g}`}l(nc,"stringifyFlowCollection");function an({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Se(e(n),s);t.push(i.trimStart())}}l(an,"addCommentBefore");function qe(s,e){const t=U(e)?e.value:e;for(const n of s)if(W(n)&&(n.key===e||n.key===t||U(n.key)&&n.key.value===t))return n}l(qe,"findPair");class se extends Zr{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Te,e),this.items=[]}static from(e,t,n){const{keepUndefined:r,replacer:i}=n,o=new this(e),a=l((c,u)=>{if(typeof i=="function")u=i.call(t,c,u);else if(Array.isArray(i)&&!i.includes(c))return;(u!==void 0||r)&&o.items.push(is(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;W(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new X(e,e?.value):n=new X(e.key,e.value);const r=qe(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);U(r.value)&&Yr(n.value)?r.value.value=n.value:r.value=n.value}else if(i){const o=this.items.findIndex(a=>i(n,a)<0);o===-1?this.items.push(n):this.items.splice(o,0,n)}else this.items.push(n)}delete(e){const t=qe(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=qe(this.items,e)?.value;return(!t&&U(r)?r.value:r)??void 0}has(e){return!!qe(this.items,e)}set(e,t){this.add(new X(e,t),!0)}toJSON(e,t,n){const r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(const i of this.items)si(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!W(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} 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 ut={collection:"map",default:!0,nodeClass:se,tag:"tag:yaml.org,2002:map",resolve(s,e){return st(s)||e("Expected a mapping for this tag"),s},createNode:l((s,e,t)=>se.from(s,e,t),"createNode")};class Oe extends Zr{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(nt,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=cn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=cn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&U(r)?r.value:r}has(e){const t=cn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=cn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];U(r)&&Yr(t)?r.value=t:this.items[n]=t}toJSON(e,t){const n=[];t?.onCreate&&t.onCreate(n);let r=0;for(const i of this.items)n.push(ae(i,String(r++),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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){const c=t instanceof Set?a:String(o++);a=r.call(t,c,a)}i.items.push(kt(a,void 0,n))}}return i}}function cn(s){let e=U(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l(cn,"asItemIndex");const ft={collection:"seq",default:!0,nodeClass:Oe,tag:"tag:yaml.org,2002:seq",resolve(s,e){return rt(s)||e("Expected a sequence for this tag"),s},createNode:l((s,e,t)=>Oe.from(s,e,t),"createNode")},ln={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),It(s,e,t,n)}},un={identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new L(null),"resolve"),stringify:l(({source:s},e)=>typeof s=="string"&&un.test.test(s)?s:e.options.nullStr,"stringify")},os={identify:l(s=>typeof s=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(s=>new L(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&os.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 ue({format:s,minFractionDigits:e,tag:t,value:n}){if(typeof n=="bigint")return String(n);const r=typeof n=="number"?n:Number(n);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=JSON.stringify(n);if(!s&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}l(ue,"stringifyNumber");const ii={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ue},oi={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ue(s)}},ai={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(s){const e=new L(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:ue},fn=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),as=l((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function ci(s,e,t){const{value:n}=s;return fn(n)&&n>=0?t+n.toString(e):ue(s)}l(ci,"intStringify$1");const li={identify:l(s=>fn(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((s,e,t)=>as(s,2,8,t),"resolve"),stringify:l(s=>ci(s,8,"0o"),"stringify")},ui={identify:fn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((s,e,t)=>as(s,0,10,t),"resolve"),stringify:ue},fi={identify:l(s=>fn(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)=>as(s,2,16,t),"resolve"),stringify:l(s=>ci(s,16,"0x"),"stringify")},sc=[ut,ft,ln,un,os,li,ui,fi,ii,oi,ai];function di(s){return typeof s=="bigint"||Number.isInteger(s)}l(di,"intIdentify$1");const dn=l(({value:s})=>JSON.stringify(s),"stringifyJSON"),rc=[{identify:l(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(s=>s,"resolve"),stringify:dn},{identify:l(s=>s==null,"identify"),createNode:l(()=>new L(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:dn},{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:dn},{identify:di,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})=>di(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:dn}],ic={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},oc=[ut,ft].concat(rc,ic),cs={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 r=0;r<t.length;++r)n[r]=t.charCodeAt(r);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,r,i){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=L.BLOCK_LITERAL),e!==L.QUOTE_DOUBLE){const c=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/c),f=new Array(u);for(let d=0,h=0;d<u;++d,h+=c)f[d]=a.substr(h,c);a=f.join(e===L.BLOCK_LITERAL?`
57
+ `:" ")}return It({comment:s,type:e,value:a},n,r,i)}};function hi(s,e){if(rt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!W(n)){if(st(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new X(new L(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
58
58
  ${r.key.commentBefore}`:n.commentBefore),n.comment){const i=r.value??r.key;i.comment=i.comment?`${n.comment}
59
- ${i.comment}`:n.comment}n=r}s.items[t]=W(n)?n:new X(n)}}else e("Expected a sequence for this tag");return s}c(hi,"resolvePairs");function pi(s,e,t){const{replacer:n}=t,r=new Oe(s);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;r.items.push(is(a,l,t))}return r}c(pi,"createPairs");const ls={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hi,createNode:pi};class wt extends Oe{static{c(this,"YAMLOMap")}constructor(){super(),this.add=se.prototype.add.bind(this),this.delete=se.prototype.delete.bind(this),this.get=se.prototype.get.bind(this),this.has=se.prototype.has.bind(this),this.set=se.prototype.set.bind(this),this.tag=wt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const r of this.items){let i,o;if(W(r)?(i=ae(r.key,"",t),o=ae(r.value,i,t)):i=ae(r,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){const r=pi(e,t,n),i=new this;return i.items=r.items,i}}wt.tag="tag:yaml.org,2002:omap";const us={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=hi(s,e),n=[];for(const{key:r}of t.items)J(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new wt,t)},createNode:c((s,e,t)=>wt.from(s,e,t),"createNode")};function mi({value:s,source:e},t){return e&&(s?gi:yi).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(mi,"boolStringify");const gi={identify:c(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:c(()=>new D(!0),"resolve"),stringify:mi},yi={identify:c(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:c(()=>new D(!1),"resolve"),stringify:mi},cc={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ue},lc={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ue(s)}},uc={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new D(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ue},Ot=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function hn(s,e,t,{intAsBigInt:n}){const r=s[0];if((r==="-"||r==="+")&&(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 r==="-"?BigInt(-1)*o:o}const i=parseInt(s,t);return r==="-"?-1*i:i}c(hn,"intResolve");function fs(s,e,t){const{value:n}=s;if(Ot(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return ue(s)}c(fs,"intStringify");const fc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>hn(s,2,2,t),"resolve"),stringify:c(s=>fs(s,2,"0b"),"stringify")},dc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>hn(s,1,8,t),"resolve"),stringify:c(s=>fs(s,8,"0"),"stringify")},hc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>hn(s,0,10,t),"resolve"),stringify:ue},pc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>hn(s,2,16,t),"resolve"),stringify:c(s=>fs(s,16,"0x"),"stringify")};class bt extends se{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=bt.tag}add(e){let t;W(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new X(e.key,null):t=new X(e,null),Be(this.items,t.key)||this.items.push(t)}get(e,t){const n=Be(this.items,e);return!t&&W(n)?J(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=Be(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new X(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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(is(o,null,n));return i}}bt.tag="tag:yaml.org,2002:set";const ds={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:bt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>bt.from(s,e,t),"createNode"),resolve(s,e){if(st(s)){if(s.hasAllNullValues(!0))return Object.assign(new bt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function hs(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,r=c(o=>e?BigInt(o):Number(o),"num"),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}c(hs,"parseSexagesimal");function wi(s){let{value:e}=s,t=c(o=>o,"num");if(typeof e=="bigint")t=c(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return ue(s);let n="";e<0&&(n="-",e*=t(-1));const r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(wi,"stringifySexagesimal");const bi={identify:c(s=>typeof s=="bigint"||Number.isInteger(s),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:c((s,e,{intAsBigInt:t})=>hs(s,t),"resolve"),stringify:wi},Si={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:c(s=>hs(s,!1),"resolve"),stringify:wi},pn={identify:c(s=>s instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(s){const e=s.match(pn.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,r,i||0,o||0,a||0,l);const f=e[8];if(f&&f!=="Z"){let d=hs(f,!1);Math.abs(d)<30&&(d*=60),u-=6e4*d}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Ci=[ut,ft,ln,un,gi,yi,fc,dc,hc,pc,cc,lc,uc,cs,Ce,us,ls,ds,bi,Si,pn],vi=new Map([["core",rc],["failsafe",[ut,ft,ln]],["json",ac],["yaml11",Ci],["yaml-1.1",Ci]]),ki={binary:cs,bool:os,float:ai,floatExp:oi,floatNaN:ii,floatTime:Si,int:ui,intHex:fi,intOct:li,intTime:bi,map:ut,merge:Ce,null:un,omap:us,pairs:ls,seq:ft,set:ds,timestamp:pn},mc={"tag:yaml.org,2002:binary":cs,"tag:yaml.org,2002:merge":Ce,"tag:yaml.org,2002:omap":us,"tag:yaml.org,2002:pairs":ls,"tag:yaml.org,2002:set":ds,"tag:yaml.org,2002:timestamp":pn};function ps(s,e,t){const n=vi.get(e);if(n&&!s)return t&&!n.includes(Ce)?n.concat(Ce):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(vi.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(s))for(const i of s)r=r.concat(i);else typeof s=="function"&&(r=s(r.slice()));return t&&(r=r.concat(Ce)),r.reduce((i,o)=>{const a=typeof o=="string"?ki[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(ki).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(ps,"getTags");const gc=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class An{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ps(e,"compat"):e?ps(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?mc:{},this.tags=ps(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ee,{value:ut}),Object.defineProperty(this,me,{value:ln}),Object.defineProperty(this,nt,{value:ft}),this.sortMapEntries=typeof o=="function"?o:o===!0?gc:null}clone(){const e=Object.create(An.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function yc(s,e){const t=[];let n=e.directives===!0;if(e.directives!==!1&&s.directives){const l=s.directives.toString(s);l?(t.push(l),n=!0):s.directives.docStart&&(n=!0)}n&&t.push("---");const r=ei(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(Se(l,""))}let o=!1,a=null;if(s.contents){if(G(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=i(s.contents.commentBefore);t.push(Se(f,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=lt(s.contents,r,()=>a=null,l);a&&(u+=qe(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(lt(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
60
- `)?(t.push("..."),t.push(Se(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=s.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Se(i(l),"")))}return t.join(`
59
+ ${i.comment}`:n.comment}n=r}s.items[t]=W(n)?n:new X(n)}}else e("Expected a sequence for this tag");return s}l(hi,"resolvePairs");function pi(s,e,t){const{replacer:n}=t,r=new Oe(s);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof n=="function"&&(o=n.call(e,String(i++),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;r.items.push(is(a,c,t))}return r}l(pi,"createPairs");const ls={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:hi,createNode:pi};class wt extends Oe{static{l(this,"YAMLOMap")}constructor(){super(),this.add=se.prototype.add.bind(this),this.delete=se.prototype.delete.bind(this),this.get=se.prototype.get.bind(this),this.has=se.prototype.has.bind(this),this.set=se.prototype.set.bind(this),this.tag=wt.tag}toJSON(e,t){if(!t)return super.toJSON(e);const n=new Map;t?.onCreate&&t.onCreate(n);for(const r of this.items){let i,o;if(W(r)?(i=ae(r.key,"",t),o=ae(r.value,i,t)):i=ae(r,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,o)}return n}static from(e,t,n){const r=pi(e,t,n),i=new this;return i.items=r.items,i}}wt.tag="tag:yaml.org,2002:omap";const us={collection:"seq",identify:l(s=>s instanceof Map,"identify"),nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=hi(s,e),n=[];for(const{key:r}of t.items)U(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new wt,t)},createNode:l((s,e,t)=>wt.from(s,e,t),"createNode")};function mi({value:s,source:e},t){return e&&(s?gi:yi).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}l(mi,"boolStringify");const gi={identify:l(s=>s===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new L(!0),"resolve"),stringify:mi},yi={identify:l(s=>s===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new L(!1),"resolve"),stringify:mi},ac={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:ue},cc={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():ue(s)}},lc={identify:l(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(s){const e=new L(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:ue},Ot=l(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function hn(s,e,t,{intAsBigInt:n}){const r=s[0];if((r==="-"||r==="+")&&(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 r==="-"?BigInt(-1)*o:o}const i=parseInt(s,t);return r==="-"?-1*i:i}l(hn,"intResolve");function fs(s,e,t){const{value:n}=s;if(Ot(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return ue(s)}l(fs,"intStringify");const uc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((s,e,t)=>hn(s,2,2,t),"resolve"),stringify:l(s=>fs(s,2,"0b"),"stringify")},fc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((s,e,t)=>hn(s,1,8,t),"resolve"),stringify:l(s=>fs(s,8,"0"),"stringify")},dc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((s,e,t)=>hn(s,0,10,t),"resolve"),stringify:ue},hc={identify:Ot,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((s,e,t)=>hn(s,2,16,t),"resolve"),stringify:l(s=>fs(s,16,"0x"),"stringify")};class bt extends se{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=bt.tag}add(e){let t;W(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new X(e.key,null):t=new X(e,null),qe(this.items,t.key)||this.items.push(t)}get(e,t){const n=qe(this.items,e);return!t&&W(n)?U(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=qe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new X(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:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(is(o,null,n));return i}}bt.tag="tag:yaml.org,2002:set";const ds={collection:"map",identify:l(s=>s instanceof Set,"identify"),nodeClass:bt,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((s,e,t)=>bt.from(s,e,t),"createNode"),resolve(s,e){if(st(s)){if(s.hasAllNullValues(!0))return Object.assign(new bt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function hs(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,r=l(o=>e?BigInt(o):Number(o),"num"),i=n.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}l(hs,"parseSexagesimal");function wi(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 ue(s);let n="";e<0&&(n="-",e*=t(-1));const r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l(wi,"stringifySexagesimal");const bi={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})=>hs(s,t),"resolve"),stringify:wi},Si={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=>hs(s,!1),"resolve"),stringify:wi},pn={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(pn.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,r,i,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,r,i||0,o||0,a||0,c);const f=e[8];if(f&&f!=="Z"){let d=hs(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=[ut,ft,ln,un,gi,yi,uc,fc,dc,hc,ac,cc,lc,cs,Ce,us,ls,ds,bi,Si,pn],vi=new Map([["core",sc],["failsafe",[ut,ft,ln]],["json",oc],["yaml11",Ci],["yaml-1.1",Ci]]),ki={binary:cs,bool:os,float:ai,floatExp:oi,floatNaN:ii,floatTime:Si,int:ui,intHex:fi,intOct:li,intTime:bi,map:ut,merge:Ce,null:un,omap:us,pairs:ls,seq:ft,set:ds,timestamp:pn},pc={"tag:yaml.org,2002:binary":cs,"tag:yaml.org,2002:merge":Ce,"tag:yaml.org,2002:omap":us,"tag:yaml.org,2002:pairs":ls,"tag:yaml.org,2002:set":ds,"tag:yaml.org,2002:timestamp":pn};function ps(s,e,t){const n=vi.get(e);if(n&&!s)return t&&!n.includes(Ce)?n.concat(Ce):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(vi.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(s))for(const i of s)r=r.concat(i);else typeof s=="function"&&(r=s(r.slice()));return t&&(r=r.concat(Ce)),r.reduce((i,o)=>{const a=typeof o=="string"?ki[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(ki).map(f=>JSON.stringify(f)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}l(ps,"getTags");const mc=l((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class An{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ps(e,"compat"):e?ps(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?pc:{},this.tags=ps(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Te,{value:ut}),Object.defineProperty(this,me,{value:ln}),Object.defineProperty(this,nt,{value:ft}),this.sortMapEntries=typeof o=="function"?o:o===!0?mc:null}clone(){const e=Object.create(An.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function gc(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 r=ei(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const c=i(s.commentBefore);t.unshift(Se(c,""))}let o=!1,a=null;if(s.contents){if(G(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=i(s.contents.commentBefore);t.push(Se(f,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const c=a?void 0:()=>o=!0;let u=lt(s.contents,r,()=>a=null,c);a&&(u+=Be(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(lt(s.contents,r));if(s.directives?.docEnd)if(s.comment){const c=i(s.comment);c.includes(`
60
+ `)?(t.push("..."),t.push(Se(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(Se(i(c),"")))}return t.join(`
61
61
  `)+`
62
- `}c(yc,"stringifyDocument");class St{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:Xn});let r=null;typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ee({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(St.prototype,{[oe]:{value:Xn}});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=G(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){dt(this.contents)&&this.contents.add(e)}addIn(e,t){dt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=zr(this);e.anchor=!t||n.has(t)?Hr(t||"a",n):t}return new Zt(e.anchor)}createNode(e,t,n){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const w=c(T=>typeof T=="number"||T instanceof String||T instanceof Number,"keyToStr"),k=t.filter(w).map(String);k.length>0&&(t=t.concat(k)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:u,tag:f}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=Wa(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:g},p=kt(e,f,y);return a&&V(p)&&(p.flow=!0),h(),p}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new X(r,i)}delete(e){return dt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Tt(e)?this.contents==null?!1:(this.contents=null,!0):dt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return V(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Tt(e)?!t&&J(this.contents)?this.contents.value:this.contents:V(this.contents)?this.contents.getIn(e,t):void 0}has(e){return V(this.contents)?this.contents.has(e):!1}hasIn(e){return Tt(e)?this.contents!==void 0:V(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Xt(this.schema,[e],t):dt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Tt(e)?this.contents=t:this.contents==null?this.contents=Xt(this.schema,Array.from(e),t):dt(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 ee({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 ee({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new An(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:r,onAnchor:i,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=ae(this.contents,t??"",a);if(typeof i=="function")for(const{count:u,res:f}of a.anchors.values())i(f,u);return typeof o=="function"?at(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return yc(this,e)}}function dt(s){if(V(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(dt,"assertCollection");class ms extends Error{static{c(this,"YAMLError")}constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Ue extends ms{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ti extends ms{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const mn=c((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:r}=t.linePos[0];t.message+=` at line ${n}, column ${r}`;let i=r-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
63
- `),o=a+o}if(/[^ ]/.test(o)){let a=1;const l=t.linePos[1];l&&l.line===n&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-i)));const u=" ".repeat(i)+"^".repeat(a);t.message+=`:
62
+ `}l(gc,"stringifyDocument");class St{static{l(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,oe,{value:Xn});let r=null;typeof t=="function"||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);const i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},n);this.options=i;let{version:o}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new ee({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(St.prototype,{[oe]:{value:Xn}});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=G(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){dt(this.contents)&&this.contents.add(e)}addIn(e,t){dt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=zr(this);e.anchor=!t||n.has(t)?Hr(t||"a",n):t}return new Zt(e.anchor)}createNode(e,t,n){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){const y=l(E=>typeof E=="number"||E instanceof String||E instanceof Number,"keyToStr"),k=t.filter(y).map(String);k.length>0&&(t=t.concat(k)),r=t}else n===void 0&&t&&(n=t,t=void 0);const{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:f}=n??{},{onAnchor:d,setAnchors:h,sourceObjects:g}=Ja(this,o||"a"),w={aliasDuplicateObjects:i??!0,keepUndefined:c??!1,onAnchor:d,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:g},p=kt(e,f,w);return a&&V(p)&&(p.flow=!0),h(),p}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new X(r,i)}delete(e){return dt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Et(e)?this.contents==null?!1:(this.contents=null,!0):dt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return V(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Et(e)?!t&&U(this.contents)?this.contents.value:this.contents:V(this.contents)?this.contents.getIn(e,t):void 0}has(e){return V(this.contents)?this.contents.has(e):!1}hasIn(e){return Et(e)?this.contents!==void 0:V(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Xt(this.schema,[e],t):dt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Et(e)?this.contents=t:this.contents==null?this.contents=Xt(this.schema,Array.from(e),t):dt(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 ee({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 ee({version:e}),n={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,n=null;break;default:{const r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new An(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:r,onAnchor:i,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},c=ae(this.contents,t??"",a);if(typeof i=="function")for(const{count:u,res:f}of a.anchors.values())i(f,u);return typeof o=="function"?at(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 gc(this,e)}}function dt(s){if(V(s))return!0;throw new Error("Expected a YAML collection as document contents")}l(dt,"assertCollection");class ms extends Error{static{l(this,"YAMLError")}constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}}class Ue extends ms{static{l(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Ei extends ms{static{l(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const mn=l((s,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:n,col:r}=t.linePos[0];t.message+=` at line ${n}, column ${r}`;let i=r-1,o=s.substring(e.lineStarts[n-1],e.lineStarts[n]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){const a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),n>1&&/^ *$/.test(o.substring(0,i))){let a=s.substring(e.lineStarts[n-2],e.lineStarts[n-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
63
+ `),o=a+o}if(/[^ ]/.test(o)){let a=1;const c=t.linePos[1];c&&c.line===n&&c.col>r&&(a=Math.max(1,Math.min(c.col-r,80-i)));const u=" ".repeat(i)+"^".repeat(a);t.message+=`:
64
64
 
65
65
  ${o}
66
66
  ${u}
67
- `}},"prettifyError");function ht(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,f=a,d="",h="",g=!1,y=!1,p=null,w=null,k=null,T=null,$=null,I=null,P=null;for(const A of s)switch(y&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),y=!1),p&&(u&&A.type!=="comment"&&A.type!=="newline"&&i(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||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const Y=A.source.substring(1)||" ";d?d+=h+Y:d=Y,h="",u=!1;break}case"newline":u?d?d+=A.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=A.source,u=!0,g=!0,(w||k)&&(T=A),f=!0;break;case"anchor":w&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),w=A,P??(P=A.offset),u=!1,f=!1,y=!0;break;case"tag":{k&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),k=A,P??(P=A.offset),u=!1,f=!1,y=!0;break}case t:(w||k)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),I&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),I=A,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){$&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),$=A,u=!1,f=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,f=!1}const L=s[s.length-1],q=L?L.offset+L.source.length:r;return y&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(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")&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:$,found:I,spaceBefore:l,comment:d,hasNewline:g,anchor:w,tag:k,newlineAfterProp:T,end:q,start:P??q}}c(ht,"resolveProps");function At(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
68
- `))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(At(e.key)||At(e.value))return!0}return!1;default:return!0}}c(At,"containsNewline");function gs(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&At(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(gs,"flowIndentCheck");function Ei(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||J(i)&&J(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(Ei,"mapIncludes");const Ii="All mapping items must start at the same column";function wc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??se,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const f of n.items){const{start:d,key:h,sep:g,value:y}=f,p=ht(d,{indicator:"explicit-key-ind",next:h??g?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!p.found;if(w){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&r(l,"BAD_INDENT",Ii)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
69
- `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||At(h))&&r(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(l,"BAD_INDENT",Ii);t.atKey=!0;const k=p.end,T=h?s(t,h,p,r):e(t,k,d,null,p,r);t.schema.compat&&gs(n.indent,h,r),t.atKey=!1,Ei(t,a.items,T)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const $=ht(g??[],{indicator:"map-value-ind",next:y,offset:T.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=$.end,$.found){w&&(y?.type==="block-map"&&!$.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<$.found.offset-1024&&r(T.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=y?s(t,y,$,r):e(t,l,g,null,$,r);t.schema.compat&&gs(n.indent,y,r),l=I.range[2];const P=new X(T,I);t.options.keepSourceTokens&&(P.srcToken=f),a.items.push(P)}else{w&&r(T.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),$.comment&&(T.comment?T.comment+=`
70
- `+$.comment:T.comment=$.comment);const I=new X(T);t.options.keepSourceTokens&&(I.srcToken=f),a.items.push(I)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(wc,"resolveBlockMap");function bc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Oe,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:f,value:d}of n.items){const h=ht(f,{indicator:"seq-item-ind",next:d,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d&&d.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=d?s(t,d,h,r):e(t,h.end,f,null,h,r);t.schema.compat&&gs(n.indent,d,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(bc,"resolveBlockSeq");function $t(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:l,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const f=l.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=l),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=l.length}}return{comment:r,offset:e}}c($t,"resolveEnd");const ys="Block collections are not allowed within flow collections",ws=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Sc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?se:Oe),u=new l(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 w=0;w<n.items.length;++w){const k=n.items[w],{start:T,key:$,sep:I,value:P}=k,L=ht(T,{flow:a,indicator:"explicit-key-ind",next:$??I?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!L.found){if(!L.anchor&&!L.tag&&!I&&!P){w===0&&L.comma?r(L.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(L.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),L.comment&&(u.comment?u.comment+=`
71
- `+L.comment:u.comment=L.comment),d=L.end;continue}!o&&t.options.strict&&At($)&&r($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)L.comma&&r(L.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(L.comma||r(L.start,"MISSING_CHAR",`Missing , between ${a} items`),L.comment){let q="";e:for(const A of T)switch(A.type){case"comma":case"space":break;case"comment":q=A.source.substring(1);break e;default:break e}if(q){let A=u.items[u.items.length-1];W(A)&&(A=A.value??A.key),A.comment?A.comment+=`
72
- `+q:A.comment=q,L.comment=L.comment.substring(q.length+1)}}if(!o&&!I&&!L.found){const q=P?s(t,P,L,r):e(t,L.end,I,null,L,r);u.items.push(q),d=q.range[2],ws(P)&&r(q.range,"BLOCK_IN_FLOW",ys)}else{t.atKey=!0;const q=L.end,A=$?s(t,$,L,r):e(t,q,T,null,L,r);ws($)&&r(A.range,"BLOCK_IN_FLOW",ys),t.atKey=!1;const Y=ht(I??[],{flow:a,indicator:"map-value-ind",next:P,offset:A.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(Y.found){if(!o&&!L.found&&t.options.strict){if(I)for(const Z of I){if(Z===Y.found)break;if(Z.type==="newline"){r(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}L.start<Y.found.offset-1024&&r(Y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else P&&("source"in P&&P.source&&P.source[0]===":"?r(P,"MISSING_CHAR",`Missing space after : in ${a}`):r(Y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Te=P?s(t,P,Y,r):Y.found?e(t,Y.end,I,null,Y,r):null;Te?ws(P)&&r(Te.range,"BLOCK_IN_FLOW",ys):Y.comment&&(A.comment?A.comment+=`
73
- `+Y.comment:A.comment=Y.comment);const Ge=new X(A,Te);if(t.options.keepSourceTokens&&(Ge.srcToken=k),o){const Z=u;Ei(t,Z.items,A)&&r(q,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(Ge)}else{const Z=new se(t.schema);Z.flow=!0,Z.items.push(Ge);const Hs=(Te??A).range;Z.range=[A.range[0],Hs[1],Hs[2]],u.items.push(Z)}d=Te?Te.range[2]:Y.end}}const h=o?"}":"]",[g,...y]=n.end;let p=d;if(g&&g.source===h)p=g.offset+g.source.length;else{const w=a[0].toUpperCase()+a.substring(1),k=f?`${w} must end with a ${h}`:`${w} in block collection must be sufficiently indented and end with a ${h}`;r(d,f?"MISSING_CHAR":"BAD_INDENT",k),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){const w=$t(y,p,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
74
- `+w.comment:u.comment=w.comment),u.range=[n.offset,p,w.offset]}else u.range=[n.offset,p,p];return u}c(Sc,"resolveFlowCollection");function bs(s,e,t,n,r,i){const o=t.type==="block-map"?wc(s,e,t,n,i):t.type==="block-seq"?bc(s,e,t,n,i):Sc(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(bs,"resolveCollection");function Cc(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,y=h&&i?h.offset>i.offset?h:i:h??i;y&&(!g||g.offset<y.offset)&&r(y,"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(!i||!o||o==="!"||o===se.tagName&&a==="map"||o===Oe.tagName&&a==="seq")return bs(s,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),bs(s,e,t,r,o)}const u=bs(s,e,t,r,o,l),f=l.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,d=G(f)?f:new D(f);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(Cc,"composeCollection");function Oi(s,e,t){const n=e.offset,r=vc(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?D.BLOCK_FOLDED:D.BLOCK_LITERAL,o=e.source?kc(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const w=o[p][1];if(w===""||w==="\r")a=p;else break}if(a===0){const p=r.chomp==="+"&&o.length>0?`
75
- `.repeat(Math.max(1,o.length-1)):"";let w=n+r.length;return e.source&&(w+=e.source.length),{value:p,type:i,comment:r.comment,range:[n,w,w]}}let l=e.indent+r.indent,u=e.offset+r.length,f=0;for(let p=0;p<a;++p){const[w,k]=o[p];if(k===""||k==="\r")r.indent===0&&w.length>l&&(l=w.length);else{w.length<l&&t(u+w.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=w.length),f=p,l===0&&!s.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=w.length+k.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>l&&(a=p+1);let d="",h="",g=!1;for(let p=0;p<f;++p)d+=o[p][0].slice(l)+`
76
- `;for(let p=f;p<a;++p){let[w,k]=o[p];u+=w.length+k.length+1;const T=k[k.length-1]==="\r";if(T&&(k=k.slice(0,-1)),k&&w.length<l){const I=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-k.length-(T?2:1),"BAD_INDENT",I),w=""}i===D.BLOCK_LITERAL?(d+=h+w.slice(l)+k,h=`
77
- `):w.length>l||k[0]===" "?(h===" "?h=`
67
+ `}},"prettifyError");function ht(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let c=!1,u=a,f=a,d="",h="",g=!1,w=!1,p=null,y=null,k=null,E=null,A=null,I=null,P=null;for(const $ of s)switch(w&&($.type!=="space"&&$.type!=="newline"&&$.type!=="comma"&&i($.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(u&&$.type!=="comment"&&$.type!=="newline"&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),$.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&$.source.includes(" ")&&(p=$),f=!0;break;case"comment":{f||i($,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const Y=$.source.substring(1)||" ";d?d+=h+Y:d=Y,h="",u=!1;break}case"newline":u?d?d+=$.source:(!I||t!=="seq-item-ind")&&(c=!0):h+=$.source,u=!0,g=!0,(y||k)&&(E=$),f=!0;break;case"anchor":y&&i($,"MULTIPLE_ANCHORS","A node can have at most one anchor"),$.source.endsWith(":")&&i($.offset+$.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=$,P??(P=$.offset),u=!1,f=!1,w=!0;break;case"tag":{k&&i($,"MULTIPLE_TAGS","A node can have at most one tag"),k=$,P??(P=$.offset),u=!1,f=!1,w=!0;break}case t:(y||k)&&i($,"BAD_PROP_ORDER",`Anchors and tags must be after the ${$.source} indicator`),I&&i($,"UNEXPECTED_TOKEN",`Unexpected ${$.source} in ${e??"collection"}`),I=$,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){A&&i($,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),A=$,u=!1,f=!1;break}default:i($,"UNEXPECTED_TOKEN",`Unexpected ${$.type} token`),u=!1,f=!1}const R=s[s.length-1],J=R?R.offset+R.source.length:r;return w&&n&&n.type!=="space"&&n.type!=="newline"&&n.type!=="comma"&&(n.type!=="scalar"||n.source!=="")&&i(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")&&i(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:A,found:I,spaceBefore:c,comment:d,hasNewline:g,anchor:y,tag:k,newlineAfterProp:E,end:J,start:P??J}}l(ht,"resolveProps");function At(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
68
+ `))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(At(e.key)||At(e.value))return!0}return!1;default:return!0}}l(At,"containsNewline");function gs(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&At(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(gs,"flowIndentCheck");function Ti(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||U(i)&&U(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}l(Ti,"mapIncludes");const Ii="All mapping items must start at the same column";function yc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??se,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=n.offset,u=null;for(const f of n.items){const{start:d,key:h,sep:g,value:w}=f,p=ht(d,{indicator:"explicit-key-ind",next:h??g?.[0],offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0}),y=!p.found;if(y){if(h&&(h.type==="block-seq"?r(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==n.indent&&r(c,"BAD_INDENT",Ii)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
69
+ `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||At(h))&&r(h??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(c,"BAD_INDENT",Ii);t.atKey=!0;const k=p.end,E=h?s(t,h,p,r):e(t,k,d,null,p,r);t.schema.compat&&gs(n.indent,h,r),t.atKey=!1,Ti(t,a.items,E)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const A=ht(g??[],{indicator:"map-value-ind",next:w,offset:E.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(c=A.end,A.found){y&&(w?.type==="block-map"&&!A.hasNewline&&r(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<A.found.offset-1024&&r(E.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const I=w?s(t,w,A,r):e(t,c,g,null,A,r);t.schema.compat&&gs(n.indent,w,r),c=I.range[2];const P=new X(E,I);t.options.keepSourceTokens&&(P.srcToken=f),a.items.push(P)}else{y&&r(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),A.comment&&(E.comment?E.comment+=`
70
+ `+A.comment:E.comment=A.comment);const I=new X(E);t.options.keepSourceTokens&&(I.srcToken=f),a.items.push(I)}}return u&&u<c&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,c,u??c],a}l(yc,"resolveBlockMap");function wc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Oe,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=ht(f,{indicator:"seq-item-ind",next:d,offset:c,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||d)d&&d.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(c,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const g=d?s(t,d,h,r):e(t,h.end,f,null,h,r);t.schema.compat&&gs(n.indent,d,r),c=g.range[2],a.items.push(g)}return a.range=[n.offset,c,u??c],a}l(wc,"resolveBlockSeq");function $t(s,e,t,n){let r="";if(s){let i=!1,o="";for(const a of s){const{source:c,type:u}=a;switch(u){case"space":i=!0;break;case"comment":{t&&!i&&n(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const f=c.substring(1)||" ";r?r+=o+f:r=f,o="";break}case"newline":r&&(o+=c),i=!0;break;default:n(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:r,offset:e}}l($t,"resolveEnd");const ys="Block collections are not allowed within flow collections",ws=l(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function bc({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",c=i?.nodeClass??(o?se:Oe),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 k=n.items[y],{start:E,key:A,sep:I,value:P}=k,R=ht(E,{flow:a,indicator:"explicit-key-ind",next:A??I?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!R.found){if(!R.anchor&&!R.tag&&!I&&!P){y===0&&R.comma?r(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<n.items.length-1&&r(R.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),R.comment&&(u.comment?u.comment+=`
71
+ `+R.comment:u.comment=R.comment),d=R.end;continue}!o&&t.options.strict&&At(A)&&r(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)R.comma&&r(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(R.comma||r(R.start,"MISSING_CHAR",`Missing , between ${a} items`),R.comment){let J="";e:for(const $ of E)switch($.type){case"comma":case"space":break;case"comment":J=$.source.substring(1);break e;default:break e}if(J){let $=u.items[u.items.length-1];W($)&&($=$.value??$.key),$.comment?$.comment+=`
72
+ `+J:$.comment=J,R.comment=R.comment.substring(J.length+1)}}if(!o&&!I&&!R.found){const J=P?s(t,P,R,r):e(t,R.end,I,null,R,r);u.items.push(J),d=J.range[2],ws(P)&&r(J.range,"BLOCK_IN_FLOW",ys)}else{t.atKey=!0;const J=R.end,$=A?s(t,A,R,r):e(t,J,E,null,R,r);ws(A)&&r($.range,"BLOCK_IN_FLOW",ys),t.atKey=!1;const Y=ht(I??[],{flow:a,indicator:"map-value-ind",next:P,offset:$.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(Y.found){if(!o&&!R.found&&t.options.strict){if(I)for(const Z of I){if(Z===Y.found)break;if(Z.type==="newline"){r(Z,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}R.start<Y.found.offset-1024&&r(Y.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else P&&("source"in P&&P.source&&P.source[0]===":"?r(P,"MISSING_CHAR",`Missing space after : in ${a}`):r(Y.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Ee=P?s(t,P,Y,r):Y.found?e(t,Y.end,I,null,Y,r):null;Ee?ws(P)&&r(Ee.range,"BLOCK_IN_FLOW",ys):Y.comment&&($.comment?$.comment+=`
73
+ `+Y.comment:$.comment=Y.comment);const Ge=new X($,Ee);if(t.options.keepSourceTokens&&(Ge.srcToken=k),o){const Z=u;Ti(t,Z.items,$)&&r(J,"DUPLICATE_KEY","Map keys must be unique"),Z.items.push(Ge)}else{const Z=new se(t.schema);Z.flow=!0,Z.items.push(Ge);const Hs=(Ee??$).range;Z.range=[$.range[0],Hs[1],Hs[2]],u.items.push(Z)}d=Ee?Ee.range[2]:Y.end}}const h=o?"}":"]",[g,...w]=n.end;let p=d;if(g&&g.source===h)p=g.offset+g.source.length;else{const y=a[0].toUpperCase()+a.substring(1),k=f?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;r(d,f?"MISSING_CHAR":"BAD_INDENT",k),g&&g.source.length!==1&&w.unshift(g)}if(w.length>0){const y=$t(w,p,t.options.strict,r);y.comment&&(u.comment?u.comment+=`
74
+ `+y.comment:u.comment=y.comment),u.range=[n.offset,p,y.offset]}else u.range=[n.offset,p,p];return u}l(bc,"resolveFlowCollection");function bs(s,e,t,n,r,i){const o=t.type==="block-map"?yc(s,e,t,n,i):t.type==="block-seq"?wc(s,e,t,n,i):bc(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}l(bs,"resolveCollection");function Sc(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:g}=n,w=h&&i?h.offset>i.offset?h:i:h??i;w&&(!g||g.offset<w.offset)&&r(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(!i||!o||o==="!"||o===se.tagName&&a==="map"||o===Oe.tagName&&a==="seq")return bs(s,e,t,r,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?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),bs(s,e,t,r,o)}const u=bs(s,e,t,r,o,c),f=c.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,d=G(f)?f:new L(f);return d.range=u.range,d.tag=o,c?.format&&(d.format=c.format),d}l(Sc,"composeCollection");function Oi(s,e,t){const n=e.offset,r=Cc(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?L.BLOCK_FOLDED:L.BLOCK_LITERAL,o=e.source?vc(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=r.chomp==="+"&&o.length>0?`
75
+ `.repeat(Math.max(1,o.length-1)):"";let y=n+r.length;return e.source&&(y+=e.source.length),{value:p,type:i,comment:r.comment,range:[n,y,y]}}let c=e.indent+r.indent,u=e.offset+r.length,f=0;for(let p=0;p<a;++p){const[y,k]=o[p];if(k===""||k==="\r")r.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"),r.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+k.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>c&&(a=p+1);let d="",h="",g=!1;for(let p=0;p<f;++p)d+=o[p][0].slice(c)+`
76
+ `;for(let p=f;p<a;++p){let[y,k]=o[p];u+=y.length+k.length+1;const E=k[k.length-1]==="\r";if(E&&(k=k.slice(0,-1)),k&&y.length<c){const I=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-k.length-(E?2:1),"BAD_INDENT",I),y=""}i===L.BLOCK_LITERAL?(d+=h+y.slice(c)+k,h=`
77
+ `):y.length>c||k[0]===" "?(h===" "?h=`
78
78
  `:!g&&h===`
79
79
  `&&(h=`
80
80
 
81
- `),d+=h+w.slice(l)+k,h=`
81
+ `),d+=h+y.slice(c)+k,h=`
82
82
  `,g=!0):k===""?h===`
83
83
  `?d+=`
84
84
  `:h=`
85
85
  `:(d+=h+k,h=" ",g=!1)}switch(r.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)d+=`
86
- `+o[p][0].slice(l);d[d.length-1]!==`
86
+ `+o[p][0].slice(c);d[d.length-1]!==`
87
87
  `&&(d+=`
88
88
  `);break;default:d+=`
89
- `}const y=n+r.length+e.source.length;return{value:d,type:i,comment:r.comment,range:[n,y,y]}}c(Oi,"resolveBlockScalar");function vc({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:r}=e[0],i=r[0];let o=0,a="",l=-1;for(let h=1;h<r.length;++h){const g=r[h];if(!a&&(g==="-"||g==="+"))a=g;else{const y=Number(g);!o&&y?o=y:l===-1&&(l=s+h)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,f="",d=r.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,f=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const y=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",y);const p=g.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:d}}c(vc,"parseBlockScalarHeader");function kc(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}c(kc,"splitLines");function Ai(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((h,g,y)=>t(n+h,g,y),"_onError");switch(r){case"scalar":a=D.PLAIN,l=Tc(i,u);break;case"single-quoted-scalar":a=D.QUOTE_SINGLE,l=Ec(i,u);break;case"double-quoted-scalar":a=D.QUOTE_DOUBLE,l=Ic(i,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}const f=n+i.length,d=$t(o,f,e,t);return{value:l,type:a,comment:d.comment,range:[n,f,d.offset]}}c(Ai,"resolveFlowScalar");function Tc(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}`),$i(s)}c(Tc,"plainValue");function Ec(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),$i(s.slice(1,-1)).replace(/''/g,"'")}c(Ec,"singleQuotedValue");function $i(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
+ `}const w=n+r.length+e.source.length;return{value:d,type:i,comment:r.comment,range:[n,w,w]}}l(Oi,"resolveBlockScalar");function Cc({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:r}=e[0],i=r[0];let o=0,a="",c=-1;for(let h=1;h<r.length;++h){const g=r[h];if(!a&&(g==="-"||g==="+"))a=g;else{const w=Number(g);!o&&w?o=w:c===-1&&(c=s+h)}}c!==-1&&n(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,f="",d=r.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":d+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=g.source.length,f=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),d+=g.source.length;break;default:{const w=`Unexpected token in block scalar header: ${g.type}`;n(g,"UNEXPECTED_TOKEN",w);const p=g.source;p&&typeof p=="string"&&(d+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:d}}l(Cc,"parseBlockScalarHeader");function vc(s){const e=s.split(/\n( *)/),t=e[0],n=t.match(/^( *)/),i=[n?.[1]?[n[1],t.slice(n[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}l(vc,"splitLines");function Ai(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,c;const u=l((h,g,w)=>t(n+h,g,w),"_onError");switch(r){case"scalar":a=L.PLAIN,c=kc(i,u);break;case"single-quoted-scalar":a=L.QUOTE_SINGLE,c=Ec(i,u);break;case"double-quoted-scalar":a=L.QUOTE_DOUBLE,c=Tc(i,u);break;default:return t(s,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[n,n+i.length,n+i.length]}}const f=n+i.length,d=$t(o,f,e,t);return{value:c,type:a,comment:d.comment,range:[n,f,d.offset]}}l(Ai,"resolveFlowScalar");function kc(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}`),$i(s)}l(kc,"plainValue");function Ec(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),$i(s.slice(1,-1)).replace(/''/g,"'")}l(Ec,"singleQuotedValue");function $i(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
90
90
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
91
91
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let n=e.exec(s);if(!n)return s;let r=n[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;n=t.exec(s);)n[1]===""?i===`
92
92
  `?r+=i:i=`
93
- `:(r+=i+n[1],i=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),r+i+(n?.[1]??"")}c($i,"foldLines");function Ic(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
93
+ `:(r+=i+n[1],i=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,n=a.exec(s),r+i+(n?.[1]??"")}l($i,"foldLines");function Tc(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
94
94
  `))if(r===`
95
- `){const{fold:i,offset:o}=Oc(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=Ac[i];if(o)t+=o;else if(i===`
95
+ `){const{fold:i,offset:o}=Ic(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=Oc[i];if(o)t+=o;else if(i===`
96
96
  `)for(i=s[n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="\r"&&s[n+1]===`
97
- `)for(i=s[++n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="x"||i==="u"||i==="U"){const a={x:2,u:4,U:8}[i];t+=$c(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(r===" "||r===" "){const i=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
97
+ `)for(i=s[++n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="x"||i==="u"||i==="U"){const a={x:2,u:4,U:8}[i];t+=Ac(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(r===" "||r===" "){const i=n;let o=s[n+1];for(;o===" "||o===" ";)o=s[++n+1];o!==`
98
98
  `&&!(o==="\r"&&s[n+2]===`
99
- `)&&(t+=n>i?s.slice(i,n+1):r)}else t+=r}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}c(Ic,"doubleQuotedValue");function Oc(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
99
+ `)&&(t+=n>i?s.slice(i,n+1):r)}else t+=r}return(s[s.length-1]!=='"'||s.length===1)&&e(s.length,"MISSING_CHAR",'Missing closing "quote'),t}l(Tc,"doubleQuotedValue");function Ic(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
100
100
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
101
101
  `);)n===`
102
102
  `&&(t+=`
103
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(Oc,"foldNewline");const Ac={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
104
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function $c(s,e,t,n){const r=s.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){const a=s.substr(e-2,t+2);return n(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}c($c,"parseCharCode");function Ni(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?Oi(s,e,n):Ai(e,s.options.strict,n),l=t?s.directives.tagName(t.source,d=>n(t,"TAG_RESOLVE_FAILED",d)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[me]:l?u=Nc(s.schema,r,l,t,n):e.type==="scalar"?u=xc(s,r,e,n):u=s.schema[me];let f;try{const d=u.resolve(r,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);f=J(d)?d:new D(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),f=new D(r)}return f.range=a,f.source=r,i&&(f.type=i),l&&(f.tag=l),u.format&&(f.format=u.format),o&&(f.comment=o),f}c(Ni,"composeScalar");function Nc(s,e,t,n,r){if(t==="!")return s[me];const i=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(const a of i)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):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[me])}c(Nc,"findScalarTagByName");function xc({atKey:s,directives:e,schema:t},n,r,i){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[me];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[me];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),f=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}c(xc,"findScalarTagByTest");function Pc(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":s-=r.source.length;continue}for(r=e[++n];r?.type==="space";)s+=r.source.length,r=e[++n];break}}return s}c(Pc,"emptyScalarPosition");const Lc={composeNode:xi,composeEmptyNode:Ss};function xi(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,f=!0;switch(e.type){case"alias":u=Dc(s,e,n),(a||l)&&n(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=Ni(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Cc(Lc,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"),r&&s.options.stringKeys&&(!J(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&n(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&f&&(u.srcToken=e),u}c(xi,"composeNode");function Ss(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const f={type:"scalar",offset:Pc(e,t,n),indent:-1,source:""},d=Ni(s,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=l),d}c(Ss,"composeEmptyNode");function Dc({options:s},{offset:e,source:t,end:n},r){const i=new Zt(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=$t(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(Dc,"composeAlias");function Rc(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new St(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},f=ht(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?xi(u,r,f,o):Ss(u,f.end,n,null,f,o);const d=l.contents.range[2],h=$t(i,d,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,d,h.offset],l}c(Rc,"composeDoc");function Nt(s){if(typeof s=="number")return[s,s+1];if(Array.isArray(s))return s.length===2?s:[s[0],s[1]];const{offset:e,source:t}=s;return[e,e+(typeof t=="string"?t.length:1)]}c(Nt,"getErrorPos");function Pi(s){let e="",t=!1,n=!1;for(let r=0;r<s.length;++r){const i=s[r];switch(i[0]){case"#":e+=(e===""?"":n?`
103
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}l(Ic,"foldNewline");const Oc={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
104
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ac(s,e,t,n){const r=s.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,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(Ac,"parseCharCode");function Ni(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?Oi(s,e,n):Ai(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[me]:c?u=$c(s.schema,r,c,t,n):e.type==="scalar"?u=Nc(s,r,e,n):u=s.schema[me];let f;try{const d=u.resolve(r,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);f=U(d)?d:new L(d)}catch(d){const h=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",h),f=new L(r)}return f.range=a,f.source=r,i&&(f.type=i),c&&(f.tag=c),u.format&&(f.format=u.format),o&&(f.comment=o),f}l(Ni,"composeScalar");function $c(s,e,t,n,r){if(t==="!")return s[me];const i=[];for(const a of s.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(const a of i)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):(r(n,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),s[me])}l($c,"findScalarTagByName");function Nc({atKey:s,directives:e,schema:t},n,r,i){const o=t.tags.find(a=>(a.default===!0||s&&a.default==="key")&&a.test?.test(n))||t[me];if(t.compat){const a=t.compat.find(c=>c.default&&c.test?.test(n))??t[me];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}`;i(r,"TAG_RESOLVE_FAILED",f,!0)}}return o}l(Nc,"findScalarTagByTest");function xc(s,e,t){if(e){t??(t=e.length);for(let n=t-1;n>=0;--n){let r=e[n];switch(r.type){case"space":case"comment":case"newline":s-=r.source.length;continue}for(r=e[++n];r?.type==="space";)s+=r.source.length,r=e[++n];break}}return s}l(xc,"emptyScalarPosition");const Pc={composeNode:xi,composeEmptyNode:Ss};function xi(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:c}=t;let u,f=!0;switch(e.type){case"alias":u=Lc(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=Ni(s,e,c,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=Sc(Pc,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"),r&&s.options.stringKeys&&(!U(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"),i&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),s.options.keepSourceTokens&&f&&(u.srcToken=e),u}l(xi,"composeNode");function Ss(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:c},u){const f={type:"scalar",offset:xc(e,t,n),indent:-1,source:""},d=Ni(s,f,a,u);return o&&(d.anchor=o.source.substring(1),d.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),i&&(d.comment=i,d.range[2]=c),d}l(Ss,"composeEmptyNode");function Lc({options:s},{offset:e,source:t,end:n},r){const i=new Zt(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=$t(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}l(Lc,"composeAlias");function Rc(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),c=new St(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},f=ht(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});f.found&&(c.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!f.hasNewline&&o(f.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=r?xi(u,r,f,o):Ss(u,f.end,n,null,f,o);const d=c.contents.range[2],h=$t(i,d,!1,o);return h.comment&&(c.comment=h.comment),c.range=[t,d,h.offset],c}l(Rc,"composeDoc");function Nt(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(Nt,"getErrorPos");function Pi(s){let e="",t=!1,n=!1;for(let r=0;r<s.length;++r){const i=s[r];switch(i[0]){case"#":e+=(e===""?"":n?`
105
105
 
106
106
  `:`
107
- `)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":s[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}c(Pi,"parsePrelude");class Cs{static{c(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,r,i)=>{const o=Nt(t);i?this.warnings.push(new Ti(o,n,r)):this.errors.push(new Ue(o,n,r))},this.directives=new ee({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Pi(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
+ `)+(i.substring(1)||" "),t=!0,n=!1;break;case"%":s[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(n=!0),t=!1}}return{comment:e,afterEmptyLine:n}}l(Pi,"parsePrelude");class Cs{static{l(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,n,r,i)=>{const o=Nt(t);i?this.warnings.push(new Ei(o,n,r)):this.errors.push(new Ue(o,n,r))},this.directives=new ee({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Pi(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
108
108
  ${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(V(i)&&!i.flow&&i.items.length>0){let o=i.items[0];W(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
109
109
  ${a}`:n}else{const o=i.commentBefore;i.commentBefore=o?`${n}
110
110
  ${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 r of e)yield*this.next(r);yield*this.end(t,n)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,n,r)=>{const i=Nt(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Rc(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 Ue(Nt(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 Ue(Nt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=$t(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}
111
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ue(Nt(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),r=new St(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}}function Mc(s,e=!0,t){if(s){const n=c((r,i,o)=>{const a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new Ue([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ai(s,e,n);case"block-scalar":return Oi({options:{strict:e}},s,n)}}return null}c(Mc,"resolveAsScalar");function jc(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=It({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:n,source:`
111
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ue(Nt(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),r=new St(void 0,n);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}}function Dc(s,e=!0,t){if(s){const n=l((r,i,o)=>{const a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new Ue([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ai(s,e,n);case"block-scalar":return Oi({options:{strict:e}},s,n)}}return null}l(Dc,"resolveAsScalar");function Mc(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=It({type:o,value:s},{implicitKey:t,indent:n>0?" ".repeat(n):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:n,source:`
112
112
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
113
113
  `),f=a.substring(0,u),d=a.substring(u+1)+`
114
- `,h=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return Li(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
115
- `}),{type:"block-scalar",offset:i,indent:n,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:l};default:return{type:"scalar",offset:i,indent:n,source:a,end:l}}}c(jc,"createScalarToken");function _c(s,e,t={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=t,a="indent"in s?s.indent:null;if(n&&typeof a=="number"&&(a+=2),!o)switch(s.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=s.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const l=It({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":Fc(s,l);break;case'"':vs(s,l,"double-quoted-scalar");break;case"'":vs(s,l,"single-quoted-scalar");break;default:vs(s,l,"scalar")}}c(_c,"setScalarValue");function Fc(s,e){const t=e.indexOf(`
114
+ `,h=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return Li(h,c)||h.push({type:"newline",offset:-1,indent:n,source:`
115
+ `}),{type:"block-scalar",offset:i,indent:n,props:h,source:d}}case'"':return{type:"double-quoted-scalar",offset:i,indent:n,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:i,indent:n,source:a,end:c};default:return{type:"scalar",offset:i,indent:n,source:a,end:c}}}l(Mc,"createScalarToken");function jc(s,e,t={}){let{afterKey:n=!1,implicitKey:r=!1,inFlow:i=!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=It({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":_c(s,c);break;case'"':vs(s,c,"double-quoted-scalar");break;case"'":vs(s,c,"single-quoted-scalar");break;default:vs(s,c,"scalar")}}l(jc,"setScalarValue");function _c(s,e){const t=e.indexOf(`
116
116
  `),n=e.substring(0,t),r=e.substring(t+1)+`
117
117
  `;if(s.type==="block-scalar"){const i=s.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=n,s.source=r}else{const{offset:i}=s,o="indent"in s?s.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:n}];Li(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
118
- `});for(const l of Object.keys(s))l!=="type"&&l!=="offset"&&delete s[l];Object.assign(s,{type:"block-scalar",indent:o,props:a,source:r})}}c(Fc,"setBlockScalarValue");function Li(s,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":s.push(t);break;case"newline":return s.push(t),!0}return!1}c(Li,"addEndtoBlockProps");function vs(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 r=e.length;s.props[0].type==="block-scalar-header"&&(r-=s.props[0].source.length);for(const i of n)i.offset+=r;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const r={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
119
- `};delete s.items,Object.assign(s,{type:t,source:e,end:[r]});break}default:{const n="indent"in s?s.indent:-1,r="end"in s&&Array.isArray(s.end)?s.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(const i of Object.keys(s))i!=="type"&&i!=="offset"&&delete s[i];Object.assign(s,{type:t,indent:n,source:e,end:r})}}}c(vs,"setFlowScalarValue");const Kc=c(s=>"type"in s?gn(s):yn(s),"stringify$1");function gn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=gn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=yn(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=yn(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=yn(s);if(s.end)for(const t of s.end)e+=t.source;return e}default:{let e=s.source;if("end"in s&&s.end)for(const t of s.end)e+=t.source;return e}}}c(gn,"stringifyToken");function yn({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=gn(e)),t)for(const i of t)r+=i.source;return n&&(r+=gn(n)),r}c(yn,"stringifyItem");const ks=Symbol("break visit"),qc=Symbol("skip children"),Di=Symbol("remove item");function Je(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Ri(Object.freeze([]),s,e)}c(Je,"visit"),Je.BREAK=ks,Je.SKIP=qc,Je.REMOVE=Di,Je.itemAtPath=(s,e)=>{let t=s;for(const[n,r]of e){const i=t?.[n];if(i&&"items"in i)t=i.items[r];else return}return t},Je.parentCollection=(s,e)=>{const t=Je.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],r=t?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Ri(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){const a=Ri(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ks)return ks;a===Di&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}c(Ri,"_visit");const wn="\uFEFF",bn="",Sn="",xt="",Bc=c(s=>!!s&&"items"in s,"isCollection"),Uc=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Jc(s){switch(s){case wn:return"<BOM>";case bn:return"<DOC>";case Sn:return"<FLOW_END>";case xt:return"<SCALAR>";default:return JSON.stringify(s)}}c(Jc,"prettyToken");function Mi(s){switch(s){case wn:return"byte-order-mark";case bn:return"doc-mode";case Sn:return"flow-error-end";case xt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
+ `});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:r})}}l(_c,"setBlockScalarValue");function Li(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(Li,"addEndtoBlockProps");function vs(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 r=e.length;s.props[0].type==="block-scalar-header"&&(r-=s.props[0].source.length);for(const i of n)i.offset+=r;delete s.props,Object.assign(s,{type:t,source:e,end:n});break}case"block-map":case"block-seq":{const r={type:"newline",offset:s.offset+e.length,indent:s.indent,source:`
119
+ `};delete s.items,Object.assign(s,{type:t,source:e,end:[r]});break}default:{const n="indent"in s?s.indent:-1,r="end"in s&&Array.isArray(s.end)?s.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(const i of Object.keys(s))i!=="type"&&i!=="offset"&&delete s[i];Object.assign(s,{type:t,indent:n,source:e,end:r})}}}l(vs,"setFlowScalarValue");const Fc=l(s=>"type"in s?gn(s):yn(s),"stringify$1");function gn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=gn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=yn(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=yn(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=yn(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(gn,"stringifyToken");function yn({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=gn(e)),t)for(const i of t)r+=i.source;return n&&(r+=gn(n)),r}l(yn,"stringifyItem");const ks=Symbol("break visit"),Kc=Symbol("skip children"),Ri=Symbol("remove item");function Je(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Di(Object.freeze([]),s,e)}l(Je,"visit"),Je.BREAK=ks,Je.SKIP=Kc,Je.REMOVE=Ri,Je.itemAtPath=(s,e)=>{let t=s;for(const[n,r]of e){const i=t?.[n];if(i&&"items"in i)t=i.items[r];else return}return t},Je.parentCollection=(s,e)=>{const t=Je.itemAtPath(s,e.slice(0,-1)),n=e[e.length-1][0],r=t?.[n];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Di(s,e,t){let n=t(e,s);if(typeof n=="symbol")return n;for(const r of["key","value"]){const i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){const a=Di(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ks)return ks;a===Ri&&(i.items.splice(o,1),o-=1)}}typeof n=="function"&&r==="key"&&(n=n(e,s))}}return typeof n=="function"?n(e,s):n}l(Di,"_visit");const wn="\uFEFF",bn="",Sn="",xt="",Bc=l(s=>!!s&&"items"in s,"isCollection"),qc=l(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Uc(s){switch(s){case wn:return"<BOM>";case bn:return"<DOC>";case Sn:return"<FLOW_END>";case xt:return"<SCALAR>";default:return JSON.stringify(s)}}l(Uc,"prettyToken");function Mi(s){switch(s){case wn:return"byte-order-mark";case bn:return"doc-mode";case Sn:return"flow-error-end";case xt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
120
120
  `:case`\r
121
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}c(Mi,"tokenType");var Wc=Object.freeze({__proto__:null,BOM:wn,DOCUMENT:bn,FLOW_END:Sn,SCALAR:xt,createScalarToken:jc,isCollection:Bc,isScalar:Uc,prettyToken:Jc,resolveAsScalar:Mc,setScalarValue:_c,stringify:Kc,tokenType:Mi,visit:Je});function fe(s){switch(s){case void 0:case" ":case`
122
- `:case"\r":case" ":return!0;default:return!1}}c(fe,"isEmpty");const ji=new Set("0123456789ABCDEFabcdef"),Vc=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Cn=new Set(",[]{}"),Gc=new Set(` ,[]{}
123
- \r `),Ts=c(s=>!s||Gc.has(s),"isNotAnchorChar");class _i{static{c(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??"stream";for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
121
+ `: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(Mi,"tokenType");var Jc=Object.freeze({__proto__:null,BOM:wn,DOCUMENT:bn,FLOW_END:Sn,SCALAR:xt,createScalarToken:Mc,isCollection:Bc,isScalar:qc,prettyToken:Uc,resolveAsScalar:Dc,setScalarValue:jc,stringify:Fc,tokenType:Mi,visit:Je});function fe(s){switch(s){case void 0:case" ":case`
122
+ `:case"\r":case" ":return!0;default:return!1}}l(fe,"isEmpty");const ji=new Set("0123456789ABCDEFabcdef"),Wc=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Cn=new Set(",[]{}"),Vc=new Set(` ,[]{}
123
+ \r `),Es=l(s=>!s||Vc.has(s),"isNotAnchorChar");class _i{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===`
124
124
  `?!0:t==="\r"?this.buffer[e+1]===`
125
125
  `:!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 r=this.buffer[n+e+1];if(r===`
126
126
  `||!r&&!this.atEnd)return e+n+1}return t===`
127
127
  `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&fe(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(`
128
- `,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]===wn&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const i=e[t-1];if(i===" "||i===" ")t-=1;else break}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),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 bn,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==="...")&&fe(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&&!fe(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===":")&&fe(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(Ts),"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 r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&fe(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Sn,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"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(Ts),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||fe(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 i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf(`
128
+ `,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]===wn&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,n=e.indexOf("#");for(;n!==-1;){const i=e[n-1];if(i===" "||i===" "){t=n-1;break}else n=e.indexOf("#",n+1)}for(;;){const i=e[t-1];if(i===" "||i===" ")t-=1;else break}const r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),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 bn,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==="...")&&fe(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&&!fe(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===":")&&fe(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(Es),"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 r=this.getLine();if(r===null)return this.setNext("flow");if((n!==-1&&n<this.indentNext&&r[0]!=="#"||n===0&&(r.startsWith("---")||r.startsWith("..."))&&fe(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Sn,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"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(Es),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||fe(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 i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}const n=this.buffer.substring(0,t);let r=n.indexOf(`
129
129
  `,this.pos);if(r!==-1){for(;r!==-1;){const i=this.continueScalar(r+1);if(i===-1)break;r=n.indexOf(`
130
130
  `,i)}r!==-1&&(t=r-(n[r-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=>fe(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,n;e:for(let i=this.pos;n=this.buffer[i];++i)switch(n){case" ":t+=1;break;case`
131
131
  `:e=i,t=0;break;case"\r":{const o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
@@ -135,26 +135,26 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
135
135
  `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield xt,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===":"){const i=this.buffer[n+1];if(fe(i)||e&&Cn.has(i))break;t=n}else if(fe(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
136
136
  `?(n+=1,r=`
137
137
  `,i=this.buffer[n+1]):t=n),i==="#"||e&&Cn.has(i))break;if(r===`
138
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Cn.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield xt,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(Ts))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(fe(t)||e&&Cn.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(;!fe(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(Vc.has(t))t=this.buffer[++e];else if(t==="%"&&ji.has(this.buffer[e+1])&&ji.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===`
138
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&Cn.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield xt,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(Es))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(fe(t)||e&&Cn.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(;!fe(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(Wc.has(t))t=this.buffer[++e];else if(t==="%"&&ji.has(this.buffer[e+1])&&ji.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===`
139
139
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
140
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Fi{static{c(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){const i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}function Ae(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Ae,"includesToken");function Ki(s){for(let e=0;e<s.length;++e)switch(s[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}c(Ki,"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}}c(qi,"isFlowToken");function vn(s){switch(s.type){case"document":return s.start;case"block-map":{const e=s.items[s.items.length-1];return e.sep??e.start}case"block-seq":return s.items[s.items.length-1].start;default:return[]}}c(vn,"getPrevProps");function pt(s){if(s.length===0)return[];let e=s.length;e:for(;--e>=0;)switch(s[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;s[++e]?.type==="space";);return s.splice(e,s.length)}c(pt,"getFirstKeyStartProps");function Bi(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Ae(e.start,"explicit-key-ind")&&!Ae(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)}c(Bi,"fixFlowSeqItems");class Es{static{c(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new _i,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=Mi(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"&&Bi(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{const r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{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 r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Ki(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.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":{Ki(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=vn(this.peek(2)),n=pt(t);let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}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(`
140
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===" "||e&&n===" ");const r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Fi{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 i=t+n>>1;this.lineStarts[i]<e?t=i+1:n=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}function Ae(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}l(Ae,"includesToken");function Ki(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(Ki,"findNonEmptyIndex");function Bi(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(Bi,"isFlowToken");function vn(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(vn,"getPrevProps");function pt(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(pt,"getFirstKeyStartProps");function qi(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Ae(e.start,"explicit-key-ind")&&!Ae(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Bi(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 Ts{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 _i,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=Mi(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"&&qi(t),n.type){case"document":n.value=t;break;case"block-scalar":n.props.push(t);break;case"block-map":{const r=n.items[n.items.length-1];if(r.value){n.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{const r=n.items[n.items.length-1];r.value?n.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{const r=n.items[n.items.length-1];!r||r.value?n.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{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 r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Ki(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(n.type==="document"?n.end=r.start:n.items.push({start:r.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":{Ki(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=vn(this.peek(2)),n=pt(t);let r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];const i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}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(`
141
141
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
142
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ae(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(qi(t.key)&&!Ae(t.sep,"newline")){const o=pt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Ae(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=pt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Ae(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ae(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Ae(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=vn(n),i=pt(r);Bi(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
142
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let i=[];if(r&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const 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&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ae(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Bi(t.key)&&!Ae(t.sep,"newline")){const o=pt(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 i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Ae(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=pt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Ae(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ae(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Ae(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{const n=this.peek(2);if(n.type==="block-map"&&(this.type==="map-value-ind"&&n.indent===e.indent||this.type==="newline"&&!n.items[n.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&n.type!=="flow-collection"){const r=vn(n),i=pt(r);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:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
143
143
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
144
- `,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=vn(e),n=pt(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=vn(e),n=pt(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 Ui(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Fi||null,prettyErrors:e}}c(Ui,"parseOptions");function zc(s,e={}){const{lineCounter:t,prettyErrors:n}=Ui(e),r=new Es(t?.addNewLine),i=new Cs(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(mn(s,t)),a.warnings.forEach(mn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(zc,"parseAllDocuments");function Ji(s,e={}){const{lineCounter:t,prettyErrors:n}=Ui(e),r=new Es(t?.addNewLine),i=new Cs(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ue(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(mn(s,t)),o.warnings.forEach(mn(s,t))),o}c(Ji,"parseDocument");function Hc(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Ji(s,t);if(!r)return null;if(r.warnings.forEach(i=>ti(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}c(Hc,"parse");function Yc(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Fe(s)&&!n?s.toString(t):new St(s,n,t).toString(t)}c(Yc,"stringify");var Zc=Object.freeze({__proto__:null,Alias:Zt,CST:Wc,Composer:Cs,Document:St,Lexer:_i,LineCounter:Fi,Pair:X,Parser:Es,Scalar:D,Schema:An,YAMLError:ms,YAMLMap:se,YAMLParseError:Ue,YAMLSeq:Oe,YAMLWarning:Ti,isAlias:Ie,isCollection:V,isDocument:Fe,isMap:st,isNode:G,isPair:W,isScalar:J,isSeq:rt,parse:Hc,parseAllDocuments:zc,parseDocument:Ji,stringify:Yc,visit:Ke,visitAsync:Yt});class Is extends zo{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}const re={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Qc={ignored:va,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Xc extends Is{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ie(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(O.existsSync(this.membraneDir)||O.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Go.watch(this.membraneDir,Qc),this.watcher.on("add",e=>this.handleFileSystemEvent(re.Updated,e)).on("change",e=>this.handleFileSystemEvent(re.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(re.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(re.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=x.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=x.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+x.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=x.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===re.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return O.readFileSync(e,"utf8")}processFileEvent(e,t){const n=x.relative(this.membraneDir,e);let r;try{r=t?Zc.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Wo.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){O.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=O.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=x.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=O.readFileSync(r,"utf8"),o=x.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Os=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Os||{});const el={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class tl extends Is{static{c(this,"RemoteElementWatcher")}constructor(e=el){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await R.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new Ho(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==xo.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class Wi{static{c(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const mt="connectors",ve="development",As={};async function Vi(){const s=new Set,t=(await R.withClient(a=>a.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors"),await R.withClient(a=>a.get(`/connectors?workspaceId=${t}`)),b.info("[connectors] Loading public connectors");const r=$e(),o=(F.existsSync(r)?F.readdirSync(r):[]).filter(a=>{if(a.startsWith("."))return!1;const l=_.join(r,a);try{return F.statSync(l).isDirectory()}catch{return!1}});for(const a of o){b.info(`[connectors] Loading connector from: ${a}`);const l=F.readdirSync(_.join(r,a)),u=await $s(a);if(!u)continue;"baseUri"in u&&delete u.baseUri;let f;if(u.uuid&&(f=await R.withClient(h=>h.get(`/connectors/${u.uuid}`),!1)),f)n[u.id]=f.id,b.info(`[connectors] Matched ${u.name} uuid: ${u.uuid}`),f.isPublic||(f.archivedAt&&(b.info(`[connectors] Restoring archived connector ${u.name}`),await R.withClient(h=>h.post(`connectors/${f.id}/restore`))),b.info(`[connectors] Updating connector ${u.name}`),await R.withClient(h=>h.patch(`connectors/${f.id}`,{...u,workspaceId:t})));else if(!n[u.id]&&!f?.isPublic){let h=!1;try{const g=await Ns({connectorId:u.id});g&&g.isPublic&&(h=!0)}catch{}if(!h){b.info(`[connectors] Creating custom connector ${u.name} (${u.key})`);const g=await R.withClient(y=>y.post("connectors",{...u,workspaceId:t}));n[u.id]=g.id}}const d=l.filter(h=>F.statSync(_.join(r,a,h)).isDirectory());for(const h of d)await rl({connector:u,version:h,connectorId:n[u.id]}),s.add(u.id)}return{connectorsMapping:n,pushedConnectors:Array.from(s)}}c(Vi,"pushConnectors");async function Gi({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=lr(),o=await Ns({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await il({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await ol({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(Gi,"pullRemoteConnector");function $e(){const s=zn();return _.join(s.membraneDirPath,mt)}c($e,"getConnectorsPath");async function $s(s){const e=_.join($e(),s,`${s}.yml`);return Zn(e,!1)}c($s,"readConnector");async function nl(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=sr("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=F.readdirSync(s);for(const a of o){const l=_.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(nl,"createZipArchive");async function sl(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=ir.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=_.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=_.join(e,o),u=_.dirname(l);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(l);i.pipe(f),f.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(sl,"extractZipArchive");async function rl({connector:s,version:e,connectorId:t}){const n=_.join($e(),ke(s),zi(e)),r=_.join(n,"src"),i=_.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await nl(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new rr;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ve)b.info(`[connectors] Uploading connector ${t}`),await R.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await R.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await R.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(rl,"pushConnectorVersion");async function Ns({connectorId:s}){if(s){if(As[s])return As[s];try{const e=await R.withClient(t=>t.get(`connectors/${s}`),!1);return As[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(Ns,"getConnector");async function il({basePath:s,connector:e}){const t=ke(e),n=_.join(s,mt,t);F.mkdirSync(n,{recursive:!0});const r=_.join(n,`${ke(e)}.yml`);F.writeFileSync(r,le.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(il,"pullConnector$1");async function ol({connector:s,connectorVersion:e,basePath:t}){const n=ke(s),r=zi(e),i=_.join(t,"connectors",n,r),o=await R.withClient(l=>l.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=_.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=_.join(i,"src");F.mkdirSync(l,{recursive:!0}),await sl(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(ol,"pullConnectorVersion");function ke(s){return s.key}c(ke,"getConnectorDirName");function zi(s){return s??ve}c(zi,"getConnectorVersionDirName");function al(s){const e=lr(),t=ke(s);return _.join(e,mt,t)}c(al,"getConnectorDirPath");function cl(s){return s.match(`${mt}/[^/]+/${ve}/src/.*`)!==null}c(cl,"isConnectorSourceFile");async function ll(s){const e=s.match(`${mt}/([^/]+)/${ve}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await $s(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await R.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}c(ll,"putConnectorFile");async function ul(s){const e=s.match(`${mt}/([^/]+)/${ve}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await $s(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await R.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(ul,"deleteConnectorFile");async function fl(s,e){try{const t=await R.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await R.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=ke(t),i=_.join($e(),r,ve,"src",e);F.mkdirSync(_.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}c(fl,"pullConnectorFile");async function dl(s,e){const t=await R.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=ke(t),r=_.join($e(),n,ve,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(dl,"deleteLocalConnectorFile");async function hl(s,e,t){if(t&&e!==t)try{const n=await R.withClient(l=>l.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=ke(n),i=_.join($e(),r,ve,"src"),o=_.join(i,e),a=_.join(i,t);F.existsSync(o)&&(F.mkdirSync(_.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}c(hl,"renameLocalConnectorDirectory");async function pl(s,e){try{const t=await R.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=ke(t),r=_.join($e(),n,ve,"src",e);if(F.existsSync(r)){const i=_.resolve($e());if(!_.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}c(pl,"deleteLocalConnectorDirectory");const H={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class ml extends Is{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(H.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(H.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(H.ConfigChanged,{config:e})}setStats(e){this.emit(H.StatsChanged,{stats:e})}addLog(e){this.emit(H.LogAdded,{log:e})}setMcpStatus(e){this.emit(H.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(H.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await R.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await R.withClient(t=>t.post("/local-clients",{hostname:nr.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await R.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await R.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const Ne=new ml({heartbeatIntervalMs:15e3}),Hi=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Dt{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Ne,this.localCache=new Wi,this.remoteCache=new Wi,this.localRepo=new qa(this.localCache),this.remoteRepo=new Ba(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Gi({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const{connectorsMapping:e}=await Vi();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===te.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===te.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Xc({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(re.Updated,e=>this.handleLocalEvent(e,re.Updated)),this.localWatcher.on(re.Deleted,e=>this.handleLocalEvent(e,re.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new tl,this.remoteWatcher.on(Os.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Os.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(te.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,te.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(te.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,te.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await Ns({connectorId:o});if(!l?.key)return;const u=al(l);await this.localWatcher?.executeWithPathLock(u,async()=>Gi({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Nn.ConnectorFileDeleted:await dl(e,t);break;case Nn.ConnectorDirectoryRenamed:await hl(e,t,r);break;case Nn.ConnectorDirectoryDeleted:await pl(e,t);break;default:await fl(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(cl(e.filePath))switch(t){case re.Updated:await ll(e.filePath);break;case re.Deleted:await ul(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const r=z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(te.OUTGOING)}] ${_a.toSentenceCase(t)}: ${n.id}`),t){case re.Updated:await this.updateElement(n,te.OUTGOING);break;case re.Deleted:await this.deleteElement(n,te.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Dt.getChanges(te.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Dt.getChanges(te.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===te.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Hi){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Hi){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case be.DELETE:return this.deleteElement(e.element,e.direction);case be.CREATE:return this.updateElement(e.element,e.direction);case be.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const l of o){const u=t.get(l),f=n.get(l),d=Dt.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case te.INCOMING:return"local\u2190remote";case te.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:be.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:be.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:be.UPDATE,element:e,direction:n,isConflict:!1}:null}}const xe=x.join(Yo.tmpdir(),"membrane-mcp-status"),Yi=3e4;class gl{static{c(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kn(void 0,e),n=Zi(e);t&&Ne.setMcpStatus(t),await Ne.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function kn(s,e){try{const t=e||process.cwd();if(!s){const r=Zi(t);return r.length===0?null:r[0]}const n=Ls(s,t);if(O.existsSync(n)){const r=O.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Yi)return Pt(s,t),null;const a=O.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>Yi)return Pt(s,t),null}return l}}catch{s&&e&&Pt(s,e)}return null}c(kn,"getMcpStatus");function Zi(s){try{const e=s||process.cwd(),t=Ps(e);if(!O.existsSync(xe))return[];const n=O.readdirSync(xe),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),l=kn(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Zi,"getAllMcpStatusFiles");function xs(s){try{const t={...kn(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};O.existsSync(xe)||O.mkdirSync(xe,{recursive:!0});const n=Ls(s.processId,s.cwd);O.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(xs,"updateMcpStatus");function Pt(s,e){try{const t=e||process.cwd();if(s){const n=Ls(s,t);O.existsSync(n)&&O.unlinkSync(n)}else{const n=Ps(t);if(O.existsSync(xe)){const r=O.readdirSync(xe);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&O.unlinkSync(x.join(xe,i))}}}catch{}}c(Pt,"clearMcpStatus");function yl(s,e){const t=kn(s,e);t&&xs({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(yl,"trackToolExecution");function Ps(s){return Vo("md5").update(s).digest("hex").slice(0,8)}c(Ps,"getCwdHash");function Ls(s,e){const t=Ps(e);return x.join(xe,`mcp-${t}-${s}.json`)}c(Ls,"getStatusFilePath");const Tn={Agent:"agent",Cli:"cli"},M={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class wl{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Ne,this.mcpStatusService=new gl,this.syncService=new Dt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&R.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(M.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(M.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&R.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(M.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(M.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(M.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(M.SYNCED),e.watch&&(await this.notifier.setState(M.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(M.NOT_INITIALIZED);try{await this.loadConfig(),_e.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(M.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(M.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=_e.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=_e.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Tn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Tn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Tn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Qi=Mn(null);function bl({children:s,membraneCLIService:e}){const{data:t}=tr("/account"),[n,r]=U(M.NOT_INITIALIZED),[i,o]=U([]),[a,l]=U({}),[u,f]=U([]),[d,h]=U(null),y=t?.workspaces?.find(p=>p.workspaceKey===d?.workspaceKey)||null;return ze(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),k=c(({log:I})=>f(P=>[...P,I]),"handleLogAdded"),T=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),$=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(H.StateChanged,p),e.notifier.on(H.StatsChanged,w),e.notifier.on(H.LogAdded,k),e.notifier.on(H.ConflictsChanged,T),e.notifier.on(H.ConfigChanged,$),e.init(),()=>{e.notifier.off(H.StateChanged,p),e.notifier.off(H.StatsChanged,w),e.notifier.off(H.LogAdded,k),e.notifier.off(H.ConflictsChanged,T),e.notifier.off(H.ConfigChanged,$)}},[]),m(Qi.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:c(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:c(p=>e.pullWorkspace(p),"pull"),push:c(p=>e.pushWorkspace(p),"push"),exit:c(()=>e.shutdown(),"exit"),fetchElements:c(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:c(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}c(bl,"MembraneCLIServiceProvider");function de(){const s=jn(Qi);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(de,"useMembraneCLIService");const Ds=Mn(null),Xi=c(()=>{const s=jn(Ds);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Sl=c(s=>Re.Children.count(s)>0,"hasChildren");function Cl(s){const e=Xi(),{label:t,value:n,isInitiallyExpanded:r}=s,i=Fo(),o=_n(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=U(r??!1),f={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:d}=s,h=typeof d=="function"?d(f):d;return{...f,props:{...s,children:h},isParent:Sl(h)}}c(Cl,"useTreeItem");function gt(s){const e=Xi(),t=Cl(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=kl}=s,l=t.ref;Mt(()=>{function h(g){return s.onInput?.(g)?!0:g.active&&g.key.rightArrow&&!n?(o(!0),!0):g.active&&g.key.leftArrow&&n?(o(!1),!0):!1}c(h,"onInput"),l.onInput=h},[l,s.onInput,n,o]),l.firstChild??={parent:l,index:0};let u=l.firstChild;function f(h){const g=u;return g.nextSibling||(g.nextSibling={parent:l,prevSibling:g,index:g.index+1}),u=g.nextSibling,g.label=h,g}c(f,"registerChildItem");function d(){l.lastRenderedChild=u.prevSibling}return c(d,"commitChildren"),Mt(()=>{d()}),E(jt,{children:[E(S,{marginLeft:e.depth*2,children:[m(S,{width:2,children:r&&m(C,{children:n?"\u25BC":"\u25B6"})}),vl(t),a(t)]}),n&&m(Ds.Provider,{value:{...e,depth:e.depth+1,registerChildItem:f},children:i})]})}c(gt,"TreeItem");function vl({active:s,label:e}){return m(S,{width:32,children:m(C,{inverse:s,children:e})})}c(vl,"defaultRenderLabel");function kl(s){return m(C,{})}c(kl,"defaultRenderValue");const We=c(({label:s,onPress:e,hotkey:t})=>m(gt,{label:s,onInput:c(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:c(()=>m(S,{children:m(C,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),eo=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=U(e),[l,u]=U(!1);return Mt(()=>{l||a(e)},[l,e]),m(gt,{label:s,value:e,onInput:c(({key:f,active:d})=>n?!1:l?(f.escape&&u(!1),f.return&&(t(o),u(!1)),!0):d&&f.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const f=o,d=r?r.repeat(f.length):f;return m(S,{children:n||!l?m(C,{dimColor:!0,children:d}):E(jt,{children:[m(S,{width:d.length+1,children:m(or,{...i,focus:l,value:f,onChange:a})}),m(C,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),Tl=c(s=>m(eo,{...s,mask:"*"}),"SecretField"),ce=c(({children:s,showHelp:e=!1})=>{const t=_n({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=U(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};Mt(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return c(o,"walkTree"),Me((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,f;for(const d of o(t.current))if(d.label!=null){if(u===n&&(f=d),d&&d.onInput?.({input:a,key:l,active:d===n}))return;u=d}l.upArrow?r(d=>d.prevSibling?.lastRenderedChild??d.prevSibling??d.parent??t.current):l.downArrow?r(d=>f??d):l.pageUp?r(()=>t.current.firstChild??t.current):l.pageDown?r(()=>t.current.lastRenderedChild??t.current):l.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):l.leftArrow?r(d=>d.parent??t.current):l.rightArrow&&r(d=>d.lastRenderedChild?d.firstChild:d)}),m(Ds.Provider,{value:i,children:E(S,{flexDirection:"column",children:[m(gt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(S,{marginTop:1,flexDirection:"column",children:m(C,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ce.Item=gt,ce.TextField=eo;function Ve({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=U([]),{fetchElements:a,getSyncedElementsByType:l}=de();return ze(()=>{c(async()=>{try{await a();const f=l(e);o(f.map(d=>d.data))}catch(f){console.error(String(f))}},"loadElements")()},[e,a,l,o]),m(gt,{label:s,children:i.map(u=>m(gt,{label:u.name,children:e===N.Action&&E(jt,{children:[t&&n&&m(We,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&m(We,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(Ve,"WorkspaceElementsTreeItem");function El({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=de(),[i,o]=U(""),a=e,l=c(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=c(async(h,g)=>{try{await t({[h]:g}),l("\u2705 Configuration updated!")}catch{l("\u274C Error updating configuration")}},"updateField"),f=c(async()=>{try{if(e){const h=_e.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(N.Action);await Wn({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:g.filter(y=>!a?.excludedActionKeys?.includes(y.key)).map(y=>y.data)}}),l("\u2705 Code generated successfully!")}}catch{l("\u274C Error saving configuration")}},"handleSaveConfig"),d=c(async()=>{try{const h=_e.loadConfig();h?(await t(h),l("\u2705 Configuration reloaded successfully!")):l("\u274C No configuration found to reload")}catch{l("\u274C Error reloading configuration")}},"handleReloadConfig");return E(S,{flexDirection:"column",gap:1,children:[m(C,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(S,{paddingX:2,children:E(ce,{showHelp:!0,children:[E(ce.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[E(ce.Item,{label:"Project",children:[m(ce.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(Tl,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ce.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),m(ce.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),E(ce.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[E(ce.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>m(C,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(We,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),m(We,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),m(ce.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),E(ce.Item,{label:"Workspace Elements",children:[m(Ve,{label:"Actions",elementType:N.Action,isActionExcluded:c(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:c(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:c(h=>{(async()=>{try{await Wn({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),l("\u2705 Code generated successfully!")}catch{l("\u274C Error generating code")}})()},"generateCode")}),m(Ve,{label:"Flows",elementType:N.Flow}),m(Ve,{label:"Data Sources",elementType:N.DataSource}),m(Ve,{label:"Field Mappings",elementType:N.FieldMapping}),m(Ve,{label:"Packages",elementType:N.Package}),m(Ve,{label:"App Data Schemas",elementType:N.AppDataSchema}),m(Ve,{label:"App Event Types",elementType:N.AppEventType})]})]}),m(We,{label:"Save Configuration",onPress:f,hotkey:"s"}),m(We,{label:"Reload Configuration",onPress:d,hotkey:"r"}),m(We,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(S,{paddingX:2,children:m(C,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(El,"ConfigManager");const to=Mn(process.cwd());function Il({cwd:s,children:e}){return m(to.Provider,{value:s,children:e})}c(Il,"CwdProvider");function Ol(){return jn(to)}c(Ol,"useCwd");function Rs({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Il,{cwd:n,children:m(Zo,{value:{fetcher:Sa()},children:m(bl,{membraneCLIService:t,children:e})})})}c(Rs,"Layout");function Al(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
145
- `)).action(()=>{Fn(Re.createElement(Rs,{membraneCLIService:e,children:Re.createElement(El,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Al,"setupConfigCommand");function $l({currentPat:s,onSubmit:e}){const[t,n]=U(""),[r,i]=U(!1),[o,a]=U(null);return E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(C,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(or,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:E(C,{children:[m(_t,{type:"dots"})," Validating token..."]})}),o&&m(C,{color:"red",children:o})]})}c($l,"PersonalAccessTokenInput");function no({onExit:s,showEscOption:e=!0}){const[t,n]=U(""),{data:r,error:i,isLoading:o}=tr("/account"),{updateConfig:a}=de(),l=r?.workspaces,u=o;if(Me((p,w)=>{w.escape&&s?.()}),u)return E(S,{children:[m(_t,{}),m(C,{children:" Fetching workspaces..."})]});if(i)return E(S,{flexDirection:"column",children:[E(C,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(p=>({label:p.name,value:p.id})),h=d.length,g=l?.length??0;async function y(p){const w=f.find($=>$.id===p);if(!w)return;const{key:k,secret:T}=w;!k||!T||(await a({workspaceKey:k,workspaceSecret:T}),s?.())}return c(y,"handleSelect"),E(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),E(S,{marginTop:1,children:[m(C,{children:"Search: "}),m(Qo,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&E(C,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(Xo,{options:d,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]})}c(no,"SelectWorkspace");var Lt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Lt||{});const Nl={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ms=[Lt.Authenticate,Lt.ConnectWorkspace];function so({onComplete:s}){const{config:e}=de(),[t,n]=U(!1),[r,i]=U(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=fr(),l=Ms[r],u=r+1,f=Ms.length,d=Ms.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:Nl[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new dr;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),ba(p),i(k=>k+1)}catch(k){console.error(k)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Me((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(C,{children:"\u2705 Setup complete. You are ready to go!"})}):E(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",E(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(C,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(y=>m(xl,{status:y.status,label:y.label},y.id))})]}),l===Lt.Authenticate&&m($l,{currentPat:a,onSubmit:h}),l===Lt.ConnectWorkspace&&m(no,{onExit:g,showEscOption:!1})]})}c(so,"Setup");function xl({status:s,label:e}){return E(S,{children:[E(S,{width:2,children:[s==="current"&&m(_t,{type:"dots"}),s==="done"&&m(C,{children:"\u2705"})]}),m(C,{dimColor:s!=="current",children:e})]})}c(xl,"StepDisplay");function Pl(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
146
- `)).action(t=>{t.key&&t.secret?_e.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):Fn(Re.createElement(Rs,{membraneCLIService:e,children:Re.createElement(so,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Pl,"setupInitCommand");async function ro(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Kn.sign(n,e)}c(ro,"generateMcpAccessToken");async function Ll(s,e){return(await Ct.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Ll,"fetchOpenApiSchema");function Pe(s,e=!0,t,n=new Set){if(!s)return e?B.string():B.string().optional();if(Object.keys(s).length===0)return e?B.any():B.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return B.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Pe(o,e,t,n)}return B.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const l=s.required?.includes(o)??!1;i[o]=Pe(a,l,t,n)}if(Object.keys(i).length>0){if(r=B.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Pe(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Pe(s.additionalProperties,!1,t,n);r=B.record(B.string(),o)}else r=B.record(B.string(),B.any())}else if(s.type==="array"){const i=s.items?Pe(s.items,!0,t,n):B.any();r=B.array(i)}else if(s.anyOf)r=B.any();else{switch(s.type){case"integer":r=B.coerce.number().int();break;case"number":r=B.coerce.number();break;case"boolean":r=B.coerce.boolean();break;case"string":default:r=B.string();break}s.format==="uuid"?r=B.string().uuid():s.format==="email"?r=B.string().email():s.format==="date"?r=B.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=B.string().datetime()),s.enum&&(r=B.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}c(Pe,"convertOpenApiSchemaToZod");function io(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(io,"extractPathParameters");function Dl(s,e,t,n,r,i,o,a){const l=s.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,u=s.description||s.summary||`${t.toUpperCase()} ${e}`,f={},d={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")d[y.name]=Pe(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Pe(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(d).length>0&&(f.params=B.object(d).describe("Path parameters")),Object.keys(h).length>0&&(f.query=B.object(h).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const p=s.requestBody.content["application/json"].schema;p?f.body=Pe(p,y,o).describe("Request body (JSON)"):f.body=B.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?f.body=y?B.string().describe("Request body (binary/text)"):B.string().optional().describe("Request body (binary/text)"):f.body=B.any().describe("Request body")}const g=Object.keys(f).length>0?B.object(f):B.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=io(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const L=p.filter(q=>!(q in y.params));if(L.length>0)throw new Error(`Missing required path parameters: ${L.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[L,q]of Object.entries(y.params)){const A=`{${L}}`;w.includes(A)&&(w=w.replace(A,String(q)))}const k=io(w);if(k.length>0)throw new Error(`Unresolved path parameters: ${k.join(", ")}`);const T=new URLSearchParams;if(y.query)for(const[L,q]of Object.entries(y.query))q!=null&&T.append(L,String(q));T.toString()&&(w+=`?${T.toString()}`);const $=await ro(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${$}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(I.headers["Content-Type"]="application/json",I.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(I.headers["Content-Type"]="application/octet-stream",I.data=y.body):s.requestBody?.content?.["text/plain"]?(I.headers["Content-Type"]="text/plain",I.data=y.body):(I.headers["Content-Type"]="application/json",I.data=y.body));const P=await Ct.request({url:w,...I});return{content:[{type:"text",text:P.data===""?"":JSON.stringify(P.data,null,2)}]}}catch(p){return Ct.isAxiosError(p)?{content:[{type:"text",text:`Error: ${p.response?.data?`HTTP ${p.response.status}: ${p.response.statusText} - ${JSON.stringify(p.response.data)}`:`HTTP ${p.response?.status||"unknown"}: ${p.message}`}`}],isError:!0}:p instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${p.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Dl,"createApiTool");function Rl(s,e,t,n,r){const i=[];if(!s.paths)return i;const o=s.components||{};for(const[a,l]of Object.entries(s.paths))if(typeof l=="object"&&l!==null){for(const[u,f]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&f&&typeof f=="object"){const d=Dl(f,a,u,e,t,n,o,r);i.push(d)}}return i}c(Rl,"convertOpenApiToTools");function Ml(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
147
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Kt();e||(console.error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials. Please provide them in the configuration file, command line, or environment variables."),process.exit(1));const t=e.apiUri||Gn,n=await ro(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Ll(t,n),i=Rl(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new ta({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
144
+ `,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=vn(e),n=pt(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=vn(e),n=pt(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 Ui(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Fi||null,prettyErrors:e}}l(Ui,"parseOptions");function Gc(s,e={}){const{lineCounter:t,prettyErrors:n}=Ui(e),r=new Ts(t?.addNewLine),i=new Cs(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(mn(s,t)),a.warnings.forEach(mn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}l(Gc,"parseAllDocuments");function Ji(s,e={}){const{lineCounter:t,prettyErrors:n}=Ui(e),r=new Ts(t?.addNewLine),i=new Cs(e);let o=null;for(const a of i.compose(r.parse(s),!0,s.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ue(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(mn(s,t)),o.warnings.forEach(mn(s,t))),o}l(Ji,"parseDocument");function zc(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Ji(s,t);if(!r)return null;if(r.warnings.forEach(i=>ti(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:n},t))}l(zc,"parse");function Hc(s,e,t){let n=null;if(typeof e=="function"||Array.isArray(e)?n=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(s===void 0){const{keepUndefined:r}=t??e??{};if(!r)return}return Fe(s)&&!n?s.toString(t):new St(s,n,t).toString(t)}l(Hc,"stringify");var Yc=Object.freeze({__proto__:null,Alias:Zt,CST:Jc,Composer:Cs,Document:St,Lexer:_i,LineCounter:Fi,Pair:X,Parser:Ts,Scalar:L,Schema:An,YAMLError:ms,YAMLMap:se,YAMLParseError:Ue,YAMLSeq:Oe,YAMLWarning:Ei,isAlias:Ie,isCollection:V,isDocument:Fe,isMap:st,isNode:G,isPair:W,isScalar:U,isSeq:rt,parse:zc,parseAllDocuments:Gc,parseDocument:Ji,stringify:Hc,visit:Ke,visitAsync:Yt});class Is extends Go{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 re={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Zc={ignored:Ca,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:20,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Qc extends Is{static{l(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ie(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(O.existsSync(this.membraneDir)||O.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=Vo.watch(this.membraneDir,Zc),this.watcher.on("add",e=>this.handleFileSystemEvent(re.Updated,e)).on("change",e=>this.handleFileSystemEvent(re.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(re.Deleted,e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.clearAllLocks(),this.emit(re.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=x.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=x.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+x.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=x.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===re.Deleted){this.removeFromCache(n);const a={filePath:t,relativePath:n,data:void 0};b.info(`[local] ${e}: ${a.relativePath}`),this.emit(e,a);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r))return;const o=this.processFileEvent(t,r);this.updateCache(n,r),o&&(b.info(`[local] ${e}: ${o.relativePath}`),this.emit(e,o))}readFileContent(e){return O.readFileSync(e,"utf8")}processFileEvent(e,t){const n=x.relative(this.membraneDir,e);let r;try{r=t?Yc.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t){if(!t)return this.contentCache[e]!==void 0;const n=this.getContentHash(t);return this.contentCache[e]!==n}getContentHash(e){return Jo.createHash("sha256").update(e).digest("hex")}updateCache(e,t){if(!t){delete this.contentCache[e];return}this.contentCache[e]=this.getContentHash(t)}removeFromCache(e){delete this.contentCache[e]}clearCache(){Object.keys(this.contentCache).forEach(e=>{delete this.contentCache[e]})}initializeContentCache(){O.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=O.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=x.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=O.readFileSync(r,"utf8"),o=x.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Os=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Os||{});const Xc={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class el extends Is{static{l(this,"RemoteElementWatcher")}constructor(e=Xc){super(),this.config=e}eventSource;debounceTimeouts=new Map;reconnectAttempts=0;reconnectTimeout;connectionTimeout;isStarted=!1;isConnected=!1;async start(){this.isStarted||(this.isStarted=!0,await this.connect())}async stop(){this.isStarted&&(this.isStarted=!1,this.isConnected=!1,this.clearReconnectTimeout(),this.clearConnectionTimeout(),this.clearAllDebounceTimeouts(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0))}async connect(){try{b.debug("[remote-events] Connecting to server"),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0);const e=await D.getClient(process.cwd()),t=await e.getToken();if(!t)throw new Error("No auth token available");const n=`${e.apiUri}/sse/workspace?token=${encodeURIComponent(t)}`;b.debug("[remote-events] Subscribing to workspace events"),this.eventSource=new zo(n),this.setupEventSourceHandlers()}catch(e){b.debug(`[remote-events] Failed to connect: ${e}`),this.emit("error",{error:e}),this.scheduleReconnect()}}setupEventSourceHandlers(){this.eventSource&&(this.eventSource.onopen=()=>{b.debug("[remote-events] Connected to server"),this.reconnectAttempts=0,this.isConnected=!0,this.resetConnectionTimeout(),this.emit("connected",{})},this.eventSource.onmessage=e=>{try{this.resetConnectionTimeout();const t=JSON.parse(e.data);this.handleElementUpdate(t)}catch(t){b.debug(`[remote-events] Failed to parse workspace event: ${t}`)}},this.eventSource.onerror=e=>{b.debug(`[remote-events] Connection error: ${JSON.stringify(e,null,2)}`),this.isConnected=!1,this.clearConnectionTimeout(),this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.emit("disconnected",{}),this.isStarted&&this.scheduleReconnect()})}handleElementUpdate(e){if(e.type!==No.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===N.Connector){const{filePath:i,eventType:o,newPath:a}=r;return b.debug(`[remote-watcher] Received connector event - elementId: ${t}, filePath: ${i}, eventType: ${o}`),this.scheduleConnectorFileUpdate(t,i,o,a)}return this.scheduleElementUpdate(t,n)}}scheduleElementUpdate(e,t){const n=this.debounceTimeouts.get(e);n&&clearTimeout(n);const r=setTimeout(()=>{this.debounceTimeouts.delete(e),this.emit("updated",{elementId:e,elementType:t})},this.config.debounceMs);this.debounceTimeouts.set(e,r)}scheduleConnectorFileUpdate(e,t,n,r){const i=JSON.stringify({connectorId:e,filePath:t}),o=this.debounceTimeouts.get(i);o&&clearTimeout(o);const a=setTimeout(()=>{this.debounceTimeouts.delete(i),this.emit("connector-file-updated",{connectorId:e,filePath:t,eventType:n,newPath:r})},this.config.debounceMs);this.debounceTimeouts.set(i,a)}scheduleReconnect(){if(!this.isStarted||this.reconnectAttempts>=this.config.maxReconnectAttempts){this.reconnectAttempts>=this.config.maxReconnectAttempts&&(b.error("[remote-events] Max reconnection attempts reached. Connection will not be retried."),this.emit("error",{error:new Error("Max reconnection attempts reached")}));return}this.reconnectTimeout&&clearTimeout(this.reconnectTimeout),this.reconnectAttempts++;const e=this.config.reconnectIntervalMs*Math.pow(2,this.reconnectAttempts-1),t=Math.random()*.3*e,n=Math.min(e+t,this.config.maxBackoffMs);b.debug(`[remote-events] Reconnecting in ${Math.round(n)}ms (attempt ${this.reconnectAttempts})`),this.reconnectTimeout=setTimeout(()=>{this.connect()},n)}clearReconnectTimeout(){this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0)}resetConnectionTimeout(){this.clearConnectionTimeout(),this.connectionTimeout=setTimeout(()=>{this.isConnected&&this.isStarted&&(b.debug("[remote-events] Connection timeout detected, reconnecting..."),this.isConnected=!1,this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.scheduleReconnect())},this.config.connectionTimeoutMs)}clearConnectionTimeout(){this.connectionTimeout&&(clearTimeout(this.connectionTimeout),this.connectionTimeout=void 0)}clearAllDebounceTimeouts(){this.debounceTimeouts.forEach(e=>clearTimeout(e)),this.debounceTimeouts.clear()}}class Wi{static{l(this,"ElementsCache")}elements=new Map;typeIndex=new Map;internalIdIndex=new Map;constructor(e){e&&this.addAll(e)}add(e){const t=e.id;this.elements.set(t,e),this.typeIndex.has(e.type)||this.typeIndex.set(e.type,new Set),this.typeIndex.get(e.type).add(t),e.data?.id&&this.internalIdIndex.set(e.data.id,t)}remove(e){const t=e.id,n=this.elements.delete(t);if(n){const r=this.typeIndex.get(e.type);r&&(r.delete(t),r.size===0&&this.typeIndex.delete(e.type)),e.data?.id&&this.internalIdIndex.delete(e.data.id)}return n}put(e){this.elements.has(e.id)&&this.remove(e),this.add(e)}get(e){return this.elements.get(e)}getByInternalId(e){const t=this.internalIdIndex.get(e);if(t)return this.elements.get(t)}getElementsByType(e){const t=this.typeIndex.get(e);return t?Array.from(t).map(n=>this.elements.get(n)).filter(n=>n!==void 0):[]}getAll(){return Array.from(this.elements.values())??[]}getTypes(){return Array.from(this.typeIndex.keys())}addAll(e){for(const t of e)t&&this.add(t)}removeAll(e){for(const t of e)this.remove(t)}getElementIdsByType(e){return this.typeIndex.get(e)}clear(){this.elements.clear(),this.typeIndex.clear(),this.internalIdIndex.clear()}getAllIds(){return new Set(this.elements.keys())}}const mt="connectors",ve="development",As={};async function Vi(){const s=new Set,t=(await D.withClient(a=>a.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors"),await D.withClient(a=>a.get(`/connectors?workspaceId=${t}`)),b.info("[connectors] Loading public connectors");const r=$e(),o=(F.existsSync(r)?F.readdirSync(r):[]).filter(a=>{if(a.startsWith("."))return!1;const c=_.join(r,a);try{return F.statSync(c).isDirectory()}catch{return!1}});for(const a of o){b.info(`[connectors] Loading connector from: ${a}`);const c=F.readdirSync(_.join(r,a)),u=await $s(a);if(!u)continue;"baseUri"in u&&delete u.baseUri;let f;if(u.uuid&&(f=await D.withClient(h=>h.get(`/connectors/${u.uuid}`),!1)),f)n[u.id]=f.id,b.info(`[connectors] Matched ${u.name} uuid: ${u.uuid}`),f.isPublic||(f.archivedAt&&(b.info(`[connectors] Restoring archived connector ${u.name}`),await D.withClient(h=>h.post(`connectors/${f.id}/restore`))),b.info(`[connectors] Updating connector ${u.name}`),await D.withClient(h=>h.patch(`connectors/${f.id}`,{...u,workspaceId:t})));else if(!n[u.id]&&!f?.isPublic){let h=!1;try{const g=await Ns({connectorId:u.id});g&&g.isPublic&&(h=!0)}catch{}if(!h){b.info(`[connectors] Creating custom connector ${u.name} (${u.key})`);const g=await D.withClient(w=>w.post("connectors",{...u,workspaceId:t}));n[u.id]=g.id}}const d=c.filter(h=>F.statSync(_.join(r,a,h)).isDirectory());for(const h of d)await sl({connector:u,version:h,connectorId:n[u.id]}),s.add(u.id)}return{connectorsMapping:n,pushedConnectors:Array.from(s)}}l(Vi,"pushConnectors");async function Gi({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=lr(),o=await Ns({connectorId:s});if(!o.isPublic||t){if(!o?.key){console.error(`[connectors] Connector ${s} has no key. Skipping..`),b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await rl({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await il({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}l(Gi,"pullRemoteConnector");function $e(){const s=zn();return _.join(s.membraneDirPath,mt)}l($e,"getConnectorsPath");async function $s(s){const e=_.join($e(),s,`${s}.yml`);return Zn(e,!1)}l($s,"readConnector");async function tl(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=sr("zip",{zlib:{level:9}});r.on("close",()=>{b.success(`[connectors] Successfully created ${e}`),t()}),r.on("end",()=>{b.info("[connectors] Data has been drained")}),i.on("warning",a=>{a.code==="ENOENT"?console.warn(a):n(a)}),i.on("error",a=>{n(a)}),i.pipe(r);const o=F.readdirSync(s);for(const a of o){const c=_.join(s,a),u=F.statSync(c);u.isFile()?i.file(c,{name:a}):u.isDirectory()&&i.directory(c,a)}i.finalize()})}l(tl,"createZipArchive");async function nl(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=ir.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const c=_.join(e,o);F.mkdirSync(c,{recursive:!0}),i.autodrain()}else{const c=_.join(e,o),u=_.dirname(c);F.mkdirSync(u,{recursive:!0});const f=F.createWriteStream(c);i.pipe(f),f.on("finish",()=>{})}}),r.on("end",()=>{b.success(`[connectors] Successfully extracted to ${e}`),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}l(nl,"extractZipArchive");async function sl({connector:s,version:e,connectorId:t}){const n=_.join($e(),ke(s),zi(e)),r=_.join(n,"src"),i=_.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await tl(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new rr;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==ve)b.info(`[connectors] Uploading connector ${t}`),await D.withClient(c=>c.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await D.withClient(u=>u.get(`/connectors/${t}/versions`))).find(u=>u.version==e)){b.info(`[connectors] Version ${e} already published`);return}b.info(`[connectors] Publishing version ${e} of connector ${t}`),await D.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`),console.error(`[connectors] Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}l(sl,"pushConnectorVersion");async function Ns({connectorId:s}){if(s){if(As[s])return As[s];try{const e=await D.withClient(t=>t.get(`connectors/${s}`),!1);return As[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),console.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}l(Ns,"getConnector");async function rl({basePath:s,connector:e}){const t=ke(e),n=_.join(s,mt,t);F.mkdirSync(n,{recursive:!0});const r=_.join(n,`${ke(e)}.yml`);F.writeFileSync(r,le.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}l(rl,"pullConnector$1");async function il({connector:s,connectorVersion:e,basePath:t}){const n=ke(s),r=zi(e),i=_.join(t,"connectors",n,r),o=await D.withClient(c=>c.get(`connectors/${s.id}/download`,{version:e},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6}));F.mkdirSync(i,{recursive:!0});const a=_.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const c=_.join(i,"src");F.mkdirSync(c,{recursive:!0}),await nl(o,c)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}l(il,"pullConnectorVersion");function ke(s){return s.key}l(ke,"getConnectorDirName");function zi(s){return s??ve}l(zi,"getConnectorVersionDirName");function ol(s){const e=lr(),t=ke(s);return _.join(e,mt,t)}l(ol,"getConnectorDirPath");function al(s){return s.match(`${mt}/[^/]+/${ve}/src/.*`)!==null}l(al,"isConnectorSourceFile");async function cl(s){const e=s.match(`${mt}/([^/]+)/${ve}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await $s(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id,o=F.readFileSync(s,"utf-8");await D.withClient(a=>a.put(`connectors/${i}/files/${n}`,o,{headers:{"Content-Type":"text/plain"}})),b.info(`[connectors] Pushed file ${n} for connector ${r.name}`)}l(cl,"putConnectorFile");async function ll(s){const e=s.match(`${mt}/([^/]+)/${ve}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await $s(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await D.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}l(ll,"deleteConnectorFile");async function ul(s,e){try{const t=await D.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await D.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=ke(t),i=_.join($e(),r,ve,"src",e);F.mkdirSync(_.dirname(i),{recursive:!0}),n!=null?(F.writeFileSync(i,n),b.info(`[connectors] Pulled file ${e} for connector ${t.name}`)):F.existsSync(i)&&(F.unlinkSync(i),b.info(`[connectors] Deleted file ${e} for connector ${t.name}`))}catch(t){b.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`),console.error(`[connectors] Failed to pull connector file ${e} for connector ${s}: ${t}`)}}l(ul,"pullConnectorFile");async function fl(s,e){const t=await D.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=ke(t),r=_.join($e(),n,ve,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}l(fl,"deleteLocalConnectorFile");async function dl(s,e,t){if(t&&e!==t)try{const n=await D.withClient(c=>c.get(`connectors/${s}`),!1);if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=ke(n),i=_.join($e(),r,ve,"src"),o=_.join(i,e),a=_.join(i,t);F.existsSync(o)&&(F.mkdirSync(_.dirname(a),{recursive:!0}),F.renameSync(o,a),b.info(`[connectors] Renamed directory from ${e} to ${t} for connector ${r}`))}catch(n){b.error(`[connectors] Failed to rename directory ${e} to ${t} for connector ${s}: ${n}`)}}l(dl,"renameLocalConnectorDirectory");async function hl(s,e){try{const t=await D.withClient(i=>i.get(`connectors/${s}`),!1);if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=ke(t),r=_.join($e(),n,ve,"src",e);if(F.existsSync(r)){const i=_.resolve($e());if(!_.resolve(r).startsWith(i))return;F.rmSync(r,{recursive:!0,force:!0}),b.info(`[connectors] Deleted directory ${e} for connector ${n}`)}}catch(t){b.error(`[connectors] Failed to delete directory ${e} for connector ${s}: ${t}`)}}l(hl,"deleteLocalConnectorDirectory");const H={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class pl extends Is{static{l(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e,b.setNotificationHandler(this)}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(H.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(H.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(H.ConfigChanged,{config:e})}setStats(e){this.emit(H.StatsChanged,{stats:e})}addLog(e){this.emit(H.LogAdded,{log:e})}setMcpStatus(e){this.emit(H.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(H.McpServersChanged,{servers:e}),await this.emitRemote({mcpServers:e.map(t=>({name:t.agentName,totalRequests:t.totalRequests}))})}async cleanup(){!this.clientId||this.isCleaningUp||(this.isCleaningUp=!0,this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0),await this.withErrorHandling(async()=>{await D.withClient(e=>e.delete(`/local-clients/${this.clientId}`))}),this.clientId=void 0)}async registerWithRemoteServer(){if(this.clientId)return;const e=await this.withErrorHandling(async()=>await D.withClient(t=>t.post("/local-clients",{hostname:nr.hostname(),workingDirectory:process.cwd()})));e?.id?this.clientId=e.id:this.addLog({timestamp:new Date().toISOString(),message:"Failed to register with remote server",type:"error"})}async startHeartbeatLoop(){this.heartbeatInterval=setInterval(async()=>{this.clientId&&await this.sendHeartbeat()},this.config.heartbeatIntervalMs)}async sendHeartbeat(){this.clientId&&await this.withErrorHandling(async()=>{await D.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await D.withClient(t=>t.patch(`/local-clients/${this.clientId}`,e))})}async withErrorHandling(e){try{return await e()}catch(t){const n=t instanceof Error?t.message:String(t);return this.addLog({timestamp:new Date().toISOString(),message:`Failed to connect to remote: ${n}`,type:"error"}),null}}}const Ne=new pl({heartbeatIntervalMs:15e3}),Hi=[N.AppDataSchema,N.AppEventType,N.DataLinkTable,N.DataSource,N.FieldMapping,N.Action,N.Flow,N.Package];class Rt{static{l(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Ne,this.localCache=new Wi,this.remoteCache=new Wi,this.localRepo=new Ka(this.localCache),this.remoteRepo=new Ba(this.remoteCache)}clear(){this.changes=[]}needsForcedSync(){return this.changes.some(e=>e.isConflict)}needsSync(){return this.changes.length>0}async getStats(){const e=this.localCache.getAll(),t={};return e.forEach(n=>{t[n.type]=(t[n.type]||0)+1}),t}async fetchElements(){const e=await this.localRepo.getElements(),t=await this.remoteRepo.getElements();this.localCache.addAll(e),this.remoteCache.addAll(t)}async updateElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{const i=await n.putElement(e);r.put(i)}catch(i){throw b.error(`Failed to update element ${e.id}: ${i}`),i}}async deleteElement(e,t){const n=this.getHandler(t),r=this.getCache(t);try{await n.deleteElement(e,{elements:n.cache.getAll(),connectorsMapping:n.connectorsMapping}),r.remove(e)}catch(i){throw b.error(`Failed to delete element ${e.id}: ${i}`),i}}async pullConnectors(e=!1){const t=this.remoteCache.getElementsByType(N.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await Gi({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const{connectorsMapping:e}=await Vi();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===te.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===te.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Qc({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(re.Updated,e=>this.handleLocalEvent(e,re.Updated)),this.localWatcher.on(re.Deleted,e=>this.handleLocalEvent(e,re.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new el,this.remoteWatcher.on(Os.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Os.ConnectorFileUpdated,({connectorId:e,filePath:t,eventType:n,newPath:r})=>this.handleRemoteConnectorFileEvent(e,t,n,r)),await this.remoteWatcher.start(),b.success("[remote] Tracking changes..")}async stopWatching(){this.localWatcher&&(await this.localWatcher.stop(),this.localWatcher=void 0),this.remoteWatcher&&(await this.remoteWatcher.stop(),this.remoteWatcher=void 0)}async handleRemoteElementEvent(e,t){try{const n=await this.remoteRepo.getByInternalId(e,t),r=!!n?.data.archivedAt||!!n?.data.isDeactivated;if(!n||r){const o=n||this.remoteCache.getByInternalId(e);return o?(b.info(`[${this.getDirectionLabel(te.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,te.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(te.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,te.INCOMING)),t===N.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,c=await Ns({connectorId:o});if(!c?.key)return;const u=ol(c);await this.localWatcher?.executeWithPathLock(u,async()=>Gi({connectorId:o,connectorVersion:a,allConnectors:!1,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions}))}}catch(n){b.error(`[sync] Error handling remote event: ${n}`)}}async handleRemoteConnectorFileEvent(e,t,n,r){try{switch(n){case Nn.ConnectorFileDeleted:await fl(e,t);break;case Nn.ConnectorDirectoryRenamed:await dl(e,t,r);break;case Nn.ConnectorDirectoryDeleted:await hl(e,t);break;default:await ul(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(al(e.filePath))switch(t){case re.Updated:await cl(e.filePath);break;case re.Deleted:await ll(e.filePath);break}else{let n=z.fromPathAndData(e.filePath,e.data);if(!n){const r=z.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(te.OUTGOING)}] ${ja.toSentenceCase(t)}: ${n.id}`),t){case re.Updated:await this.updateElement(n,te.OUTGOING);break;case re.Deleted:await this.deleteElement(n,te.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=Rt.getChanges(te.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=Rt.getChanges(te.OUTGOING,this.localCache,this.remoteCache);return this.updateChanges(e),e}async resolveChanges(){if(!this.needsSync())return;b.info("[resolver] Resolving changes.."),b.info("[resolver] Resolving integration elements");const e=this.changes.filter(r=>r.element.type===N.Integration);await Promise.all(e.map(async r=>this.resolveChange(r))),e.length>0&&(await this.fetchElements(),this.changes=this.changes.length>0&&this.changes[0]?.direction===te.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==N.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of Hi){const i=t.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.info("[resolver] Resolving integration level elements");const n=this.changes.filter(r=>r.element.hasParent());for(const r of Hi){const i=n.filter(o=>o.element.type===r);b.info(`[resolver] Resolving ${r} elements`),await Promise.all(i.map(async o=>this.resolveChange(o)))}b.success("[resolver] Resolved changes")}async resolveChange(e){switch(e.type){case be.DELETE:return this.deleteElement(e.element,e.direction);case be.CREATE:return this.updateElement(e.element,e.direction);case be.UPDATE:return this.updateElement(e.element,e.direction)}}static getChanges(e,t,n){const r=t.getAllIds(),i=n.getAllIds(),o=new Set([...r,...i]),a=[];for(const c of o){const u=t.get(c),f=n.get(c),d=Rt.detectChangeForElement(u,f,e);d&&a.push(d)}return a}updateChanges(e){if(this.changes=e,this.needsForcedSync()){const t=e.filter(n=>n.isConflict);b.warning("[resolver] Conflicts detected"),this.notifier.setConflicts(t)}}clearChanges(){this.changes=[]}getDirectionLabel(e){switch(e){case te.INCOMING:return"local\u2190remote";case te.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:be.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:be.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:be.UPDATE,element:e,direction:n,isConflict:!1}:null}}const xe=x.join(Ho.tmpdir(),"membrane-mcp-status"),Yi=3e4;class ml{static{l(this,"McpStatusService")}constructor(e=2e3){this.pollIntervalMs=e}isRunning=!1;pollInterval;async start(){this.isRunning||(this.isRunning=!0,this.pollInterval=setInterval(async()=>await this.checkStatus(),this.pollIntervalMs),await this.checkStatus())}async stop(){this.pollInterval&&(clearInterval(this.pollInterval),this.pollInterval=void 0,this.isRunning=!1)}async checkStatus(){try{const e=process.cwd(),t=kn(void 0,e),n=Zi(e);t&&Ne.setMcpStatus(t),await Ne.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function kn(s,e){try{const t=e||process.cwd();if(!s){const r=Zi(t);return r.length===0?null:r[0]}const n=Ls(s,t);if(O.existsSync(n)){const r=O.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>Yi)return Pt(s,t),null;const a=O.readFileSync(n,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(i.getTime()-u>Yi)return Pt(s,t),null}return c}}catch{s&&e&&Pt(s,e)}return null}l(kn,"getMcpStatus");function Zi(s){try{const e=s||process.cwd(),t=Ps(e);if(!O.existsSync(xe))return[];const n=O.readdirSync(xe),r=[];for(const i of n){const o=i.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=kn(a,e);c&&r.push(c)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}l(Zi,"getAllMcpStatusFiles");function xs(s){try{const t={...kn(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};O.existsSync(xe)||O.mkdirSync(xe,{recursive:!0});const n=Ls(s.processId,s.cwd);O.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}l(xs,"updateMcpStatus");function Pt(s,e){try{const t=e||process.cwd();if(s){const n=Ls(s,t);O.existsSync(n)&&O.unlinkSync(n)}else{const n=Ps(t);if(O.existsSync(xe)){const r=O.readdirSync(xe);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&O.unlinkSync(x.join(xe,i))}}}catch{}}l(Pt,"clearMcpStatus");function gl(s,e){const t=kn(s,e);t&&xs({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(gl,"trackToolExecution");function Ps(s){return Wo("md5").update(s).digest("hex").slice(0,8)}l(Ps,"getCwdHash");function Ls(s,e){const t=Ps(e);return x.join(xe,`mcp-${t}-${s}.json`)}l(Ls,"getStatusFilePath");const En={Agent:"agent",Cli:"cli"},M={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class yl{static{l(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Ne,this.mcpStatusService=new ml,this.syncService=new Rt,this.setupProcessCleanup()}initialized=!1;notifier;mcpStatusService;syncService;isShuttingDown=!1;currentConfig=null;get config(){return this.currentConfig}getSyncedElements(){return this.syncService.localCache.getAll()}getSyncedElementsByType(e){return this.syncService.localCache.getElementsByType(e)}async fetchElements(){await this.syncService.fetchElements()}async pullWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&D.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(M.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(M.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to pull workspace: ${n}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async pushWorkspace(e={}){let t=!1;try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&D.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(M.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force){await this.notifier.setState(M.CONFLICTS),e.watch||(t=!0);return}await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(n){t=!0,b.error(`Failed to push workspace: ${n}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}finally{if(e.saveLogs&&b.saveLogsToFile(),t)process.exit(1);else return e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(M.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(M.SYNCED),e.watch&&(await this.notifier.setState(M.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(M.NOT_INITIALIZED);try{await this.loadConfig(),_e.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(M.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(M.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(M.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=_e.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=_e.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===En.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===En.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===En.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop())}setupProcessCleanup(){["SIGINT","SIGTERM","uncaughtException","unhandledRejection"].forEach(t=>process.on(t,()=>this.shutdown())),process.on("beforeExit",t=>{t===0&&this.shutdown()})}}const Qi=Mn(null);function wl({children:s,membraneCLIService:e}){const{data:t}=tr("/account"),[n,r]=q(M.NOT_INITIALIZED),[i,o]=q([]),[a,c]=q({}),[u,f]=q([]),[d,h]=q(null),w=t?.workspaces?.find(p=>p.workspaceKey===d?.workspaceKey)||null;return ze(()=>{const p=l(({state:I})=>r(I),"handleStateChanged"),y=l(({stats:I})=>c(I),"handleStatsChanged"),k=l(({log:I})=>f(P=>[...P,I]),"handleLogAdded"),E=l(({conflicts:I})=>o(I),"handleConflictsUpdated"),A=l(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(H.StateChanged,p),e.notifier.on(H.StatsChanged,y),e.notifier.on(H.LogAdded,k),e.notifier.on(H.ConflictsChanged,E),e.notifier.on(H.ConfigChanged,A),e.init(),()=>{e.notifier.off(H.StateChanged,p),e.notifier.off(H.StatsChanged,y),e.notifier.off(H.LogAdded,k),e.notifier.off(H.ConflictsChanged,E),e.notifier.off(H.ConfigChanged,A)}},[]),m(Qi.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:w,conflicts:i,config:d,updateConfig:l(p=>e.updateConfig(p),"updateConfig"),resolveConflicts:l(p=>e.syncWorkspaces(p),"resolveConflicts"),pull:l(p=>e.pullWorkspace(p),"pull"),push:l(p=>e.pushWorkspace(p),"push"),exit:l(()=>e.shutdown(),"exit"),fetchElements:l(()=>e.fetchElements(),"fetchElements"),getSyncedElementsByType:l(p=>e.getSyncedElementsByType(p),"getSyncedElementsByType")},children:s})}l(wl,"MembraneCLIServiceProvider");function de(){const s=jn(Qi);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}l(de,"useMembraneCLIService");const Rs=Mn(null),Xi=l(()=>{const s=jn(Rs);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),bl=l(s=>De.Children.count(s)>0,"hasChildren");function Sl(s){const e=Xi(),{label:t,value:n,isInitiallyExpanded:r}=s,i=_o(),o=_n(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[c,u]=q(r??!1),f={props:s,ref:o,id:i,active:a,expanded:c,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:d}=s,h=typeof d=="function"?d(f):d;return{...f,props:{...s,children:h},isParent:bl(h)}}l(Sl,"useTreeItem");function gt(s){const e=Xi(),t=Sl(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=vl}=s,c=t.ref;Mt(()=>{function h(g){return s.onInput?.(g)?!0:g.active&&g.key.rightArrow&&!n?(o(!0),!0):g.active&&g.key.leftArrow&&n?(o(!1),!0):!1}l(h,"onInput"),c.onInput=h},[c,s.onInput,n,o]),c.firstChild??={parent:c,index:0};let u=c.firstChild;function f(h){const g=u;return g.nextSibling||(g.nextSibling={parent:c,prevSibling:g,index:g.index+1}),u=g.nextSibling,g.label=h,g}l(f,"registerChildItem");function d(){c.lastRenderedChild=u.prevSibling}return l(d,"commitChildren"),Mt(()=>{d()}),T(jt,{children:[T(S,{marginLeft:e.depth*2,children:[m(S,{width:2,children:r&&m(C,{children:n?"\u25BC":"\u25B6"})}),Cl(t),a(t)]}),n&&m(Rs.Provider,{value:{...e,depth:e.depth+1,registerChildItem:f},children:i})]})}l(gt,"TreeItem");function Cl({active:s,label:e}){return m(S,{width:32,children:m(C,{inverse:s,children:e})})}l(Cl,"defaultRenderLabel");function vl(s){return m(C,{})}l(vl,"defaultRenderValue");const We=l(({label:s,onPress:e,hotkey:t})=>m(gt,{label:s,onInput:l(({input:n,key:r,active:i})=>i&&r.return||t&&t in r&&r[t]||n===t?(e(),!0):!1,"onInput"),renderValue:l(()=>m(S,{children:m(C,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),eo=l(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=q(e),[c,u]=q(!1);return Mt(()=>{c||a(e)},[c,e]),m(gt,{label:s,value:e,onInput:l(({key:f,active:d})=>n?!1:c?(f.escape&&u(!1),f.return&&(t(o),u(!1)),!0):d&&f.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:l(()=>{const f=o,d=r?r.repeat(f.length):f;return m(S,{children:n||!c?m(C,{dimColor:!0,children:d}):T(jt,{children:[m(S,{width:d.length+1,children:m(or,{...i,focus:c,value:f,onChange:a})}),m(C,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),kl=l(s=>m(eo,{...s,mask:"*"}),"SecretField"),ce=l(({children:s,showHelp:e=!1})=>{const t=_n({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=q(t.current),i={depth:0,isActiveByRef:l(a=>n===a,"isActiveByRef"),registerChildItem:l(()=>t.current,"registerChildItem"),activeItemRef:n};Mt(()=>{r(a=>a.parent?a.parent.lastRenderedChild&&a.index>a.parent.lastRenderedChild.index?a.parent.lastRenderedChild:a:t.current.firstChild??t.current)});function*o(a){a&&(yield a,yield*o(a.firstChild),a.nextSibling&&a!==a.parent?.lastRenderedChild&&(yield*o(a.nextSibling)))}return l(o,"walkTree"),Me((a,c)=>{if(n.onInput?.({input:a,key:c,active:!0}))return;let u,f;for(const d of o(t.current))if(d.label!=null){if(u===n&&(f=d),d&&d.onInput?.({input:a,key:c,active:d===n}))return;u=d}c.upArrow?r(d=>d.prevSibling?.lastRenderedChild??d.prevSibling??d.parent??t.current):c.downArrow?r(d=>f??d):c.pageUp?r(()=>t.current.firstChild??t.current):c.pageDown?r(()=>t.current.lastRenderedChild??t.current):c.tab?console.log({label:n.label,nextSibling:n.nextSibling?.label,prevSibling:n.prevSibling?.label,parent:n.parent?.label,firstChild:n.firstChild?.label,lastRenderedChild:n.lastRenderedChild?.label}):c.leftArrow?r(d=>d.parent??t.current):c.rightArrow&&r(d=>d.lastRenderedChild?d.firstChild:d)}),m(Rs.Provider,{value:i,children:T(S,{flexDirection:"column",children:[m(gt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(S,{marginTop:1,flexDirection:"column",children:m(C,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ce.Item=gt,ce.TextField=eo;function Ve({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=q([]),{fetchElements:a,getSyncedElementsByType:c}=de();return ze(()=>{l(async()=>{try{await a();const f=c(e);o(f.map(d=>d.data))}catch(f){console.error(String(f))}},"loadElements")()},[e,a,c,o]),m(gt,{label:s,children:i.map(u=>m(gt,{label:u.name,children:e===N.Action&&T(jt,{children:[t&&n&&m(We,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:l(()=>{n(u)},"onPress")}),r&&m(We,{label:"Generate code",onPress:l(()=>{r?.(u)},"onPress")})]})},u.id))})}l(Ve,"WorkspaceElementsTreeItem");function El({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=de(),[i,o]=q(""),a=e,c=l(h=>{o(h),setTimeout(()=>o(""),2e3)},"setFlash"),u=l(async(h,g)=>{try{await t({[h]:g}),c("\u2705 Configuration updated!")}catch{c("\u274C Error updating configuration")}},"updateField"),f=l(async()=>{try{if(e){const h=_e.saveToFile(e);c(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(N.Action);await Wn({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:g.filter(w=>!a?.excludedActionKeys?.includes(w.key)).map(w=>w.data)}}),c("\u2705 Code generated successfully!")}}catch{c("\u274C Error saving configuration")}},"handleSaveConfig"),d=l(async()=>{try{const h=_e.loadConfig();h?(await t(h),c("\u2705 Configuration reloaded successfully!")):c("\u274C No configuration found to reload")}catch{c("\u274C Error reloading configuration")}},"handleReloadConfig");return T(S,{flexDirection:"column",gap:1,children:[m(C,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(S,{paddingX:2,children:T(ce,{showHelp:!0,children:[T(ce.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[T(ce.Item,{label:"Project",children:[m(ce.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:l(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(kl,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:l(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ce.TextField,{label:"API URI",value:a?.apiUri??"",onChange:l(h=>u("apiUri",h),"onChange")}),m(ce.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:l(h=>u("testCustomerId",h),"onChange")})]}),T(ce.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[T(ce.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:l(({value:h})=>m(C,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(We,{label:"Update to TypeScript",onPress:l(()=>u("projectType","typescript"),"onPress")}),m(We,{label:"Update to OpenAPI",onPress:l(()=>u("projectType","openapi"),"onPress")})]}),m(ce.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:l(h=>u("outputDir",h),"onChange")})]}),T(ce.Item,{label:"Workspace Elements",children:[m(Ve,{label:"Actions",elementType:N.Action,isActionExcluded:l(h=>a?.excludedActionKeys?.includes(h.key)??!1,"isActionExcluded"),toggleAction:l(h=>u("excludedActionKeys",[...a?.excludedActionKeys??[],h.key]),"toggleAction"),generateCode:l(h=>{(async()=>{try{await Wn({out:a?.outputDir??"",target:a?.projectType??"typescript",schemasOnly:!1,membraneInterfaces:{actions:[h]}}),c("\u2705 Code generated successfully!")}catch{c("\u274C Error generating code")}})()},"generateCode")}),m(Ve,{label:"Flows",elementType:N.Flow}),m(Ve,{label:"Data Sources",elementType:N.DataSource}),m(Ve,{label:"Field Mappings",elementType:N.FieldMapping}),m(Ve,{label:"Packages",elementType:N.Package}),m(Ve,{label:"App Data Schemas",elementType:N.AppDataSchema}),m(Ve,{label:"App Event Types",elementType:N.AppEventType})]})]}),m(We,{label:"Save Configuration",onPress:f,hotkey:"s"}),m(We,{label:"Reload Configuration",onPress:d,hotkey:"r"}),m(We,{label:"Exit",onPress:l(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(S,{paddingX:2,children:m(C,{color:i.includes("\u2705")?"green":"red",children:i})})]})}l(El,"ConfigManager");const to=Mn(process.cwd());function Tl({cwd:s,children:e}){return m(to.Provider,{value:s,children:e})}l(Tl,"CwdProvider");function Il(){return jn(to)}l(Il,"useCwd");function Ds({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Tl,{cwd:n,children:m(Yo,{value:{fetcher:ba()},children:m(wl,{membraneCLIService:t,children:e})})})}l(Ds,"Layout");function Ol(s,e){s.command("config").alias("install").description("\u26A0\uFE0F EXPERIMENTAL: Manage local membrane configuration with interactive UI").addHelpText("after",["","Examples:"," membrane config # Open interactive config manager",""].join(`
145
+ `)).action(()=>{Fn(De.createElement(Ds,{membraneCLIService:e,children:De.createElement(El,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(Ol,"setupConfigCommand");function Al({currentPat:s,onSubmit:e}){const[t,n]=q(""),[r,i]=q(!1),[o,a]=q(null);return T(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(C,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(or,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:l(async u=>{a(null),i(!0);try{await e(u),n("")}catch{a("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&m(S,{marginTop:1,children:T(C,{children:[m(_t,{type:"dots"})," Validating token..."]})}),o&&m(C,{color:"red",children:o})]})}l(Al,"PersonalAccessTokenInput");function no({onExit:s,showEscOption:e=!0}){const[t,n]=q(""),{data:r,error:i,isLoading:o}=tr("/account"),{updateConfig:a}=de(),c=r?.workspaces,u=o;if(Me((p,y)=>{y.escape&&s?.()}),u)return T(S,{children:[m(_t,{}),m(C,{children:" Fetching workspaces..."})]});if(i)return T(S,{flexDirection:"column",children:[T(C,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]});const f=c?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(p=>({label:p.name,value:p.id})),h=d.length,g=c?.length??0;async function w(p){const y=f.find(A=>A.id===p);if(!y)return;const{key:k,secret:E}=y;!k||!E||(await a({workspaceKey:k,workspaceSecret:E}),s?.())}return l(w,"handleSelect"),T(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),T(S,{marginTop:1,children:[m(C,{children:"Search: "}),m(Zo,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&T(C,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(Qo,{options:d,onChange:l(p=>{p&&w(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(C,{color:"grey",children:"Press ESC to go back"})})]})}l(no,"SelectWorkspace");var Lt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Lt||{});const $l={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Ms=[Lt.Authenticate,Lt.ConnectWorkspace];function so({onComplete:s}){const{config:e}=de(),[t,n]=q(!1),[r,i]=q(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=fr(),c=Ms[r],u=r+1,f=Ms.length,d=Ms.map((w,p)=>{let y="pending";return p<r?y="done":p===r&&(y="current"),{id:w,label:$l[w],status:y}});async function h(w){const p=a&&w===""?a:w,y=new dr;try{await y.request("/account",{headers:{Authorization:`Bearer ${p}`}}),wa(p),i(k=>k+1)}catch(k){console.error(k)}}l(h,"handlePatSubmit");function g(){n(!0),s&&s()}return l(g,"handleWorkspaceSelected"),Me((w,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(C,{children:"\u2705 Setup complete. You are ready to go!"})}):T(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:T(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",T(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&m(C,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:d.map(w=>m(Nl,{status:w.status,label:w.label},w.id))})]}),c===Lt.Authenticate&&m(Al,{currentPat:a,onSubmit:h}),c===Lt.ConnectWorkspace&&m(no,{onExit:g,showEscOption:!1})]})}l(so,"Setup");function Nl({status:s,label:e}){return T(S,{children:[T(S,{width:2,children:[s==="current"&&m(_t,{type:"dots"}),s==="done"&&m(C,{children:"\u2705"})]}),m(C,{dimColor:s!=="current",children:e})]})}l(Nl,"StepDisplay");function xl(s,e){s.command("init").description("Run interactive setup for Membrane project").option("--key <key>","Workspace key for non-interactive setup").option("--secret <secret>","Workspace secret for non-interactive setup").addHelpText("after",["","Examples:"," membrane init # Run interactive setup"," membrane init --key KEY --secret SEC # Non-interactive setup with key and secret",""].join(`
146
+ `)).action(t=>{t.key&&t.secret?_e.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):Fn(De.createElement(Ds,{membraneCLIService:e,children:De.createElement(so,{onComplete:l(()=>process.exit(0),"onComplete")})}))})}l(xl,"setupInitCommand");const Pl=86400;async function Ll(s,e,t,n){const r={iss:s,isAdmin:!0};return t&&(r.id=t),Kn.sign(r,e,{expiresIn:Pl})}l(Ll,"generateMcpAccessToken");async function Rl(s,e){return(await Ct.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(Rl,"fetchOpenApiSchema");function Pe(s,e=!0,t,n=new Set){if(!s)return e?B.string():B.string().optional();if(Object.keys(s).length===0)return e?B.any():B.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return B.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Pe(o,e,t,n)}return B.any()}let r;if(s.type==="object"||s.properties){const i={};if(s.properties)for(const[o,a]of Object.entries(s.properties)){const c=s.required?.includes(o)??!1;i[o]=Pe(a,c,t,n)}if(Object.keys(i).length>0){if(r=B.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Pe(s.additionalProperties,!1,t,n);r=r.catchall(o)}else s.additionalProperties===!0&&(r=r.passthrough())}else if(s.additionalProperties&&typeof s.additionalProperties=="object"){const o=Pe(s.additionalProperties,!1,t,n);r=B.record(B.string(),o)}else r=B.record(B.string(),B.any())}else if(s.type==="array"){const i=s.items?Pe(s.items,!0,t,n):B.any();r=B.array(i)}else if(s.anyOf)r=B.any();else{switch(s.type){case"integer":r=B.coerce.number().int();break;case"number":r=B.coerce.number();break;case"boolean":r=B.coerce.boolean();break;case"string":default:r=B.string();break}s.format==="uuid"?r=B.string().uuid():s.format==="email"?r=B.string().email():s.format==="date"?r=B.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=B.string().datetime()),s.enum&&(r=B.enum(s.enum)),(s.type==="integer"||s.type==="number")&&(s.minimum!==void 0&&(r=r.min(s.minimum)),s.maximum!==void 0&&(r=r.max(s.maximum))),s.type==="string"&&(s.minLength!==void 0&&(r=r.min(s.minLength)),s.maxLength!==void 0&&(r=r.max(s.maxLength)))}return e?r:r.optional()}l(Pe,"convertOpenApiSchemaToZod");function ro(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(ro,"extractPathParameters");function Dl(s,e,t,n,r,i){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]=Pe(h.schema,!0,r).describe(h.description||`Path parameter: ${h.name}`);else if(h.in==="query"){const g=h.required===!0;f[h.name]=Pe(h.schema,g,r).describe(h.description||`Query parameter: ${h.name}`)}}if(Object.keys(u).length>0&&(c.params=B.object(u).describe("Path parameters")),Object.keys(f).length>0&&(c.query=B.object(f).describe("Query parameters")),s.requestBody&&s.requestBody.content){const h=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const g=s.requestBody.content["application/json"].schema;g?c.body=Pe(g,h,r).describe("Request body (JSON)"):c.body=B.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?c.body=h?B.string().describe("Request body (binary/text)"):B.string().optional().describe("Request body (binary/text)"):c.body=B.any().describe("Request body")}const d=Object.keys(c).length>0?B.object(c):B.object({});return{name:o,description:a,parameters:d,async execute(h){try{const g=ro(e);if(g.length>0){if(!h.params)throw new Error(`Missing required path parameters: ${g.join(", ")}`);const A=g.filter(I=>!(I in h.params));if(A.length>0)throw new Error(`Missing required path parameters: ${A.join(", ")}`)}let w=`${n}${e}`;if(h.params)for(const[A,I]of Object.entries(h.params)){const P=`{${A}}`;w.includes(P)&&(w=w.replace(P,String(I)))}const p=ro(w);if(p.length>0)throw new Error(`Unresolved path parameters: ${p.join(", ")}`);const y=new URLSearchParams;if(h.query)for(const[A,I]of Object.entries(h.query))I!=null&&y.append(A,String(I));y.toString()&&(w+=`?${y.toString()}`);const k={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`}};h.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(k.headers["Content-Type"]="application/json",k.data=h.body):s.requestBody?.content?.["application/octet-stream"]?(k.headers["Content-Type"]="application/octet-stream",k.data=h.body):s.requestBody?.content?.["text/plain"]?(k.headers["Content-Type"]="text/plain",k.data=h.body):(k.headers["Content-Type"]="application/json",k.data=h.body));const E=await Ct.request({url:w,...k});return{content:[{type:"text",text:E.data===""?"":JSON.stringify(E.data,null,2)}]}}catch(g){return Ct.isAxiosError(g)?{content:[{type:"text",text:`Error: ${g.response?.data?`HTTP ${g.response.status}: ${g.response.statusText} - ${JSON.stringify(g.response.data)}`:`HTTP ${g.response?.status||"unknown"}: ${g.message}`}`}],isError:!0}:g instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${g.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(Dl,"createApiTool");function Ml(s,e,t){const n=[];if(!s.paths)return n;const r=s.components||{};for(const[i,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=Dl(c,i,a,e,r,t);n.push(u)}}return n}l(Ml,"convertOpenApiToTools");function jl(s){s.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from environment variables or membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from env vars or membrane.config.yml",""].join(`
147
+ `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Kt(),t=process.env.MEMBRANE_ACCESS_TOKEN||e?.accessToken,n=process.env.MEMBRANE_WORKSPACE_KEY||e?.workspaceKey,r=process.env.MEMBRANE_WORKSPACE_SECRET||e?.workspaceSecret,i=process.env.MEMBRANE_TEST_CUSTOMER_ID||e?.testCustomerId,o=process.env.MEMBRANE_API_URI||e?.apiUri||Gn;!t&&(!n||!r)&&(e||(console.error("No configuration found. Please set MEMBRANE_ACCESS_TOKEN, or MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first to create a configuration file."),process.exit(1)),console.error("Missing credentials. Please provide MEMBRANE_ACCESS_TOKEN or workspace key/secret in the configuration file, command line, or environment variables."),process.exit(1));const a=t||await Ll(n,r,i),c=await Rl(o,a),u=Ml(c,o,a),f=new ea({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
148
148
  Use it for anything related to Membrane or integrations.
149
- `,version:"1.0.0"});for(const u of i){const f=u.execute;u.execute=async d=>(yl(process.pid,process.cwd()),f(d)),o.addTool(u)}xs({isRunning:!0,startTime:new Date().toISOString(),toolsCount:i.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{xs({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),Pt(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await l(),process.exit(0)}),process.on("SIGTERM",async()=>{await l(),process.exit(0)}),process.on("exit",()=>{Pt(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await l(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await l(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}c(Ml,"setupMcpCommand");const jl={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},_l={info:v.white,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class j{static{c(this,"Logger")}static formatMessage(e,t,n={icon:!1}){const r=n.timestamp?`${v.gray(new Date().toISOString())} `:"",i=n.prefix?`${v.gray(n.prefix)} `:"",o=n.suffix?` ${v.gray(n.suffix)}`:"",a=jl[t],l=_l[t];return`${r}${n.icon?a:""} ${i}${l(e)}${o}`}static info(e,t){let n=v.white;if(t?.color&&(n=v[t.color.toLowerCase()]||v.white),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${v.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(v.gray(`[${t.prefix}] ${e}`),t.error?`
149
+ `,version:"1.0.0"});for(const g of u){const w=g.execute;g.execute=async p=>(gl(process.pid,process.cwd()),w(p)),f.addTool(g)}xs({isRunning:!0,startTime:new Date().toISOString(),toolsCount:u.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const d=setInterval(()=>{xs({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),h=l(async()=>{clearInterval(d),Pt(process.pid,process.cwd());try{await f.stop()}catch{}},"cleanup");await f.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await h(),process.exit(0)}),process.on("SIGTERM",async()=>{await h(),process.exit(0)}),process.on("exit",()=>{Pt(process.pid,process.cwd())}),process.on("uncaughtException",async g=>{console.error("Uncaught exception:",g.message),await h(),process.exit(1)}),process.on("unhandledRejection",async g=>{console.error("Unhandled rejection:",g),await h(),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(jl,"setupMcpCommand");const _l={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Fl={info:v.white,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class j{static{l(this,"Logger")}static formatMessage(e,t,n={icon:!1}){const r=n.timestamp?`${v.gray(new Date().toISOString())} `:"",i=n.prefix?`${v.gray(n.prefix)} `:"",o=n.suffix?` ${v.gray(n.suffix)}`:"",a=_l[t],c=Fl[t];return`${r}${n.icon?a:""} ${i}${c(e)}${o}`}static info(e,t){let n=v.white;if(t?.color&&(n=v[t.color.toLowerCase()]||v.white),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${v.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(v.gray(`[${t.prefix}] ${e}`),t.error?`
150
150
  ${v.red(t.error)}`:""):console.debug(v.gray(e),t?.error?`
151
- ${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]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function Fl(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
152
- `)).action(async()=>{try{j.header("Opening Workspace in Browser"),j.info("Loading configuration...");const e=Kt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");j.info("Retrieving workspace ID...");const t=await gr(process.cwd()),n=`${e.consoleUri||ya}/w/${t}`;j.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),j.success("Browser opened successfully")}catch(e){e instanceof Error&&(j.error(e.message),process.exit(1)),j.error("An unknown error occurred"),process.exit(1)}})}c(Fl,"setupOpenCommand");async function js(s,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;b.debug(`[background-job] Started job ${n}`);const o=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:l=3e5,maxRetries:u=3}=t;let f=0;for(;;){if(Date.now()-o>l)throw new Error(`Background job ${n} timed out after ${l}ms`);await new Promise(g=>setTimeout(g,a));let h;try{h=await s.get(`background-jobs/${i}`),f=0}catch(g){if(g instanceof Po&&f<u){f++,b.debug(`[background-job] Job ${n} not found, retrying (${f}/${u})`);continue}throw g}if(h.status==="completed"){if(b.debug(`[background-job] Completed job ${n}`),!h.result)throw new Error(`Background job ${n} completed but returned no result`);return h.result}if(h.status==="failed"){const g=h.failedReason||"Unknown error";throw b.error(`[background-job] Failed job ${n}: ${g}`),h.stacktrace&&b.error(`Stacktrace: ${h.stacktrace.join(`
153
- `)}`),new Error(`Background job ${n} failed: ${g}`)}b.debug(`[background-job] Polling job ${n} (status: ${h.status})`)}}c(js,"pollBackgroundJob");function Kl(s,e){_s(x.dirname(s)),O.writeFileSync(s,e)}c(Kl,"writeFile");function ql(s){O.existsSync(s)&&O.rmSync(s)}c(ql,"deleteFile");function oo(s){O.existsSync(s)&&O.rmSync(s,{recursive:!0,force:!0})}c(oo,"deleteDir");function Bl(s,e=!0){if(O.existsSync(s))try{const t=O.readFileSync(s,"utf8");return le.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=x.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Bl,"readYaml");function ao(s,e,t){try{_s(x.dirname(s));const n=le.dump(e,t);O.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=x.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}c(ao,"writeYaml");function _s(s){O.existsSync(s)||O.mkdirSync(s,{recursive:!0})}c(_s,"ensureDirExists");function co(s,e=!0){if(!O.existsSync(s)||!O.statSync(s).isDirectory())return;let t=O.readdirSync(s);t.length>0&&(t.forEach(n=>co(x.join(s,n),!1)),t=O.readdirSync(s)),t.length===0&&!e&&O.rmdirSync(s)}c(co,"cleanupEmptyFolders");function Ul(s){const e=s.split(/[\\/]/).join("/");return e.endsWith("/")?e+"**":e}c(Ul,"normalizePattern");async function lo(s,e=[]){return new Promise(async(t,n)=>{const r=e.map(Ul),i=sr("zip",{zlib:{level:9}}),o=[];i.on("data",l=>o.push(l)),i.on("end",()=>t(Buffer.concat(o))),i.on("error",l=>n(l));const a=new Map;for(const l of s[N.Integration]||[])a.set(l.uuid,l.key);for(const[l,u]of Object.entries(s))for(const f of u){const d=f.key,h=a.get(f.integrationUuid),g=Lo(l,d,h);if(r.length>0&&!r.some(p=>na(g,p)))continue;const y=le.dump(f);i.append(y,{name:g})}i.finalize()})}c(lo,"createMembraneZip");async function Fs(s,e){const t=await cr.loadAsync(s),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const o=De(r);if(!o)continue;const a=await i.async("string"),l=le.load(a);if(!l)continue;const u=await e(r,l,o);u!==void 0&&n.push(u)}return n}c(Fs,"iterateZipItems");async function Jl(s){const e=await cr.loadAsync(s),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=De(n);if(!i)continue;const o=await r.async("string"),a=le.load(o);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}c(Jl,"readMembraneZip");async function uo(s=process.cwd()){const e=await fo(ie(s)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}c(uo,"readMembraneDir");async function fo(s){const e=ho(s),t=[];for(const n of e){if(n.isDirectory())continue;const r=De(n.path);if(!r)continue;const i=await n.readContent(),o=le.load(i),a=x.join(s,n.path);t.push({filePath:a,data:o,type:r.type})}return t}c(fo,"iterateMembraneFiles");function ho(s,e){const t=[];if(e||(e=s),!O.existsSync(e)||e.startsWith(x.join(s,"connectors")))return t;const n=O.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=x.join(e,r.name),o=x.relative(s,i);r.isDirectory()?t.push(...ho(s,i)):r.isFile()&&De(o)&&t.push({path:o,isDirectory:c(()=>!1,"isDirectory"),readContent:c(async()=>O.readFileSync(i,"utf8"),"readContent")})}return t}c(ho,"getMembraneFiles");function po(){const s={},e=x.join(ie(process.cwd()),"connectors");if(!O.existsSync(e))return s;const t=O.readdirSync(e);for(const n of t){const r=x.join(e,n);if(!O.statSync(r).isDirectory())continue;const i=x.join(r,`${n}.yml`),o=Bl(i,!1);if(!o?.uuid)continue;const a=new Set,l=O.readdirSync(r);for(const u of l){if(u.endsWith(".yml"))continue;const f=x.join(r,u);O.statSync(f).isDirectory()&&a.add(u=="development"?"":u)}s[o.uuid]={key:n,id:o.id,versions:Array.from(a)}}return s}c(po,"readConnectorsDir");function En(s,e){const t=x.join(ie(process.cwd()),"connectors",s);return e==""||e===Zs?x.join(t,"development"):e?x.join(t,e):t}c(En,"getConnectorPath");const mo=300,go=6e4;async function Wl(){const s=await R.withClient(async t=>js(t,()=>t.get("export"),{pollIntervalMs:mo,timeoutMs:go}));if(!s)throw new Error("Failed to export workspace");const e=await Ct.get(s.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}c(Wl,"downloadWorkspaceExport");async function yo(s,e={}){const t=new rr;t.append("file",s,{filename:"membrane.zip",contentType:"application/zip"});const n=await R.withClient(async i=>{const o=`import?dryRun=${e.dryRun??!1}&partial=${e.partial??!1}`,{jobId:a,accessKey:l}=await i.post(o,t,{headers:t.getHeaders()});return js(i,()=>Promise.resolve({jobId:a,accessKey:l}),{pollIntervalMs:1e3,timeoutMs:3e5})});if(!n)throw new Error("Failed to import workspace");const r={};for(const[i,o]of Object.entries(n))r[i]=new Set(o||[]);return r}c(yo,"importWorkspace");async function Vl(s,e){const t=await R.withClient(async r=>js(r,()=>r.get(`connectors/${s}/export`,{version:e}),{pollIntervalMs:mo,timeoutMs:go}));if(!t)throw new Error("Failed to export connector version");const n=await Ct.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}c(Vl,"exportConnector");const Ks=5;function Gl(s){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
154
- `)).action(async e=>{const t=ar({text:"Pulling workspace",color:"white"}).start();try{const n=await zl(e,t);t.stop(),Zl(n.workspaceExport,n.connectors)}catch(n){t.stop(),Xl(n),process.exit(1)}})}c(Gl,"setupPullCommand");async function zl(s,e){const t=await uo(),n=await lo(t),r=await Wl(),i=await Jl(r),{comparison:o}=Do(t,i);o[we.DELETE].size>0&&!s.force&&(await Ql(o,n),j.error("Use --force to delete local elements"),process.exit(1));const l=await fo(ie(process.cwd()));for(const{filePath:f,data:d}of l)o[we.DELETE].has(d.uuid)&&ql(f);return co(ie(process.cwd())),await Fs(r,(f,d)=>{if(De(f)&&(o[we.CREATE].has(d.uuid)||o[we.UPDATE].has(d.uuid))){const g=_.join(ie(process.cwd()),f);ao(g,d)}}),{connectors:await Hl(i[N.Integration],e),workspaceExport:i}}c(zl,"pullWorkspace");async function Hl(s,e){e.text="Pulling connectors";const t=new Map,{id:n}=await R.withClient(l=>l.get("org-workspace-id")),{items:r=[]}=await R.withClient(l=>l.get(`/connectors?workspaceId=${n}`));for(const l of r){const u=l.uuid??l.id;!l.isPublic&&u&&t.set(u,new Set([""]))}for(const l of s??[]){const{connectorUuid:u,connectorVersion:f}=l;u&&(t.has(u)||t.set(u,new Set),t.get(u).add(f??""))}const i=po();for(const[l,{key:u,versions:f}]of Object.entries(i)){if(!t.has(l)){const h=En(u);oo(h);continue}const d=t.get(l);for(const h of f)if(!d.has(h)){const g=En(u,h);oo(g)}}const o=Array.from(t.entries()),a=o.length;for(let l=0;l<a;l+=Ks){const u=o.slice(l,l+Ks),f=Math.min(l+Ks,a);e.text=`Pulling connectors \xB7 ${f} out of ${a}`,await Promise.all(u.map(([d,h])=>Yl(d,Array.from(h))))}return Array.from(t.keys())}c(Hl,"pullConnectors");async function Yl(s,e){const t=await R.withClient(i=>i.get(`connectors/${s}`),!1);if(!t||!t.key)return;const n=En(t.key),r=_.join(n,`${t.key}.yml`);ao(r,t);for(const i of e){const o=await Vl(s,i),a=En(t.key,i);if(Kl(_.join(a,"src.zip"),o),!i||i===Zs){const l=_.join(a,"src");_s(l),await(await ir.Open.buffer(o)).extract({path:l})}}}c(Yl,"pullConnector");function Zl(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;j.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(s).sort()){const r=s[n];j.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&j.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(Zl,"showStats$1");async function Ql(s,e){const t=s[we.DELETE].size;j.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await Fs(e,(n,r)=>{De(n)&&s[we.DELETE].has(r.uuid)&&j.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}c(Ql,"showConflicts$1");async function Xl(s){j.error("\u25A0 Error"),j.error(`\u2514\u2500\u2500 ${s.message}`),j.error(` ${s.stack}`)}c(Xl,"showError$1");const Q=[];for(let s=0;s<256;++s)Q.push((s+256).toString(16).slice(1));function eu(s,e=0){return(Q[s[e+0]]+Q[s[e+1]]+Q[s[e+2]]+Q[s[e+3]]+"-"+Q[s[e+4]]+Q[s[e+5]]+"-"+Q[s[e+6]]+Q[s[e+7]]+"-"+Q[s[e+8]]+Q[s[e+9]]+"-"+Q[s[e+10]]+Q[s[e+11]]+Q[s[e+12]]+Q[s[e+13]]+Q[s[e+14]]+Q[s[e+15]]).toLowerCase()}c(eu,"unsafeStringify");let qs;const tu=new Uint8Array(16);function nu(){if(!qs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");qs=crypto.getRandomValues.bind(crypto)}return qs(tu)}c(nu,"rng");const su=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var wo={randomUUID:su};function ru(s,e,t){if(wo.randomUUID&&!s)return wo.randomUUID();s=s||{};const n=s.random??s.rng?.()??nu();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,eu(n)}c(ru,"v4");function iu(s){s.command("push").description("Push workspace data to specified workspace").argument("[files...]","Files, directories, or glob patterns to push").option("--force","Overwrite conflicts with local data",!1).addHelpText("after",["","Examples:"," membrane push # Push all workspace elements"," membrane push data-sources/ # Push all data-sources"," membrane push actions/my-action/spec.yaml # Push specific action"," membrane push flows/*-test/spec.yaml # Push flows matching pattern"," membrane push --force # Overwrite conflicts with local data",""].join(`
155
- `)).action(async(e,t)=>{const n=ar({text:"Pushing workspace",color:"white"}).start();try{await ou(e,t,n)}catch(r){n.stop(),du(r),process.exit(1)}})}c(iu,"setupPushCommand");async function ou(s,e,t){const n=s.length>0,r=await uo(),i=po(),o=au(r,i),a=await lo(o,n?s:void 0);t.text="Comparing workspace";const l=await yo(a,{dryRun:!0,partial:n});l[we.DELETE].size>0&&!e.force&&(t.stop(),await fu(l,a),j.error("Use --force to delete remote elements"),process.exit(1)),t.text="Pushing connectors";const{pushedConnectors:f=[]}=await Vi();t.text="Pushing workspace",await yo(a,{partial:n}),t.stop(),uu(o,f),process.exit(0)}c(ou,"pushWorkspace");function au(s,e){const t=cu(s),n=lu(t,e),r={};for(const[i,o]of Object.entries(t)){const a=i,l=ye[a]?.parentFieldKey||"parentId";r[a]=(o||[]).map(u=>{const f={...u};if(f.integrationId&&!f.integrationUuid&&(f.integrationUuid=n.get(f.integrationId.toString())||f.integrationId,delete f.integrationId),f.connectorId){if(!f.connectorUuid){const d=n.get(f.connectorId.toString());d&&(f.connectorUuid=d)}delete f.connectorId}if(f[l]){const d=f[l].toString();f.parentUuid=n.get(d)||d}return a===N.Package&&f.elements&&(f.elements=f.elements.map(d=>{if(d.id&&!d.uuid){const h=n.get(d.id.toString());if(h)return{uuid:h,type:d.type}}return d})),delete f.id,f})}return r}c(au,"resolveLegacyIdReferences");function cu(s){const e={};for(const[t,n]of Object.entries(s))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:ru()});return e}c(cu,"generateMissingUuids");function lu(s,e){const t=new Map;for(const n of Object.values(s))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}c(lu,"buildIdToUuidLookup");function uu(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;j.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(s).sort()){const r=s[n];j.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&j.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}c(uu,"showStats");async function fu(s,e){const t=s[we.DELETE].size;j.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Fs(e,(n,r)=>{De(n)&&s[we.DELETE].has(r.uuid)&&j.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}c(fu,"showConflicts");async function du(s){j.error("\u25A0 Error"),j.error(`\u2514\u2500\u2500 ${s.message}`),j.error(` ${s.stack}`)}c(du,"showError");const Bs=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:c(()=>{const s=x.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(O.existsSync(s))try{t=JSON.parse(O.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return O.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=x.join(process.cwd(),".cursor"),e=x.join(s,"mcp.json");O.existsSync(s)||O.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(O.existsSync(e))try{n=JSON.parse(O.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return O.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function hu({onExit:s,onComplete:e}){const[t,n]=U(0),[r,i]=U(!1),[o,a]=U(null),[l,u]=U(""),[f,d]=U("");Me((y,p)=>{if(l||f){(p.escape||y==="q"||p.return)&&e();return}if(r)p.return||y===" "?h(o):p.escape&&(i(!1),a(null));else if(p.escape)s();else if(p.upArrow||y==="k")n(Math.max(0,t-1));else if(p.downArrow||y==="j")n(Math.min(Bs.length-1,t+1));else if(p.return||y===" "){const w=Bs[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){d(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"green",children:"Success"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"green",children:l}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(C,{color:"red",children:f})}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Confirmation"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[E(C,{children:["Connect ",m(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(C,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:E(C,{children:[m(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:E(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Select Agent"})]})}),E(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:Bs.map((y,p)=>E(S,{children:[E(C,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),E(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(hu,"AddMcpServerScreen");function pu(){const[s,e]=U(null),[t,n]=U([]),[r,i]=U(null);return ze(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Ne.on(H.McpStatusChanged,o),Ne.on(H.McpServersChanged,a),()=>{Ne.off(H.McpStatusChanged,o),Ne.off(H.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}c(pu,"useMcpStatus");function mu(){const{error:s,serverCount:e,allMcpServers:t}=pu(),n=Math.min(100,process.stdout.columns||100);return E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:E(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(C,{color:"red",children:"error reading status"}):e===0?m(C,{color:"yellow",children:"none"}):m(C,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:E(C,{color:"grey",children:["Connect your AI agents to Membrane.",m(qo,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:E(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(mu,"Agent");const bo=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function So(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(So,"truncateText");function gu({children:s}){const{state:e,logs:t}=de();return!e||e===M.NOT_INITIALIZED?E(S,{gap:1,flexDirection:"row",children:[m(ea,{type:"dots"}),m(C,{children:"Initializing..."})]}):e===M.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===M.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(C,{color:bo(n.type),children:n.message},n.timestamp+r))}):s}c(gu,"EnsureInitialized");function yu(){const{stats:s}=de(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:E(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(C,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>E(S,{children:[m(S,{width:20,children:E(C,{children:[t,":"]})}),m(C,{color:"green",children:n})]},t))})]})}c(yu,"ElementStats");const Us=5,wu=6;function bu(){const{logs:s}=de(),[e,t]=U(0),n=Math.min(100,process.stdout.columns||100),r=Us,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-wu,u=e<s.length-r,f=e>0;return Me((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(y=>Math.min(g,y+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),E(S,{flexDirection:"column",paddingTop:1,children:[E(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Us&&m(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(S,{marginLeft:1,children:m(C,{color:bo(d.type),children:So(d.message,l)})},d.timestamp+h)),s.length>Us&&E(S,{marginLeft:1,flexDirection:"row",children:[u&&m(C,{color:"grey",children:"\u2191 "}),f&&m(C,{color:"grey",children:"\u2193 "})]})]})}c(bu,"Logs");const In=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Su(){const{state:s,resolveConflicts:e,exit:t}=de(),[n,r]=U(0),[i,o]=U(!1),[a,l]=U(!1);return Me((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:In.length-1):f.downArrow?r(d=>d<In.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),In[n].value==="sync"?e({watch:!0}):t())}}),ze(()=>{s!==M.CONFLICTS&&i&&o(!1)},[s,i]),E(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(vu,{isExpanded:a})}),E(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(C,{color:"white",bold:!0,children:"What would you like to do?"}),m(C,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?E(S,{flexDirection:"row",gap:1,children:[m(_t,{type:"dots"}),m(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:In.map((u,f)=>m(S,{flexDirection:"column",children:E(S,{flexDirection:"row",gap:1,children:[m(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c(Su,"ResolveChangesUI");const Cu={[be.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[be.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[be.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function vu({isExpanded:s,showControls:e=!0}){const{conflicts:t}=de(),n=5,r=Ko(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=Cu[a][l];return E(S,{flexDirection:"column",children:[E(S,{flexDirection:"row",gap:1,children:[E(C,{color:"yellow",children:[u.label," (",o.length,")"]}),m(C,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>m(S,{marginLeft:2,children:E(C,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:E(C,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(vu,"Conflicts");function ku(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=de(),i=n?.name,o=i?So(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ze(()=>{r({watch:!0})},[]),E(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:E(S,{flexDirection:"row",gap:1,children:[m(C,{bold:!0,children:"\u{1F504} Workspace"}),E(C,{color:Eu(e),children:[" [",Tu(e),"] "]})]})}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Local:"})}),m(C,{color:"grey",children:process.cwd()})]}),E(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?E(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):E(C,{children:[m(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===M.CONFLICTS?m(Su,{}):E(jt,{children:[m(S,{paddingTop:1,children:m(yu,{})}),t.length>0&&m(bu,{})]})]})}c(ku,"Workspace");function Tu(s){switch(s){case M.PULLING:return"pulling";case M.PUSHING:return"pushing";case M.CONFLICTS:return"conflicts";case M.SYNCED:return"synced";case M.ERROR:return"error";case M.WATCHING:return"tracking changes";case M.RESOLVING:return"resolving";case M.NOT_SYNCED:return"not synced";case M.INITIALIZED:return"initialized";case M.SETTING_UP:return"setup required";default:return"unknown"}}c(Tu,"getStatusDisplay");function Eu(s){switch(s){case M.PULLING:return"yellow";case M.PUSHING:return"yellow";case M.CONFLICTS:return"red";case M.SYNCED:return"green";case M.ERROR:return"red";case M.WATCHING:return"green";case M.RESOLVING:return"yellow";case M.NOT_SYNCED:return"grey";case M.SETTING_UP:return"yellow";default:return"grey"}}c(Eu,"getStatusColor");const Iu="https://console.integration.app/w";function Ou(){const s=Ol(),e=_n(!0),{exit:t,state:n}=de(),[r,i]=U(null),o=r??(n===M.SETTING_UP?"setup":"main");Me(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===M.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await gr(s),u=`${Iu}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";sa(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),ze(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(no,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(hu,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(so,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(gu,{children:E(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(mu,{})}),m(ku,{}),m(S,{paddingLeft:2,children:m(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Ou,"Main");const Au=c(()=>[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 Real-time agent mode is experimental and subject to changes. \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(`
156
- `),"createExperimentalWarning$1");function $u(s,e){s.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
157
- `)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const n=t.rps;!isNaN(n)&&n>0&&n<=1e3?R.init({maxRequestsPerSecond:n}):(b.error(`Invalid RPS value: ${n}. Must be between 1 and 1000.`),process.exit(1))}console.warn(Au()),Fn(Re.createElement(Rs,{cwd:process.cwd(),membraneCLIService:e,children:Re.createElement(Ou)}))})}c($u,"setupSyncCommand");class Nu{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=zn(),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 xu="claude-sonnet-4-20250514";class zs{static{c(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:r,options:i,llm:o}){this.client=r,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=i}static async create({connectionId:e,testBasePath:t,options:n}){const r=Kt();if(!r)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!r.workspaceKey||!r.workspaceSecret)throw new Error("Missing workspace credentials");if(!r.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const i=new Ys({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new ra({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const f=await o.messages.create({model:xu,max_tokens:u,messages:[{role:"user",content:l}]});return f.content[0].type==="text"?f.content[0].text:""},"complete")};return new zs({client:i,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(),qn(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=_.join(this.testsDir,this.testBasePath,this.connectionId,e);return Zn(t)}async writeYaml(e,t){const n=_.join(this.testsDir,this.testBasePath,this.connectionId,e);F.mkdirSync(_.dirname(n),{recursive:!0}),F.writeFileSync(n,le.dump(t,{noRefs:!0}))}writeResults(e){const t=_.join(this.testsDir,this.testBasePath,this.connectionId);F.mkdirSync(t,{recursive:!0});const n=_.join(t,"test-results.yaml");F.writeFileSync(n,le.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},r={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Kn.sign(n,e.workspaceSecret,r)}}oa.interpolate=/{{([\s\S]+?)}}/g;function Js(s,e){if(typeof s=="string"){const t=ia(s),n={state:e,random:{number:c(()=>vt.number.int(),"number"),alphaNumeric:c(i=>vt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>vt.company.name(),"name"),catchPhrase:c(()=>vt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>vt.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},r=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${r}`)),r}return Array.isArray(s)?s.map(t=>Js(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Js(n,e)])):s}c(Js,"processNode");function Pu(s,e){return Js(s,e)}c(Pu,"handleTemplate");class Lu{static{c(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${v.bold.cyan("[start]")} ${v.yellow(e.path)}`);let t=!1,n=!1,r={},i={},o;for(;!t;)try{i=await e.readTestCase(),i||(i=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),i),console.debug(`${v.bold.yellow("[initialized]")} ${v.yellow(e.path)}`)),o=Pu(i,this.environment.state),await e.run(o),console.debug(`${v.bold.green("[success]")} ${v.yellow(e.path)}`),t=!0,r=e.getResult(),xn(this.result,e.path,r)}catch(l){if(console.error(`${v.bold.red("[error]")} ${v.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${v.bold.red("[fix fail]")} ${v.yellow(e.path)}: ${u}`)}}xn(this.result,e.path,{error:he(l)}),t=!0,r={error:he(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),qn(this.result,e.getResult())}}class Le{static{c(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0,this.resultsLocator=""}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 r=await e();r?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:r})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(r){this.assertions.push({message:t,result:!1,details:he(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Ws(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const r=s[n],i=e[n];if(r&&i&&typeof r=="object"&&typeof i=="object"){if(Array.isArray(r)&&Array.isArray(i)){const o=i.filter(a=>!r.some(l=>{if(typeof l=="object"&&typeof a=="object"&&l!==null&&a!==null&&!Array.isArray(l)&&!Array.isArray(a)){for(const u in a)if(!(u in l)||!Vs(l[u],a[u]))return!1;return!0}else return JSON.stringify(l)===JSON.stringify(a)}));o.length>0&&(t[n]=o)}else if(!Array.isArray(r)&&!Array.isArray(i)){const o=Ws(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}Vs(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(Ws,"getNotMatchingSubFields");function Vs(s,e){if(s==e||s?.toString?.()===e?.toString?.())return!0;const t=new Date(s),n=new Date(e);return!isNaN(t.getTime())&&!isNaN(n.getTime())?t.getTime()===n.getTime():!1}c(Vs,"softCompare");class Du extends Le{static{c(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const n=Pn(this.dataCollection);if(this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!i.record,"Record is returned from findById"),i.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:i.record.fields});const o=Qs(n),a=Rt(e.input.fields,o,{skipUnknownFields:!0}),l=Rt(i.record.fields,o),u=Ws(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=Ro(n??{});if(r.length>0){const i={};r.forEach(a=>{const l=Mo(e.input.fields,a);typeof l<"u"&&xn(i,a,l)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:i});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Pn(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=he(t),r=Pn(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to create a data record in a data collection with the following fields schema:
151
+ ${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]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function Kl(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
152
+ `)).action(async()=>{try{j.header("Opening Workspace in Browser"),j.info("Loading configuration...");const e=Kt();if(!e)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");j.info("Retrieving workspace ID...");const t=await gr(process.cwd()),n=`${e.consoleUri||ga}/w/${t}`;j.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),j.success("Browser opened successfully")}catch(e){e instanceof Error&&(j.error(e.message),process.exit(1)),j.error("An unknown error occurred"),process.exit(1)}})}l(Kl,"setupOpenCommand");async function js(s,e,t={}){const{jobId:n,accessKey:r}=await e(),i=`${n}:${r}`;b.debug(`[background-job] Started job ${n}`);const o=Date.now(),{pollIntervalMs:a=1e3,timeoutMs:c=3e5,maxRetries:u=3}=t;let f=0;for(;;){if(Date.now()-o>c)throw new Error(`Background job ${n} timed out after ${c}ms`);await new Promise(g=>setTimeout(g,a));let h;try{h=await s.get(`background-jobs/${i}`),f=0}catch(g){if(g instanceof xo&&f<u){f++,b.debug(`[background-job] Job ${n} not found, retrying (${f}/${u})`);continue}throw g}if(h.status==="completed"){if(b.debug(`[background-job] Completed job ${n}`),!h.result)throw new Error(`Background job ${n} completed but returned no result`);return h.result}if(h.status==="failed"){const g=h.failedReason||"Unknown error";throw b.error(`[background-job] Failed job ${n}: ${g}`),h.stacktrace&&b.error(`Stacktrace: ${h.stacktrace.join(`
153
+ `)}`),new Error(`Background job ${n} failed: ${g}`)}b.debug(`[background-job] Polling job ${n} (status: ${h.status})`)}}l(js,"pollBackgroundJob");function Bl(s,e){_s(x.dirname(s)),O.writeFileSync(s,e)}l(Bl,"writeFile");function ql(s){O.existsSync(s)&&O.rmSync(s)}l(ql,"deleteFile");function io(s){O.existsSync(s)&&O.rmSync(s,{recursive:!0,force:!0})}l(io,"deleteDir");function Ul(s,e=!0){if(O.existsSync(s))try{const t=O.readFileSync(s,"utf8");return le.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=x.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}l(Ul,"readYaml");function oo(s,e,t){try{_s(x.dirname(s));const n=le.dump(e,t);O.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=x.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}return e}l(oo,"writeYaml");function _s(s){O.existsSync(s)||O.mkdirSync(s,{recursive:!0})}l(_s,"ensureDirExists");function ao(s,e=!0){if(!O.existsSync(s)||!O.statSync(s).isDirectory())return;let t=O.readdirSync(s);t.length>0&&(t.forEach(n=>ao(x.join(s,n),!1)),t=O.readdirSync(s)),t.length===0&&!e&&O.rmdirSync(s)}l(ao,"cleanupEmptyFolders");function Jl(s){const e=s.split(/[\\/]/).join("/");return e.endsWith("/")?e+"**":e}l(Jl,"normalizePattern");async function co(s,e=[]){return new Promise(async(t,n)=>{const r=e.map(Jl),i=sr("zip",{zlib:{level:9}}),o=[];i.on("data",c=>o.push(c)),i.on("end",()=>t(Buffer.concat(o))),i.on("error",c=>n(c));const a=new Map;for(const c of s[N.Integration]||[])a.set(c.uuid,c.key);for(const[c,u]of Object.entries(s))for(const f of u){const d=f.key,h=a.get(f.integrationUuid),g=Po(c,d,h);if(r.length>0&&!r.some(p=>ta(g,p)))continue;const w=le.dump(f);i.append(w,{name:g})}i.finalize()})}l(co,"createMembraneZip");async function Fs(s,e){const t=await cr.loadAsync(s),n=[];for(const[r,i]of Object.entries(t.files)){if(i.dir)continue;const o=Re(r);if(!o)continue;const a=await i.async("string"),c=le.load(a);if(!c)continue;const u=await e(r,c,o);u!==void 0&&n.push(u)}return n}l(Fs,"iterateZipItems");async function Wl(s){const e=await cr.loadAsync(s),t={};for(const[n,r]of Object.entries(e.files)){if(r.dir)continue;const i=Re(n);if(!i)continue;const o=await r.async("string"),a=le.load(o);t[i.type]||(t[i.type]=[]),t[i.type].push(a)}return t}l(Wl,"readMembraneZip");async function lo(s=process.cwd()){const e=await uo(ie(s)),t={};for(const{data:n,type:r}of e)t[r]||(t[r]=[]),t[r].push(n);return t}l(lo,"readMembraneDir");async function uo(s){const e=fo(s),t=[];for(const n of e){if(n.isDirectory())continue;const r=Re(n.path);if(!r)continue;const i=await n.readContent(),o=le.load(i),a=x.join(s,n.path);t.push({filePath:a,data:o,type:r.type})}return t}l(uo,"iterateMembraneFiles");function fo(s,e){const t=[];if(e||(e=s),!O.existsSync(e)||e.startsWith(x.join(s,"connectors")))return t;const n=O.readdirSync(e,{withFileTypes:!0});for(const r of n){const i=x.join(e,r.name),o=x.relative(s,i);r.isDirectory()?t.push(...fo(s,i)):r.isFile()&&Re(o)&&t.push({path:o,isDirectory:l(()=>!1,"isDirectory"),readContent:l(async()=>O.readFileSync(i,"utf8"),"readContent")})}return t}l(fo,"getMembraneFiles");function ho(){const s={},e=x.join(ie(process.cwd()),"connectors");if(!O.existsSync(e))return s;const t=O.readdirSync(e);for(const n of t){const r=x.join(e,n);if(!O.statSync(r).isDirectory())continue;const i=x.join(r,`${n}.yml`),o=Ul(i,!1);if(!o?.uuid)continue;const a=new Set,c=O.readdirSync(r);for(const u of c){if(u.endsWith(".yml"))continue;const f=x.join(r,u);O.statSync(f).isDirectory()&&a.add(u=="development"?"":u)}s[o.uuid]={key:n,id:o.id,versions:Array.from(a)}}return s}l(ho,"readConnectorsDir");function Tn(s,e){const t=x.join(ie(process.cwd()),"connectors",s);return e==""||e===Zs?x.join(t,"development"):e?x.join(t,e):t}l(Tn,"getConnectorPath");const po=300,mo=6e4;async function Vl(){const s=await D.withClient(async t=>js(t,()=>t.get("export"),{pollIntervalMs:po,timeoutMs:mo}));if(!s)throw new Error("Failed to export workspace");const e=await Ct.get(s.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(e.data)}l(Vl,"downloadWorkspaceExport");async function go(s,e={}){const t=new rr;t.append("file",s,{filename:"membrane.zip",contentType:"application/zip"});const n=await D.withClient(async i=>{const o=`import?dryRun=${e.dryRun??!1}&partial=${e.partial??!1}`,{jobId:a,accessKey:c}=await i.post(o,t,{headers:t.getHeaders()});return js(i,()=>Promise.resolve({jobId:a,accessKey:c}),{pollIntervalMs:1e3,timeoutMs:3e5})});if(!n)throw new Error("Failed to import workspace");const r={};for(const[i,o]of Object.entries(n))r[i]=new Set(o||[]);return r}l(go,"importWorkspace");async function Gl(s,e){const t=await D.withClient(async r=>js(r,()=>r.get(`connectors/${s}/export-files`,{version:e}),{pollIntervalMs:po,timeoutMs:mo}));if(!t)throw new Error("Failed to export connector version");const n=await Ct.get(t.downloadUrl,{responseType:"arraybuffer"});return Buffer.from(n.data)}l(Gl,"exportConnector");const Ks=5;function zl(s){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data",""].join(`
154
+ `)).action(async e=>{const t=ar({text:"Pulling workspace",color:"white"}).start();try{const n=await Hl(e,t);t.stop(),Ql(n.workspaceExport,n.connectors)}catch(n){t.stop(),eu(n),process.exit(1)}})}l(zl,"setupPullCommand");async function Hl(s,e){const t=await lo(),n=await co(t),r=await Vl(),i=await Wl(r),{comparison:o}=Lo(t,i);o[we.DELETE].size>0&&!s.force&&(await Xl(o,n),j.error("Use --force to delete local elements"),process.exit(1));const c=await uo(ie(process.cwd()));for(const{filePath:f,data:d}of c)o[we.DELETE].has(d.uuid)&&ql(f);return ao(ie(process.cwd())),await Fs(r,(f,d)=>{if(Re(f)&&(o[we.CREATE].has(d.uuid)||o[we.UPDATE].has(d.uuid))){const g=_.join(ie(process.cwd()),f);oo(g,d)}}),{connectors:await Yl(i[N.Integration],e),workspaceExport:i}}l(Hl,"pullWorkspace");async function Yl(s,e){e.text="Pulling connectors";const t=new Map,{id:n}=await D.withClient(c=>c.get("org-workspace-id")),{items:r=[]}=await D.withClient(c=>c.get(`/connectors?workspaceId=${n}`));for(const c of r){const u=c.uuid??c.id;!c.isPublic&&u&&t.set(u,new Set([""]))}for(const c of s??[]){const{connectorUuid:u,connectorVersion:f}=c;u&&(t.has(u)||t.set(u,new Set),t.get(u).add(f??""))}const i=ho();for(const[c,{key:u,versions:f}]of Object.entries(i)){if(!t.has(c)){const h=Tn(u);io(h);continue}const d=t.get(c);for(const h of f)if(!d.has(h)){const g=Tn(u,h);io(g)}}const o=Array.from(t.entries()),a=o.length;for(let c=0;c<a;c+=Ks){const u=o.slice(c,c+Ks),f=Math.min(c+Ks,a);e.text=`Pulling connectors \xB7 ${f} out of ${a}`,await Promise.all(u.map(([d,h])=>Zl(d,Array.from(h))))}return Array.from(t.keys())}l(Yl,"pullConnectors");async function Zl(s,e){const t=await D.withClient(a=>a.get(`connectors/${s}/export-json`),!1),n=await D.withClient(a=>a.get(`connectors/${s}`),!1);if(!t||!n||!t.key||!n.key)return;const r={...t,id:n.id,uuid:n.uuid},i=Tn(t.key),o=_.join(i,`${t.key}.yml`);oo(o,r);for(const a of e){const c=await Gl(s,a),u=Tn(t.key,a);if(Bl(_.join(u,"src.zip"),c),!a||a===Zs){const f=_.join(u,"src");_s(f),await(await ir.Open.buffer(c)).extract({path:f})}}}l(Zl,"pullConnector");function Ql(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;j.info(`\u25CF Pulled workspace elements \xB7 ${t}`);for(const n of Object.keys(s).sort()){const r=s[n];j.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&j.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}l(Ql,"showStats$1");async function Xl(s,e){const t=s[we.DELETE].size;j.info(`\u2299 Pull: conflicts detected \xB7 ${t}`),await Fs(e,(n,r)=>{Re(n)&&s[we.DELETE].has(r.uuid)&&j.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted in remote)`)})}l(Xl,"showConflicts$1");async function eu(s){j.error("\u25A0 Error"),j.error(`\u2514\u2500\u2500 ${s.message}`),j.error(` ${s.stack}`)}l(eu,"showError$1");const Q=[];for(let s=0;s<256;++s)Q.push((s+256).toString(16).slice(1));function tu(s,e=0){return(Q[s[e+0]]+Q[s[e+1]]+Q[s[e+2]]+Q[s[e+3]]+"-"+Q[s[e+4]]+Q[s[e+5]]+"-"+Q[s[e+6]]+Q[s[e+7]]+"-"+Q[s[e+8]]+Q[s[e+9]]+"-"+Q[s[e+10]]+Q[s[e+11]]+Q[s[e+12]]+Q[s[e+13]]+Q[s[e+14]]+Q[s[e+15]]).toLowerCase()}l(tu,"unsafeStringify");let Bs;const nu=new Uint8Array(16);function su(){if(!Bs){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Bs=crypto.getRandomValues.bind(crypto)}return Bs(nu)}l(su,"rng");const ru=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);var yo={randomUUID:ru};function iu(s,e,t){if(yo.randomUUID&&!s)return yo.randomUUID();s=s||{};const n=s.random??s.rng?.()??su();if(n.length<16)throw new Error("Random bytes length must be >= 16");return n[6]=n[6]&15|64,n[8]=n[8]&63|128,tu(n)}l(iu,"v4");function ou(s){s.command("push").description("Push workspace data to specified workspace").argument("[files...]","Files, directories, or glob patterns to push").option("--force","Overwrite conflicts with local data",!1).addHelpText("after",["","Examples:"," membrane push # Push all workspace elements"," membrane push data-sources/ # Push all data-sources"," membrane push actions/my-action/spec.yaml # Push specific action"," membrane push flows/*-test/spec.yaml # Push flows matching pattern"," membrane push --force # Overwrite conflicts with local data",""].join(`
155
+ `)).action(async(e,t)=>{const n=ar({text:"Pushing workspace",color:"white"}).start();try{await au(e,t,n)}catch(r){n.stop(),hu(r),process.exit(1)}})}l(ou,"setupPushCommand");async function au(s,e,t){const n=s.length>0,r=await lo(),i=ho(),o=cu(r,i),a=await co(o,n?s:void 0);t.text="Comparing workspace";const c=await go(a,{dryRun:!0,partial:n});c[we.DELETE].size>0&&!e.force&&(t.stop(),await du(c,a),j.error("Use --force to delete remote elements"),process.exit(1)),t.text="Pushing connectors";const{pushedConnectors:f=[]}=await Vi();t.text="Pushing workspace",await go(a,{partial:n}),t.stop(),fu(o,f),process.exit(0)}l(au,"pushWorkspace");function cu(s,e){const t=lu(s),n=uu(t,e),r={};for(const[i,o]of Object.entries(t)){const a=i,c=ye[a]?.parentFieldKey||"parentId";r[a]=(o||[]).map(u=>{const f={...u};if(f.integrationId&&!f.integrationUuid&&(f.integrationUuid=n.get(f.integrationId.toString())||f.integrationId,delete f.integrationId),f.connectorId){if(!f.connectorUuid){const d=n.get(f.connectorId.toString());d&&(f.connectorUuid=d)}delete f.connectorId}if(f[c]){const d=f[c].toString();f.parentUuid=n.get(d)||d}return a===N.Package&&f.elements&&(f.elements=f.elements.map(d=>{if(d.id&&!d.uuid){const h=n.get(d.id.toString());if(h)return{uuid:h,type:d.type}}return d})),delete f.id,f})}return r}l(cu,"resolveLegacyIdReferences");function lu(s){const e={};for(const[t,n]of Object.entries(s))e[t]=(n||[]).map(r=>r.uuid?r:{...r,uuid:iu()});return e}l(lu,"generateMissingUuids");function uu(s,e){const t=new Map;for(const n of Object.values(s))for(const r of n||[])r.id&&r.uuid&&t.set(r.id.toString(),r.uuid);for(const[n,r]of Object.entries(e))r.id&&t.set(r.id.toString(),n);return t}l(uu,"buildIdToUuidLookup");function fu(s,e=[]){const t=Object.values(s).reduce((n,r)=>n+(r?.length??0),0)+e.length;j.info(`\u25CF Pushed workspace elements \xB7 ${t}`);for(const n of Object.keys(s).sort()){const r=s[n];j.info(`\u2514\u2500\u2500 ${n}s \xB7 ${r?.length??0}`)}e.length>0&&j.info(`\u2514\u2500\u2500 connectors \xB7 ${e.length}`)}l(fu,"showStats");async function du(s,e){const t=s[we.DELETE].size;j.info(`\u2299 Push: conflicts detected \xB7 ${t}`),await Fs(e,(n,r)=>{Re(n)&&s[we.DELETE].has(r.uuid)&&j.info(`\u2514\u2500\u2500 ./membrane/${n} (deleted locally)`)})}l(du,"showConflicts");async function hu(s){j.error("\u25A0 Error"),j.error(`\u2514\u2500\u2500 ${s.message}`),j.error(` ${s.stack}`)}l(hu,"showError");const qs=[{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=x.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(O.existsSync(s))try{t=JSON.parse(O.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return O.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=x.join(process.cwd(),".cursor"),e=x.join(s,"mcp.json");O.existsSync(s)||O.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(O.existsSync(e))try{n=JSON.parse(O.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return O.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function pu({onExit:s,onComplete:e}){const[t,n]=q(0),[r,i]=q(!1),[o,a]=q(null),[c,u]=q(""),[f,d]=q("");Me((w,p)=>{if(c||f){(p.escape||w==="q"||p.return)&&e();return}if(r)p.return||w===" "?h(o):p.escape&&(i(!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(qs.length-1,t+1));else if(p.return||w===" "){const y=qs[t];a(y),i(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){d(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return c?T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:T(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"green",children:"Success"})]})}),T(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"green",children:c}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:T(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(C,{color:"red",children:f})}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:T(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Confirmation"})]})}),T(S,{flexDirection:"column",paddingLeft:2,children:[T(C,{children:["Connect ",m(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,children:m(C,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:T(C,{children:[m(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:T(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(C,{color:"cyan",children:"Select Agent"})]})}),T(S,{flexDirection:"column",paddingLeft:2,children:[m(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),m(S,{marginTop:1,flexDirection:"column",children:qs.map((w,p)=>T(S,{children:[T(C,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),T(C,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}l(pu,"AddMcpServerScreen");function mu(){const[s,e]=q(null),[t,n]=q([]),[r,i]=q(null);return ze(()=>{const o=l(({status:c})=>{e(c),i(null)},"handleMcpStatusChanged"),a=l(({servers:c})=>{n(c),i(null)},"handleMcpServersChanged");return Ne.on(H.McpStatusChanged,o),Ne.on(H.McpServersChanged,a),()=>{Ne.off(H.McpStatusChanged,o),Ne.off(H.McpServersChanged,a)}},[]),{mcpStatus:s,allMcpServers:t,error:r,isRunning:s?.isRunning||!1,toolsCount:s?.toolsCount||0,totalRequests:s?.totalRequests||0,lastActivity:s?.lastActivity,processId:s?.processId,serverCount:t.length}}l(mu,"useMcpStatus");function gu(){const{error:s,serverCount:e,allMcpServers:t}=mu(),n=Math.min(100,process.stdout.columns||100);return T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:T(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(C,{color:"red",children:"error reading status"}):e===0?m(C,{color:"yellow",children:"none"}):m(C,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:T(C,{color:"grey",children:["Connect your AI agents to Membrane.",m(Ko,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&m(S,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>m(S,{children:T(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(C,{color:"grey",children:"[a: connect an agent]"})})]})}l(gu,"Agent");const wo=l(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function bo(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}l(bo,"truncateText");function yu({children:s}){const{state:e,logs:t}=de();return!e||e===M.NOT_INITIALIZED?T(S,{gap:1,flexDirection:"row",children:[m(Xo,{type:"dots"}),m(C,{children:"Initializing..."})]}):e===M.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===M.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(C,{color:wo(n.type),children:n.message},n.timestamp+r))}):s}l(yu,"EnsureInitialized");function wu(){const{stats:s}=de(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:T(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(C,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>T(S,{children:[m(S,{width:20,children:T(C,{children:[t,":"]})}),m(C,{color:"green",children:n})]},t))})]})}l(wu,"ElementStats");const Us=5,bu=6;function Su(){const{logs:s}=de(),[e,t]=q(0),n=Math.min(100,process.stdout.columns||100),r=Us,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),c=n-bu,u=e<s.length-r,f=e>0;return Me((d,h)=>{if(s.length!==0)if(h.upArrow){const g=Math.max(0,s.length-r);t(w=>Math.min(g,w+1))}else h.downArrow?t(g=>Math.max(0,g-1)):(d==="G"||d==="g")&&t(0)}),T(S,{flexDirection:"column",paddingTop:1,children:[T(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Us&&m(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,h)=>m(S,{marginLeft:1,children:m(C,{color:wo(d.type),children:bo(d.message,c)})},d.timestamp+h)),s.length>Us&&T(S,{marginLeft:1,flexDirection:"row",children:[u&&m(C,{color:"grey",children:"\u2191 "}),f&&m(C,{color:"grey",children:"\u2193 "})]})]})}l(Su,"Logs");const In=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Cu(){const{state:s,resolveConflicts:e,exit:t}=de(),[n,r]=q(0),[i,o]=q(!1),[a,c]=q(!1);return Me((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){c(!a);return}f.upArrow?r(d=>d>0?d-1:In.length-1):f.downArrow?r(d=>d<In.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),In[n].value==="sync"?e({watch:!0}):t())}}),ze(()=>{s!==M.CONFLICTS&&i&&o(!1)},[s,i]),T(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(ku,{isExpanded:a})}),T(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(C,{color:"white",bold:!0,children:"What would you like to do?"}),m(C,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?T(S,{flexDirection:"row",gap:1,children:[m(_t,{type:"dots"}),m(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:In.map((u,f)=>m(S,{flexDirection:"column",children:T(S,{flexDirection:"row",gap:1,children:[m(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),m(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}l(Cu,"ResolveChangesUI");const vu={[be.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[be.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[be.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function ku({isExpanded:s,showControls:e=!0}){const{conflicts:t}=de(),n=5,r=Fo(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return m(S,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,c]=i.split("-"),u=vu[a][c];return T(S,{flexDirection:"column",children:[T(S,{flexDirection:"row",gap:1,children:[T(C,{color:"yellow",children:[u.label," (",o.length,")"]}),m(C,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>m(S,{marginLeft:2,children:T(C,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:T(C,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&m(S,{marginLeft:2,children:m(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}l(ku,"Conflicts");function Eu(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=de(),i=n?.name,o=i?bo(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return ze(()=>{r({watch:!0})},[]),T(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:T(S,{flexDirection:"row",gap:1,children:[m(C,{bold:!0,children:"\u{1F504} Workspace"}),T(C,{color:Iu(e),children:[" [",Tu(e),"] "]})]})}),T(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Local:"})}),m(C,{color:"grey",children:process.cwd()})]}),T(S,{children:[m(S,{width:12,children:m(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?T(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):T(C,{children:[m(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===M.CONFLICTS?m(Cu,{}):T(jt,{children:[m(S,{paddingTop:1,children:m(wu,{})}),t.length>0&&m(Su,{})]})]})}l(Eu,"Workspace");function Tu(s){switch(s){case M.PULLING:return"pulling";case M.PUSHING:return"pushing";case M.CONFLICTS:return"conflicts";case M.SYNCED:return"synced";case M.ERROR:return"error";case M.WATCHING:return"tracking changes";case M.RESOLVING:return"resolving";case M.NOT_SYNCED:return"not synced";case M.INITIALIZED:return"initialized";case M.SETTING_UP:return"setup required";default:return"unknown"}}l(Tu,"getStatusDisplay");function Iu(s){switch(s){case M.PULLING:return"yellow";case M.PUSHING:return"yellow";case M.CONFLICTS:return"red";case M.SYNCED:return"green";case M.ERROR:return"red";case M.WATCHING:return"green";case M.RESOLVING:return"yellow";case M.NOT_SYNCED:return"grey";case M.SETTING_UP:return"yellow";default:return"grey"}}l(Iu,"getStatusColor");const Ou="https://console.integration.app/w";function Au(){const s=Il(),e=_n(!0),{exit:t,state:n}=de(),[r,i]=q(null),o=r??(n===M.SETTING_UP?"setup":"main");Me(c=>{o==="main"&&(c==="w"&&i("workspace-selection"),c==="a"&&i("add-mcp-server"),c==="o"&&n===M.INITIALIZED&&a(),c==="s"&&i("setup"))});async function a(){try{const c=await gr(s),u=`${Ou}/${c}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";na(`${f} "${u}"`)}catch(c){console.error("Failed to open workspace:",c),t()}}return l(a,"handleOpenWorkspace"),ze(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(no,{onExit:l(()=>i(null),"onExit")}):o==="add-mcp-server"?m(pu,{onExit:l(()=>i(null),"onExit"),onComplete:l(()=>i(null),"onComplete")}):o==="setup"?m(so,{onComplete:l(()=>i(null),"onComplete")},Date.now()):m(yu,{children:T(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(gu,{})}),m(Eu,{}),m(S,{paddingLeft:2,children:m(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}l(Au,"Main");const $u=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 Real-time agent mode is experimental and subject to changes. \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(`
156
+ `),"createExperimentalWarning$1");function Nu(s,e){s.command("sync").description("\u26A0\uFE0F EXPERIMENTAL: Sync workspace data in real-time - This feature is experimental and subject to changes. Use in production environments is not recommended.").option("--watch","Watch for changes and sync automatically",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane sync --watch # Start real-time sync with watch mode"," membrane sync --watch --rps 5 # Limit to 5 requests per second",""].join(`
157
+ `)).action(async t=>{if(t.watch||(console.error("Error: The sync command requires the --watch flag"),console.error("Usage: membrane sync --watch"),process.exit(1)),t.rps!==void 0){const n=t.rps;!isNaN(n)&&n>0&&n<=1e3?D.init({maxRequestsPerSecond:n}):(b.error(`Invalid RPS value: ${n}. Must be between 1 and 1000.`),process.exit(1))}console.warn($u()),Fn(De.createElement(Ds,{cwd:process.cwd(),membraneCLIService:e,children:De.createElement(Au)}))})}l(Nu,"setupSyncCommand");class xu{static{l(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=zn(),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 Pu="claude-sonnet-4-20250514";class zs{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:n,client:r,options:i,llm:o}){this.client=r,this.connectionId=e,this.testsDir=t,this.testBasePath=n,this.llm=o,this.options=i}static async create({connectionId:e,testBasePath:t,options:n}){const r=Kt();if(!r)throw new Error("No configuration found. Please set MEMBRANE_WORKSPACE_KEY and MEMBRANE_WORKSPACE_SECRET environment variables, or run `membrane init` first.");if(!r.workspaceKey||!r.workspaceSecret)throw new Error("Missing workspace credentials");if(!r.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const i=new Ys({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new sa({apiKey:r.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const f=await o.messages.create({model:Pu,max_tokens:u,messages:[{role:"user",content:c}]});return f.content[0].type==="text"?f.content[0].text:""},"complete")};return new zs({client:i,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(),Bn(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=_.join(this.testsDir,this.testBasePath,this.connectionId,e);return Zn(t)}async writeYaml(e,t){const n=_.join(this.testsDir,this.testBasePath,this.connectionId,e);F.mkdirSync(_.dirname(n),{recursive:!0}),F.writeFileSync(n,le.dump(t,{noRefs:!0}))}writeResults(e){const t=_.join(this.testsDir,this.testBasePath,this.connectionId);F.mkdirSync(t,{recursive:!0});const n=_.join(t,"test-results.yaml");F.writeFileSync(n,le.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},r={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Kn.sign(n,e.workspaceSecret,r)}}ia.interpolate=/{{([\s\S]+?)}}/g;function Js(s,e){if(typeof s=="string"){const t=ra(s),n={state:e,random:{number:l(()=>vt.number.int(),"number"),alphaNumeric:l(i=>vt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:l(()=>vt.company.name(),"name"),catchPhrase:l(()=>vt.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>vt.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},r=t(n);return s.includes("{{")&&s.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${s}`),console.debug(`[TEMPLATE] Output: ${r}`)),r}return Array.isArray(s)?s.map(t=>Js(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,Js(n,e)])):s}l(Js,"processNode");function Lu(s,e){return Js(s,e)}l(Lu,"handleTemplate");class Ru{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,r={},i={},o;for(;!t;)try{i=await e.readTestCase(),i||(i=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),i),console.debug(`${v.bold.yellow("[initialized]")} ${v.yellow(e.path)}`)),o=Lu(i,this.environment.state),await e.run(o),console.debug(`${v.bold.green("[success]")} ${v.yellow(e.path)}`),t=!0,r=e.getResult(),xn(this.result,e.path,r)}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}`)}}xn(this.result,e.path,{error:he(c)}),t=!0,r={error:he(c)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Bn(this.result,e.getResult())}}class Le{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,this.resultsLocator=""}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 r=await e();r?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:r})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:n}))}catch(r){this.assertions.push({message:t,result:!1,details:he(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Ws(s,e){const t={};for(const n in e){if(!(n in s)){t[n]=e[n];continue}const r=s[n],i=e[n];if(r&&i&&typeof r=="object"&&typeof i=="object"){if(Array.isArray(r)&&Array.isArray(i)){const o=i.filter(a=>!r.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)||!Vs(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(r)&&!Array.isArray(i)){const o=Ws(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}Vs(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}l(Ws,"getNotMatchingSubFields");function Vs(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(Vs,"softCompare");class Du extends Le{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=Pn(this.dataCollection);if(this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!i.record,"Record is returned from findById"),i.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:i.record.fields});const o=Qs(n),a=Dt(e.input.fields,o,{skipUnknownFields:!0}),c=Dt(i.record.fields,o),u=Ws(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const r=Ro(n??{});if(r.length>0){const i={};r.forEach(a=>{const c=Do(e.input.fields,a);typeof c<"u"&&xn(i,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:i});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=Pn(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=he(t),r=Pn(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to create a data record in a data collection with the following fields schema:
158
158
 
159
159
  ${JSON.stringify(r,null,2)}
160
160
 
@@ -178,7 +178,7 @@ Format your response as a JSON object with two fields:
178
178
  "fields": { ... fixed fields ... }
179
179
  }.
180
180
 
181
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),l=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,l.explanation),{input:{fields:l.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.
181
+ 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.
182
182
 
183
183
  ${this.getExampleRecordsPrompt(t)}
184
184
 
@@ -194,7 +194,7 @@ ${JSON.stringify(r,null,2)}`).join(`
194
194
 
195
195
  `)}.
196
196
 
197
- 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 Xs(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields??{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=er(r);n[i]=await this.fetchExampleRecords(r)}return n}}class Ru extends Le{static{c(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=he(t),r=`I'm trying to delete a record from a data collection.
197
+ 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 Xs(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields??{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=er(r);n[i]=await this.fetchExampleRecords(r)}return n}}class Mu extends Le{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=he(t),r=`I'm trying to delete a record from a data collection.
198
198
 
199
199
  I tried to delete a record with this ID:
200
200
 
@@ -214,7 +214,7 @@ Format your response as a JSON object with two fields:
214
214
  "id": "fixed id"
215
215
  }.
216
216
 
217
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Mu extends Le{static{c(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=he(t),r=`I'm trying to find a record by ID in a data collection.
217
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class ju extends Le{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=he(t),r=`I'm trying to find a record by ID in a data collection.
218
218
 
219
219
  I tried to find a record with this ID:
220
220
 
@@ -234,7 +234,7 @@ Format your response as a JSON object with two fields:
234
234
  "id": "fixed id"
235
235
  }.
236
236
 
237
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class ju extends Le{static{c(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:n,direction:r}=e.input.sort,i=t.records;if(i.length>1)for(let o=1;o<i.length;o++){const a=i[o-1].fields?.[n],l=i[o].fields?.[n];a==null||l==null||(r==="asc"?await this.assert(()=>a<=l,`Records are sorted by ${n} in ascending order`):await this.assert(()=>a>=l,`Records are sorted by ${n} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const n=he(t),r=`I'm trying to list records from a data collection.
237
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class _u extends Le{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:r}=e.input.sort,i=t.records;if(i.length>1)for(let o=1;o<i.length;o++){const a=i[o-1].fields?.[n],c=i[o].fields?.[n];a==null||c==null||(r==="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=he(t),r=`I'm trying to list records from a data collection.
238
238
 
239
239
  I tried to list records with these parameters:
240
240
 
@@ -254,7 +254,7 @@ Format your response as a JSON object with two fields:
254
254
  "input": { ... fixed parameters ... }
255
255
  }.
256
256
 
257
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class _u extends Le{static{c(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const n=t.record,i=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id})).record;for(const[o,a]of Object.entries(e.input.query)){const l=i.fields?.[o];await this.assert(()=>Vs(l,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(l)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const n={},r=t.fields||{},i=Object.entries(r).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(i.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of i)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=he(t),r=`I'm trying to match a record in a data collection.
257
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Fu extends Le{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,i=(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=i.fields?.[o];await this.assert(()=>Vs(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={},r=t.fields||{},i=Object.entries(r).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(i.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of i)n[o]=a;return{input:{query:n}}}async fixTestCase({config:e,error:t}){const n=he(t),r=`I'm trying to match a record in a data collection.
258
258
 
259
259
  I tried to match a record with this query:
260
260
 
@@ -274,7 +274,7 @@ Format your response as a JSON object with two fields:
274
274
  "query": { ... fixed query ... }
275
275
  }.
276
276
 
277
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Fu extends Le{static{c(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const n=t.records.some(r=>r.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.
277
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Ku extends Le{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(r=>r.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.
278
278
 
279
279
  Record fields:
280
280
  ${JSON.stringify(e,null,2)}
@@ -299,7 +299,7 @@ Format your response as a JSON object with two fields:
299
299
  "input": { ... fixed parameters ... }
300
300
  }.
301
301
 
302
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Ku extends Le{static{c(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=n}async run(){const e=Object.keys(this.dataCollection.fieldsSchema||{}).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class qu extends Le{static{c(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!n.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=n.id,this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!r.record,"Record is returned from findById");const i=Ln(this.dataCollection),o=Qs(i),a=Rt(e.input.fields,o,{skipUnknownFields:!0}),l=Rt(r.record.fields,o),u=Ws(l,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:l})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!r?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=r.records[0].id}const t=Ln(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=he(t),r=Ln(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to update a data record in a data collection with the following fields schema:
302
+ Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:r,maxTokens:1e3}),o=JSON.parse(i.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Bu extends Le{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 qu extends Le{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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:n.id});await this.assert(()=>!!r.record,"Record is returned from findById");const i=Ln(this.dataCollection),o=Qs(i),a=Dt(e.input.fields,o,{skipUnknownFields:!0}),c=Dt(r.record.fields,o),u=Ws(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 r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!r?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=r.records[0].id}const t=Ln(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=he(t),r=Ln(this.dataCollection),i=await this.getExampleRecordsForSchema(r),o=`I'm trying to update a data record in a data collection with the following fields schema:
303
303
 
304
304
  ${JSON.stringify(r,null,2)}
305
305
 
@@ -323,7 +323,7 @@ Format your response as a JSON object with two fields:
323
323
  "fields": { ... fixed fields ... }
324
324
  }.
325
325
 
326
- Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),l=JSON.parse(a.trim());return console.warn(v.bold.yellow("[auto-fix]"),`${this.path}:`,l.explanation),{input:{id:e.input.id,fields:l.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.
326
+ 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.
327
327
 
328
328
  ${this.getExampleRecordsPrompt(t)}
329
329
 
@@ -339,9 +339,9 @@ ${JSON.stringify(r,null,2)}`).join(`
339
339
 
340
340
  `)}.
341
341
 
342
- 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 Xs(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=er(r);n[i]=await this.fetchExampleRecords(r)}return n}}const Gs={spec:{testerClass:Ku},create:{testerClass:Du,operationKey:"create"},"find-by-id":{testerClass:Mu,operationKey:"findById"},list:{testerClass:ju,operationKey:"list"},match:{testerClass:_u,operationKey:"match"},search:{testerClass:Fu,operationKey:"search"},update:{testerClass:qu,operationKey:"update"},delete:{testerClass:Ru,operationKey:"delete"}};class Bu extends Lu{static{c(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:n}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=n}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);j.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=Gs[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Gs).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(Gs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){j.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Uu extends Nu{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){j.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(j.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(j.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),j.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,f=[...a,...t?t.split("/"):[]].join("/"),d=await zs.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await d.client.get(`connections/${l}/data`),y=[],p=f?f.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let k,T;p.length>=1&&(T=p[0],p.length>=2&&p[1].trim()!==""&&(k=p[1]));for(const $ of g){if(T&&T!==$.key)continue;const I=new Bu({environment:d,dataCollectionKey:$.key,testMethod:k});y.push(I)}}y.length===0&&(j.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const w={};for(const k of y){await k.run();const T=k.getResult();j.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),qn(w,T)}console.debug("[TestRunner] All results collected:",Object.keys(w)),d.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const On=c(()=>[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(`
343
- `),"createExperimentalWarning");function Ju(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",On()).action(async()=>{console.warn(On()),j.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",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"),"",On()].join(`
344
- `)).action(async(t,n)=>{try{console.warn(On()),t||(j.error("Test path is required"),process.exit(1)),j.header(`Testing: ${t}`);const r=new Uu({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),j.success("Tests completed")}catch(r){r instanceof Error&&(j.error(r.message),process.exit(1)),j.error("An unknown error occurred"),process.exit(1)}})}c(Ju,"setupTestCommand");const Wu=c(()=>{try{const s=Oo(import.meta.url),e=Io(s),t=$n(e,"..","package.json");return JSON.parse(Eo(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),Co=Wu();function Vu(){process.on("SIGINT",()=>process.exit(130));const s=new Ao().name("membrane").description("Command-line interface for Membrane Agent").version(Co,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>v.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${v.cyan(n.name())} ${v.gray("[options]")} ${v.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${v.gray("\u25B8")} ${v.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>v.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>v.gray(n.description),"optionDescription"),commandDescription:c(n=>v.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
345
- ${v.bold.cyan("Membrane Agent CLI")} ${v.gray(`v${Co}`)}
342
+ 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 Xs(e,r=>{if(r.referenceCollection){const i=r.referenceCollection.key,o=r.referenceCollection.parameters,a=`${i}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),n.push({key:i,parameters:o}))}return r}),n}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(n=>({id:n.id,fields:n.fields||{}}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),n={};for(const r of t){const i=er(r);n[i]=await this.fetchExampleRecords(r)}return n}}const Gs={spec:{testerClass:Bu},create:{testerClass:Du,operationKey:"create"},"find-by-id":{testerClass:ju,operationKey:"findById"},list:{testerClass:_u,operationKey:"list"},match:{testerClass:Fu,operationKey:"match"},search:{testerClass:Ku,operationKey:"search"},update:{testerClass:qu,operationKey:"update"},delete:{testerClass:Mu,operationKey:"delete"}};class Uu extends Ru{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);j.info("\u{1F680} Running tests...");for(const n of t)await this.runTest(n);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const n=Gs[e];if(!n)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const r="operationKey"in n?n.operationKey:void 0;if(!this.isOperationAvailable(t,r))throw new Error(`${r} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(n,t)}createAllAvailableTesters(e){return Object.entries(Gs).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(Gs).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){j.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Ju extends xu{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){j.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(j.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(j.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),j.error("Supported test types: connectors"),process.exit(1));const c=o,u=i,f=[...a,...t?t.split("/"):[]].join("/"),d=await zs.create({connectionId:c,testBasePath:u,options:{fix:n}}),g=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 k,E;p.length>=1&&(E=p[0],p.length>=2&&p[1].trim()!==""&&(k=p[1]));for(const A of g){if(E&&E!==A.key)continue;const I=new Uu({environment:d,dataCollectionKey:A.key,testMethod:k});w.push(I)}}w.length===0&&(j.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const y={};for(const k of w){await k.run();const E=k.getResult();j.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Bn(y,E)}console.debug("[TestRunner] All results collected:",Object.keys(y)),d.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const On=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(`
343
+ `),"createExperimentalWarning");function Wu(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",On()).action(async()=>{console.warn(On()),j.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",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"),"",On()].join(`
344
+ `)).action(async(t,n)=>{try{console.warn(On()),t||(j.error("Test path is required"),process.exit(1)),j.header(`Testing: ${t}`);const r=new Ju({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),j.success("Tests completed")}catch(r){r instanceof Error&&(j.error(r.message),process.exit(1)),j.error("An unknown error occurred"),process.exit(1)}})}l(Wu,"setupTestCommand");const Vu=l(()=>{try{const s=Io(import.meta.url),e=To(s),t=$n(e,"..","package.json");return JSON.parse(Eo(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),So=Vu();function Gu(){process.on("SIGINT",()=>process.exit(130));const s=new Oo().name("membrane").description("Command-line interface for Membrane Agent").version(So,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:l(n=>v.cyan(n.name()),"subcommandTerm"),commandUsage:l(n=>n.name()==="membrane"?`${v.cyan(n.name())} ${v.gray("[options]")} ${v.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:l(n=>{const r=n.flags;return`${v.gray("\u25B8")} ${v.cyan(r)}`},"optionTerm"),subcommandDescription:l(n=>v.gray(n.description()),"subcommandDescription"),optionDescription:l(n=>v.gray(n.description),"optionDescription"),commandDescription:l(n=>v.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
345
+ ${v.bold.cyan("Membrane Agent CLI")} ${v.gray(`v${So}`)}
346
346
 
347
- `);const e=new wl(Tn.Cli,process.cwd());Gl(s),iu(s),Fl(s),Ju(s),Ml(s),$u(s,e),Pl(s,e),ha(s,e),Al(s,e),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(Vu,"runCLI"),Vu();
347
+ `);const e=new yl(En.Cli,process.cwd());zl(s),ou(s),Kl(s),Wu(s),jl(s),Nu(s,e),xl(s,e),da(s,e),Ol(s,e),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}l(Gu,"runCLI"),Gu();