@membranehq/cli 1.1.11 → 1.1.13

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 +127 -126
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,173 +1,174 @@
1
1
  #!/usr/bin/env node
2
- var bc=Object.defineProperty;var c=(s,e)=>bc(s,"name",{value:e,configurable:!0});import{jsx as g,jsxs as O,Fragment as Rs}from"react/jsx-runtime";import*as K from"node:path";import{join as Ls,resolve as Sc,dirname as vc}from"node:path";import{useInput as rt,Box as v,Text as C,Newline as Cc,render as bn}from"ink";import kc from"minimist";import{SWRConfig as Tc}from"swr";import it,{createContext as mi,useState as H,useEffect as Ge,useContext as gi,useMemo as _c,useRef as Ec}from"react";import yi from"swr/immutable";import wi from"os";import B from"path";import Oc from"conf";import{MembraneConfigLoader as Ac,MembraneAxiosInstance as Ic,MembraneClient as bi,WorkspaceElementType as R,WorkspaceElementSpecs as De,WorkspaceSyncEventType as $c,ConnectorFileUpdateType as Ds,setValueAtLocator as js,extractMembraneErrorData as ke,getDataCollectionCreateFields as Fs,excludeWriteOnlyFieldsFromSchema as Si,valueToSchema as Sn,getRequiredFieldsFromSchema as Nc,getValueAtLocator as xc,walkSchema as vi,makeDataLocationPath as Ci,getDataCollectionUpdateFields as qs}from"@membranehq/sdk";import Ks from"jsonwebtoken";import*as L from"node:fs";import{mkdirSync as Pc,writeFileSync as Mc,readFileSync as Rc}from"node:fs";import{EventEmitter as Lc}from"events";import Dc from"lodash/isEqual.js";import Dt from"js-yaml";import*as jc from"node:crypto";import{createHash as Fc}from"node:crypto";import qc from"chokidar";import{EventSource as Kc}from"eventsource";import F from"fs";import Bc from"archiver";import Uc from"form-data";import Wc from"unzipper";import*as Jc from"node:os";import{exec as Hc}from"node:child_process";import{Spinner as Vc,TextInput as Gc,Select as zc}from"@inkjs/ui";import vn from"ink-spinner";import Yc from"ink-text-input";import{fileURLToPath as Xc}from"node:url";import T from"chalk";import{Command as Qc}from"commander";import Bs from"lodash/camelCase.js";import Us from"lodash/upperFirst.js";import Zc from"code-block-writer";import el from"lodash/uniqBy.js";import{FastMCP as tl}from"fastmcp";import Ws from"axios";import{z as W}from"zod";import Js from"lodash/merge.js";import{faker as jt}from"@faker-js/faker";import nl from"lodash/template.js";import sl from"lodash/templateSettings.js";const rl="membrane",il="membrane.config.yml",Hs="https://api.integration.app";function Vs(){const s=process.cwd(),e=K.join(s,rl),t=K.join(s,il),n=e,r=K.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(Vs,"getPaths");function ki(){return Vs().membraneDirPath}c(ki,"getBasePath");const ol={pat:{type:"string"},workspace:{type:"object"}},Ti=new Oc({schema:ol,configName:"config",cwd:B.join(wi.homedir(),".membrane")}),al=c(s=>{Ti.set("pat",s)},"setPat"),_i=c(()=>Ti.get("pat"),"getPat");class Ei{static{c(this,"AccountApiClient")}constructor(e=Hs){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=_i();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 cl=c(s=>{const e=new Ei(Hs);return t=>e.get(t)},"createAccountApiFetcher");class Pt{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Ac}static getInstance(){return Pt.instance||(Pt.instance=new Pt),Pt.instance}loadConfig(e){e&&e!==this.sdkLoader.getCwd()&&this.sdkLoader.setCwd(e);try{return this.sdkLoader.loadConfig({validate:!0})}catch(t){if(t.message?.includes("Failed to parse"))throw t;return null}}clearCache(){this.sdkLoader.clearCache()}updateConfig(e){return this.sdkLoader.updateConfig(e)}saveToFile(e){return this.sdkLoader.saveToFile(e)}isCacheDefined(){return this.sdkLoader.hasValidConfig()}}const Ft=Pt.getInstance();function Cn(s){return Ft.loadConfig(s)}c(Cn,"readProjectConfig");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class Gs extends Lc{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class ll extends Gs{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.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 U.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 U.withClient(t=>t.post("/local-clients",{hostname:wi.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 U.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await U.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 Oe=new ll({heartbeatIntervalMs:15e3}),ul="membrane",fl=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function ot(s){return K.join(s,ul)}c(ot,"getMembraneDir");const Oi=Ls(ot(process.cwd()),".logs");class dl{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Oe}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Pc(Oi,{recursive:!0});const i=Ls(Oi,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
3
- `);return Mc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new dl;class hl{static{c(this,"RequestLogger")}constructor(e=Ic){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=>{t.metadata={startTime:Date.now()};const{method:n,url:r}=this.getRequestDetails(t);return b.debug(`[Request]: ${n} ${r}`),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}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){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 pl{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 hl,this.requestLogger.setup()}async withClient(e,t=process.cwd()){return this.withRetry(async()=>{const n=await this.getClient(t);await this.acquireSemaphore();try{return await this.waitIfNeeded(),this.recordRequest(),await this.withTimeout(e(n),this.requestTimeout)}finally{this.releaseSemaphore()}},"API request")}async generateAccessToken(e,t){return Ks.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=Cn(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 bi({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 U=new pl;async function Ai(s){const{id:e}=await U.withClient(t=>t.get("org-workspace-id"),s);return e}c(Ai,"getWorkspaceId");var q={},kn={},Ii;function $i(){if(Ii)return kn;Ii=1,Object.defineProperty(kn,"__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"),kn.default=s,kn}c($i,"requireJsCamelcase");var Tn={},Ni;function xi(){if(Ni)return Tn;Ni=1,Object.defineProperty(Tn,"__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"),Tn.default=s,Tn}c(xi,"requireJsSnakecase");var _n={},Pi;function Mi(){if(Pi)return _n;Pi=1,Object.defineProperty(_n,"__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"),_n.default=s,_n}c(Mi,"requireJsPascalcase");var En={},Ri;function ml(){if(Ri)return En;Ri=1,Object.defineProperty(En,"__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"),En.default=s,En}c(ml,"requireJsDotcase");var On={},Li;function gl(){if(Li)return On;Li=1,Object.defineProperty(On,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),On.default=s,On}c(gl,"requireJsPathcase");var An={},Di;function yl(){if(Di)return An;Di=1,Object.defineProperty(An,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),An.default=s,An}c(yl,"requireJsTextcase");var In={},ji;function wl(){if(ji)return In;ji=1,Object.defineProperty(In,"__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"),In.default=s,In}c(wl,"requireJsSentencecase");var $n={},Fi;function bl(){if(Fi)return $n;Fi=1,Object.defineProperty($n,"__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"),$n.default=s,$n}c(bl,"requireJsHeadercase");var Nn={},qi;function Ki(){if(qi)return Nn;qi=1,Object.defineProperty(Nn,"__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"),Nn.default=s,Nn}c(Ki,"requireJsKebabcase");var at={},zs={},Bi;function ct(){return Bi||(Bi=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})}}(zs)),zs}c(ct,"requireUtils");var Ui;function Sl(){if(Ui)return at;Ui=1;var s=at&&at.__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(at,"__esModule",{value:!0});var e=ct();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"),at.default=t,at}c(Sl,"requireLowercaseKeysObject");var lt={},Wi;function vl(){if(Wi)return lt;Wi=1;var s=lt&&lt.__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(lt,"__esModule",{value:!0});var e=ct();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"),lt.default=t,lt}c(vl,"requireUppercaseKeysObject");var ut={},Ji;function Cl(){if(Ji)return ut;Ji=1;var s=ut&&ut.__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(ut,"__esModule",{value:!0});var e=ct(),t=$i();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 p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"camelKeys"),ut.default=n,ut}c(Cl,"requireCamelcaseKeysObject");var ft={},Hi;function kl(){if(Hi)return ft;Hi=1;var s=ft&&ft.__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(ft,"__esModule",{value:!0});var e=ct(),t=xi();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 p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"snakeKeys"),ft.default=n,ft}c(kl,"requireSnakecaseKeysObject");var dt={},Vi;function Tl(){if(Vi)return dt;Vi=1;var s=dt&&dt.__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(dt,"__esModule",{value:!0});var e=ct(),t=Mi();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 p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"pascalKeys"),dt.default=n,dt}c(Tl,"requirePascalcaseKeysObject");var ht={},Gi;function _l(){if(Gi)return ht;Gi=1;var s=ht&&ht.__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(ht,"__esModule",{value:!0});var e=ct(),t=Ki();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 p=n({key:f},i);d=p.key}return d}))),o[u]=l}),o}return c(n,"kebabKeys"),ht.default=n,ht}c(_l,"requireKebabcaseKeysObject");var zi;function El(){if(zi)return q;zi=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=$i();q.toCamelCase=s.default;var e=xi();q.toSnakeCase=e.default;var t=Mi();q.toPascalCase=t.default;var n=ml();q.toDotCase=n.default;var r=gl();q.toPathCase=r.default;var i=yl();q.toTextCase=i.default;var o=wl();q.toSentenceCase=o.default;var a=bl();q.toHeaderCase=a.default;var l=Ki();q.toKebabCase=l.default;var u=Sl();q.lowerKeys=u.default;var f=vl();q.upperKeys=f.default;var d=Cl();q.camelKeys=d.default;var p=kl();q.snakeKeys=p.default;var m=Tl();q.pascalKeys=m.default;var y=_l();q.kebabKeys=y.default;var h=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");q.toLowerCase=h;var w=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");q.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:h,lowerKeys:u.default,upperKeys:f.default,camelKeys:d.default,snakeKeys:p.default,pascalKeys:m.default,kebabKeys:y.default};return q.default=k,q}c(El,"requireLib");var Ys,Yi;function Ol(){return Yi||(Yi=1,Ys=El()),Ys}c(Ol,"requireJsConvertCase");var Al=Ol();const Ae={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},le={[R.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")},[R.Connector]:{element:"connector",elements:"connectors",exportable:!1},[R.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[R.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[R.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[R.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[R.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[R.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[R.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[R.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Il(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Il,"baseExportCleanup");const $l=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],Xi=[R.Action,R.FieldMapping,R.Flow,R.DataSource,R.Package];class X{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||X.extractIntegrationKey(r)}get id(){return X.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=De[this.type].apiPath;if(this.integrationKey){const t=De[R.Integration].apiPath;return K.join(t,this.integrationKey,e,this.key)}return K.join(e,this.key)}get path(){return K.join(this.dirPath,"spec.yaml")}get relativePath(){return K.relative(ot(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(ot(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Dc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return $l.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return le?.[this.type]?.parentKey&&(e=le?.[this.type]?.parentKey),e}static new(e,t,n,r){return new X(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 X(e,t.key,n,t)}static fromPathAndData(e,t){const n=X.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?X.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new X(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=X.parsePath(e);if(t)return X.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===R.Integration?`${e}:${t}`:X.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(De).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(R).find(t=>De[t].apiPath===e)}static getRelativePath(e){return K.relative(ot(process.cwd()),e)}static isIntegrationSpecific(e){return Xi.includes(e)}static canBeIntegrationSpecific(e){return Xi.includes(e)}}class Qi{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=[R.Integration,R.Connector],r=Object.keys(le),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),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 deleteElement(e,t){}}function Xs(s,e=!0){if(L.existsSync(s))try{const t=L.readFileSync(s,"utf8");return Dt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(Xs,"readYaml");function Nl(s,e,t){try{const n=Dt.dump(e,t);L.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Nl,"writeYaml");class xl extends Qi{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=ot(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,De[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,De[R.Integration].apiPath,o.key,De[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=K.join(this.basePath,t.dirPath),r=K.join(this.basePath,t.path);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),Nl(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,De[R.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=Xs(e);if(t)return X.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.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||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Pl extends Qi{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=X.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!X.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 U.withClient(n=>n[le[e.type].element](e.data.id).get(),process.cwd());return X.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await U.withClient(o=>o[le[e.type].elements].create(n),process.cwd()),i=X.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");const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await U.withClient(a=>a[le[e.type].element](t.data.id).put(r),process.cwd()),o=X.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 U.withClient(t=>t[le[e.type].element](e.data.id).archive(),process.cwd()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const t=(await U.withClient(n=>n.integrations.findAll(),process.cwd())).map(n=>X.fromData(R.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;try{n=await U.withClient(r=>r[le[t].element](e).get())}catch{return}return X.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===R.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===R.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===R.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===R.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!==R.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){return(await U.withClient(i=>i[le[e].elements].findAll(t),process.cwd())).filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),X.fromData(e,i)))}}const Qs=Symbol.for("yaml.alias"),Zs=Symbol.for("yaml.document"),je=Symbol.for("yaml.map"),Zi=Symbol.for("yaml.pair"),Te=Symbol.for("yaml.scalar"),pt=Symbol.for("yaml.seq"),pe=Symbol.for("yaml.node.type"),Fe=c(s=>!!s&&typeof s=="object"&&s[pe]===Qs,"isAlias"),ze=c(s=>!!s&&typeof s=="object"&&s[pe]===Zs,"isDocument"),mt=c(s=>!!s&&typeof s=="object"&&s[pe]===je,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[pe]===Zi,"isPair"),J=c(s=>!!s&&typeof s=="object"&&s[pe]===Te,"isScalar$1"),gt=c(s=>!!s&&typeof s=="object"&&s[pe]===pt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[pe]){case je:case pt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[pe]){case Qs:case je:case Te:case pt:return!0}return!1}c(Y,"isNode");const eo=c(s=>(J(s)||z(s))&&!!s.anchor,"hasAnchor"),ce=Symbol("break visit"),to=Symbol("skip children"),_e=Symbol("remove node");function Ye(s,e){const t=no(e);ze(s)?yt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):yt(null,s,t,Object.freeze([]))}c(Ye,"visit$1"),Ye.BREAK=ce,Ye.SKIP=to,Ye.REMOVE=_e;function yt(s,e,t,n){const r=so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),yt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=yt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=yt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=yt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(yt,"visit_");async function xn(s,e){const t=no(e);ze(s)?await wt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await wt(null,s,t,Object.freeze([]))}c(xn,"visitAsync"),xn.BREAK=ce,xn.SKIP=to,xn.REMOVE=_e;async function wt(s,e,t,n){const r=await so(s,e,t,n);if(Y(r)||V(r))return ro(s,n,r),wt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await wt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===ce)return ce;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await wt("key",e.key,t,n);if(i===ce)return ce;i===_e&&(e.key=null);const o=await wt("value",e.value,t,n);if(o===ce)return ce;o===_e&&(e.value=null)}}return r}c(wt,"visitAsync_");function no(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(no,"initVisitor");function so(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(mt(e))return t.Map?.(s,e,n);if(gt(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(J(e))return t.Scalar?.(s,e,n);if(Fe(e))return t.Alias?.(s,e,n)}c(so,"callVisitor");function ro(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(ze(n))n.contents=t;else{const r=Fe(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(ro,"replaceNode");const Ml={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rl=c(s=>s.replace(/[!,[\]{}]/g,e=>Ml[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.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+Rl(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&&Y(e.contents)){const i={};Ye(e.contents,(o,a)=>{Y(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(`
4
- `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function io(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(io,"anchorIsValid");function oo(s){const e=new Set;return Ye(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(oo,"anchorNames");function ao(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(ao,"findNewAnchor");function Ll(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=oo(s));const o=ao(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)||z(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(Ll,"createNodeAnchors");function bt(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=bt(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=bt(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=bt(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=bt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(bt,"applyReviver");function me(s,e,t){if(Array.isArray(s))return s.map((n,r)=>me(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!eo(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(me,"toJS");class er{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,pe,{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(!ze(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=me(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?bt(i,{"":a},"",a):a}}class Pn extends er{static{c(this,"Alias")}constructor(e){super(Qs),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=[],Ye(e,{Node:c((i,o)=>{(Fe(o)||eo(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||(me(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=Mn(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(io(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 Mn(s,e,t){if(Fe(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(z(e)){let n=0;for(const r of e.items){const i=Mn(s,r,t);i>n&&(n=i)}return n}else if(V(e)){const n=Mn(s,e.key,t),r=Mn(s,e.value,t);return Math.max(n,r)}return 1}c(Mn,"getAliasCount");const co=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class P extends er{static{c(this,"Scalar")}constructor(e){super(Te),this.value=e}toJSON(e,t){return t?.keep?this.value:me(this.value,e,t)}toString(){return String(this.value)}}P.BLOCK_FOLDED="BLOCK_FOLDED",P.BLOCK_LITERAL="BLOCK_LITERAL",P.PLAIN="PLAIN",P.QUOTE_DOUBLE="QUOTE_DOUBLE",P.QUOTE_SINGLE="QUOTE_SINGLE";const Dl="tag:yaml.org,2002:";function jl(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(jl,"findTagObject");function qt(s,e,t){if(ze(s)&&(s=s.contents),Y(s))return s;if(V(s)){const d=t.schema[je].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 Pn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Dl+e.slice(2));let u=jl(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const d=new P(s);return l&&(l.node=d),d}u=s instanceof Map?o[je]:Symbol.iterator in Object(s)?o[pt]:o[je]}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 P(s);return e?f.tag=e:u.default||(f.tag=u.tag),l&&(l.node=f),f}c(qt,"createNode");function Rn(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 qt(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(Rn,"collectionFromPath");const Kt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class lo extends er{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=>Y(n)||V(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Kt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(z(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Rn(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(z(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:z(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!V(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 z(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(z(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Rn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Fl=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ie(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ie,"indentComment");const Xe=c((s,e,t)=>s.endsWith(`
5
- `)?Ie(t,e):t.includes(`
2
+ var xc=Object.defineProperty;var c=(s,e)=>xc(s,"name",{value:e,configurable:!0});import{jsx as m,jsxs as _,Fragment as ut}from"react/jsx-runtime";import*as K from"node:path";import{join as Ks,resolve as Pc,dirname as Rc}from"node:path";import{useInput as Xe,Box as S,Text as v,Newline as Mc,render as Ut}from"ink";import Lc from"minimist";import{SWRConfig as Dc}from"swr";import Ae,{createContext as Bs,useState as J,useEffect as Fe,useContext as Us,useMemo as jc,useRef as Ws,useId as Fc,useLayoutEffect as _n}from"react";import Ei from"swr/immutable";import _i from"os";import U from"path";import qc from"conf";import{MembraneConfigLoader as Kc,MembraneAxiosInstance as Bc,MembraneClient as Ii,WorkspaceElementType as x,WorkspaceElementSpecs as qe,WorkspaceSyncEventType as Uc,ConnectorFileUpdateType as Js,InteractiveMcpToolName as Wc,InteractiveMcpToolStatus as Jc,setValueAtLocator as Hs,extractMembraneErrorData as Te,getDataCollectionCreateFields as Vs,excludeWriteOnlyFieldsFromSchema as Ai,valueToSchema as In,getRequiredFieldsFromSchema as Hc,getValueAtLocator as Vc,walkSchema as Oi,makeDataLocationPath as $i,getDataCollectionUpdateFields as Gs}from"@membranehq/sdk";import zs from"jsonwebtoken";import*as L from"node:fs";import{mkdirSync as Gc,writeFileSync as zc,readFileSync as Yc}from"node:fs";import{EventEmitter as Xc}from"events";import{AsyncLocalStorage as Qc}from"async_hooks";import Zc from"lodash/isEqual.js";import Wt from"js-yaml";import*as el from"node:crypto";import{createHash as tl}from"node:crypto";import nl from"chokidar";import{EventSource as sl}from"eventsource";import F from"fs";import rl from"archiver";import il from"form-data";import ol from"unzipper";import*as al from"node:os";import{exec as cl}from"node:child_process";import{Spinner as ll,TextInput as ul,Select as dl}from"@inkjs/ui";import An from"ink-spinner";import Ni from"ink-text-input";import{fileURLToPath as fl}from"node:url";import T from"chalk";import{Command as hl}from"commander";import Ys from"lodash/camelCase.js";import Xs from"lodash/upperFirst.js";import pl from"code-block-writer";import ml from"lodash/uniqBy.js";import"node:events";import{FastMCP as gl}from"fastmcp";import{z as W}from"zod";import Qs from"axios";import Zs from"lodash/merge.js";import{faker as Jt}from"@faker-js/faker";import yl from"lodash/template.js";import wl from"lodash/templateSettings.js";const bl="membrane",Sl="membrane.config.yml",er="https://api.integration.app";function tr(){const s=process.cwd(),e=K.join(s,bl),t=K.join(s,Sl),n=e,r=K.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(tr,"getPaths");function xi(){return tr().membraneDirPath}c(xi,"getBasePath");const Cl={pat:{type:"string"},workspace:{type:"object"}},Pi=new qc({schema:Cl,configName:"config",cwd:U.join(_i.homedir(),".membrane")}),vl=c(s=>{Pi.set("pat",s)},"setPat"),Ri=c(()=>Pi.get("pat"),"getPat");class Mi{static{c(this,"AccountApiClient")}constructor(e=er){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=Ri();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 kl=c(s=>{const e=new Mi(er);return t=>e.get(t)},"createAccountApiFetcher");class Ft{static{c(this,"ConfigLoader")}static instance=null;sdkLoader;constructor(){this.sdkLoader=new Kc}static getInstance(){return Ft.instance||(Ft.instance=new Ft),Ft.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 Qe=Ft.getInstance();function On(s){return Qe.loadConfig(s)}c(On,"readProjectConfig");const Q={LogAdded:"logAdded",StateChanged:"stateChanged",StatsChanged:"statsChanged",ConflictsChanged:"conflictsChanged",McpStatusChanged:"mcpStatusChanged",McpServersChanged:"mcpServersChanged",ConfigChanged:"configChanged"};class nr extends Xc{static{c(this,"TypedEventEmitter")}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}off(e,t){return super.off(e,t)}once(e,t){return super.once(e,t)}}class Tl extends nr{static{c(this,"WorkspaceNotifications")}constructor(e){super(),this.config=e}clientId;heartbeatInterval;isCleaningUp=!1;async connectToRemote(){await this.registerWithRemoteServer(),await this.startHeartbeatLoop()}async setState(e){this.emit(Q.StateChanged,{state:e}),await this.emitRemote({status:e})}setConflicts(e){this.emit(Q.ConflictsChanged,{conflicts:e})}setConfig(e){this.emit(Q.ConfigChanged,{config:e})}setStats(e){this.emit(Q.StatsChanged,{stats:e})}addLog(e){this.emit(Q.LogAdded,{log:e})}setMcpStatus(e){this.emit(Q.McpStatusChanged,{status:e})}async setMcpServers(e){this.emit(Q.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 B.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 B.withClient(t=>t.post("/local-clients",{hostname:_i.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 B.withClient(e=>e.post(`/local-clients/${this.clientId}/keep-alive`,{}))})}async emitRemote(e){this.clientId&&await this.withErrorHandling(async()=>{await B.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 Oe=new Tl({heartbeatIntervalMs:15e3}),El="membrane",_l=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**","**/.logs/**"];function dt(s){return K.join(s,El)}c(dt,"getMembraneDir");const Li=Ks(dt(process.cwd()),".logs");class Il{static{c(this,"WorkspaceLogger")}_logs;workspaceNotifications;verboseMode=!1;constructor(){this._logs=[],this.workspaceNotifications=Oe}setVerboseMode(e){this.verboseMode=e}getVerboseMode(){return this.verboseMode}get logs(){return[...this._logs]}get latestLogs(){return this._logs.slice(this._logs.length-5)}log(e,t="info"){const n={timestamp:new Date().toISOString(),message:e,type:t};this._logs.push(n),this._logs=this._logs.slice(0,1e3),(t!=="debug"||this.verboseMode)&&this.workspaceNotifications.addLog(n)}info(e){this.log(e,"info")}success(e){this.log(e,"success")}warning(e){this.log(e,"warning")}error(e){this.log(e,"error")}debug(e){this.log(e,"debug")}clear(){this._logs=[]}saveLogsToFile(e){if(this._logs.length===0)return null;try{const t=new Date().toISOString().replace(/[:.]/g,"_"),n=e?`-${e}`:"",r=`${t}${n}.txt`;Gc(Li,{recursive:!0});const i=Ks(Li,r),o=this._logs.map(a=>`[${a.timestamp}] ${a.type?.toUpperCase()||"INFO"}: ${a.message}`).join(`
3
+ `);return zc(i,o,"utf-8"),i}catch(t){return console.error("Failed to save logs:",t),null}}}const b=new Il,Di=new Qc;class ji{static{c(this,"RequestLogger")}constructor(e=Bc){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=Di.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 Di.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 Al{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 ji,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():ji.withSkipErrorLog(r)}async generateAccessToken(e,t){return zs.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=On(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 Ii({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 B=new Al;async function Fi(s){const e=await B.withClient(t=>t.get("org-workspace-id"),!0,s);if(!e)throw new Error("Failed to get workspace ID");return e.id}c(Fi,"getWorkspaceId");var q={},$n={},qi;function Ki(){if(qi)return $n;qi=1,Object.defineProperty($n,"__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"),$n.default=s,$n}c(Ki,"requireJsCamelcase");var Nn={},Bi;function Ui(){if(Bi)return Nn;Bi=1,Object.defineProperty(Nn,"__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"),Nn.default=s,Nn}c(Ui,"requireJsSnakecase");var xn={},Wi;function Ji(){if(Wi)return xn;Wi=1,Object.defineProperty(xn,"__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"),xn.default=s,xn}c(Ji,"requireJsPascalcase");var Pn={},Hi;function Ol(){if(Hi)return Pn;Hi=1,Object.defineProperty(Pn,"__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"),Pn.default=s,Pn}c(Ol,"requireJsDotcase");var Rn={},Vi;function $l(){if(Vi)return Rn;Vi=1,Object.defineProperty(Rn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return c(s,"toPathCase"),Rn.default=s,Rn}c($l,"requireJsPathcase");var Mn={},Gi;function Nl(){if(Gi)return Mn;Gi=1,Object.defineProperty(Mn,"__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"),Mn.default=s,Mn}c(Nl,"requireJsTextcase");var Ln={},zi;function xl(){if(zi)return Ln;zi=1,Object.defineProperty(Ln,"__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"),Ln.default=s,Ln}c(xl,"requireJsSentencecase");var Dn={},Yi;function Pl(){if(Yi)return Dn;Yi=1,Object.defineProperty(Dn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,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"),Dn.default=s,Dn}c(Pl,"requireJsHeadercase");var jn={},Xi;function Qi(){if(Xi)return jn;Xi=1,Object.defineProperty(jn,"__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"),jn.default=s,jn}c(Qi,"requireJsKebabcase");var ft={},sr={},Zi;function ht(){return Zi||(Zi=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})}}(sr)),sr}c(ht,"requireUtils");var eo;function Rl(){if(eo)return ft;eo=1;var s=ft&&ft.__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,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(ft,"__esModule",{value:!0});var e=ht();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 d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"lowerKeys"),ft.default=t,ft}c(Rl,"requireLowercaseKeysObject");var pt={},to;function Ml(){if(to)return pt;to=1;var s=pt&&pt.__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,d=l.length;u<d;u++,a++)o[a]=l[u];return o};Object.defineProperty(pt,"__esModule",{value:!0});var e=ht();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 d=u;if(e.isValidObject(u))e.belongToTypes(d,r.keepTypesOnRecursion)||(d=t(u,r));else if(e.isArrayObject(u)){var f=t({key:u},r);d=f.key}return d}))),i[l]=a}),i}return c(t,"upperKeys"),pt.default=t,pt}c(Ml,"requireUppercaseKeysObject");var mt={},no;function Ll(){if(no)return mt;no=1;var s=mt&&mt.__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],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(mt,"__esModule",{value:!0});var e=ht(),t=Ki();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(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"camelKeys"),mt.default=n,mt}c(Ll,"requireCamelcaseKeysObject");var gt={},so;function Dl(){if(so)return gt;so=1;var s=gt&&gt.__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],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(gt,"__esModule",{value:!0});var e=ht(),t=Ui();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(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"snakeKeys"),gt.default=n,gt}c(Dl,"requireSnakecaseKeysObject");var yt={},ro;function jl(){if(ro)return yt;ro=1;var s=yt&&yt.__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],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(yt,"__esModule",{value:!0});var e=ht(),t=Ji();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(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"pascalKeys"),yt.default=n,yt}c(jl,"requirePascalcaseKeysObject");var wt={},io;function Fl(){if(io)return wt;io=1;var s=wt&&wt.__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],d=0,f=u.length;d<f;d++,l++)a[l]=u[d];return a};Object.defineProperty(wt,"__esModule",{value:!0});var e=ht(),t=Qi();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(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,i.keepTypesOnRecursion)||(f=n(d,i));else if(e.isArrayObject(d)){var h=n({key:d},i);f=h.key}return f}))),o[u]=l}),o}return c(n,"kebabKeys"),wt.default=n,wt}c(Fl,"requireKebabcaseKeysObject");var oo;function ql(){if(oo)return q;oo=1,Object.defineProperty(q,"__esModule",{value:!0}),q.kebabKeys=q.pascalKeys=q.snakeKeys=q.camelKeys=q.upperKeys=q.lowerKeys=q.toLowerCase=q.toUpperCase=q.toKebabCase=q.toHeaderCase=q.toSentenceCase=q.toTextCase=q.toPathCase=q.toDotCase=q.toPascalCase=q.toSnakeCase=q.toCamelCase=void 0;var s=Ki();q.toCamelCase=s.default;var e=Ui();q.toSnakeCase=e.default;var t=Ji();q.toPascalCase=t.default;var n=Ol();q.toDotCase=n.default;var r=$l();q.toPathCase=r.default;var i=Nl();q.toTextCase=i.default;var o=xl();q.toSentenceCase=o.default;var a=Pl();q.toHeaderCase=a.default;var l=Qi();q.toKebabCase=l.default;var u=Rl();q.lowerKeys=u.default;var d=Ml();q.upperKeys=d.default;var f=Ll();q.camelKeys=f.default;var h=Dl();q.snakeKeys=h.default;var g=jl();q.pascalKeys=g.default;var y=Fl();q.kebabKeys=y.default;var p=c(function(E){return String(E||"").toLowerCase()},"toLowerCase");q.toLowerCase=p;var w=c(function(E){return String(E||"").toUpperCase()},"toUpperCase");q.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:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:g.default,kebabKeys:y.default};return q.default=k,q}c(ql,"requireLib");var rr,ao;function Kl(){return ao||(ao=1,rr=ql()),rr}c(Kl,"requireJsConvertCase");var Bl=Kl();const $e={UPDATE:"update",DELETE:"delete",CREATE:"create"},ae={INCOMING:"incoming",OUTGOING:"outgoing"},ce={[x.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")},[x.Connector]:{element:"connector",elements:"connectors",exportable:!1},[x.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[x.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[x.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[x.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[x.DataSource]:{element:"dataSource",elements:"dataSources",parentKey:"universalDataSourceId",integrationSpecific:!0},[x.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,parentKey:"universalFieldMappingId",exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[x.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0,parentKey:"universalFlowId"},[x.Package]:{element:"package",elements:"packages",integrationSpecific:!0}};function Ul(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(Ul,"baseExportCleanup");const Wl=["id","workspaceId","integrationId","createdAt","updatedAt","revision","archivedAt","baseUri","state","appliedToIntegrations","dependencies"],co=[x.Action,x.FieldMapping,x.Flow,x.DataSource,x.Package];class X{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||X.extractIntegrationKey(r)}get id(){return X.makeId(this.type,this.key,this.integrationKey)}get dirPath(){const e=qe[this.type].apiPath;if(this.integrationKey){const t=qe[x.Integration].apiPath;return K.join(t,this.integrationKey,e,this.key)}return K.join(e,this.key)}get path(){return K.join(this.dirPath,"spec.yaml")}get relativePath(){return K.relative(dt(process.cwd()),this.path)}get absolutePath(){return K.resolve(K.join(dt(process.cwd()),this.path))}isEqual(e){if(this.id!==e.id)return!1;const t=this.clean(),n=e.clean();return Zc(t,n)}hasParent(){const e=this.getParentKey();return!!e&&!!this.data?.[e]}clean(){const e={...this.data};return Wl.forEach(t=>{delete e[t]}),Object.keys(e).forEach(t=>{t.match(/universal.*Revision/)&&delete e[t]}),e}getParentKey(){let e="parentId";return ce?.[this.type]?.parentKey&&(e=ce?.[this.type]?.parentKey),e}static new(e,t,n,r){return new X(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 X(e,t.key,n,t)}static fromPathAndData(e,t){const n=X.parsePath(e);if(!t)return;const r=t?.key||n?.key;return n?X.new(n.type,r,n.integrationKey,t):void 0}static fromElement(e){return new X(e.type,e.key,e.integrationKey,{...e.data})}static idFromPath(e){const t=X.parsePath(e);if(t)return X.makeId(t.type,t.key,t.integrationKey)}static makeId(e,t,n){return e===x.Integration?`${e}:${t}`:X.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(qe).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,d=this.getElementTypeFromPath(l);if(d)return{type:d,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:d}=a.groups,f=this.getElementTypeFromPath(u);if(f)return{type:f,key:d,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(x).find(t=>qe[t].apiPath===e)}static getRelativePath(e){return K.relative(dt(process.cwd()),e)}static isIntegrationSpecific(e){return co.includes(e)}static canBeIntegrationSpecific(e){return co.includes(e)}}class lo{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=[x.Integration,x.Connector],r=Object.keys(ce),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 ir(s,e=!0){if(L.existsSync(s))try{const t=L.readFileSync(s,"utf8");return Wt.load(t)||void 0}catch(t){if(!e)return;if(t instanceof Error){const n=K.relative(process.cwd(),s);throw new Error(`Failed to parse YAML file "${n}": ${t.message}`)}throw t}}c(ir,"readYaml");function Jl(s,e,t){try{const n=Wt.dump(e,t);L.writeFileSync(s,n,"utf8")}catch(n){if(n instanceof Error){const r=K.relative(process.cwd(),s);throw new Error(`Failed to write YAML file "${r}": ${n.message}`)}throw n}}c(Jl,"writeYaml");class Hl extends lo{static{c(this,"LocalWorkspaceElementsRepository")}basePath;constructor(e){super(e),this.basePath=dt(process.cwd())}async getElementsByType(e,t){const n=[],r=K.join(this.basePath,qe[e].apiPath),i=await this.readElementsInDir(r);n.push(...i);for(const o of t){const a=K.join(this.basePath,qe[x.Integration].apiPath,o.key,qe[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=K.join(this.basePath,t.dirPath),r=K.join(this.basePath,t.path);return L.existsSync(n)||L.mkdirSync(n,{recursive:!0}),Jl(r,e.data),b.debug(`[local] Written ${t.relativePath}`),t}async deleteElement(e){const t=K.join(this.basePath,e.path),n=K.join(this.basePath,e.dirPath);L.existsSync(t)&&L.rmSync(t,{force:!0}),this.pruneEmptyDir(n),b.debug(`[local] Deleted ${e.relativePath}`)}async getIntegrations(){const e=K.join(this.basePath,qe[x.Integration].apiPath);return this.readElementsInDir(e)}async readElement(e){const t=ir(e);if(t)return X.fromPathAndData(e,t)}async readElementsInDir(e){const t=[];if(!L.existsSync(e))return t;const n=L.readdirSync(e);if(n.length===0)return t;const r=n.map(async o=>{const a=K.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||!L.existsSync(e)||L.readdirSync(e).length>0)return;L.rmdirSync(e),this.pruneEmptyDir(K.dirname(e))}catch(t){console.warn(`Failed to prune empty directory ${e}:`,t)}}}class Vl extends lo{static{c(this,"RemoteWorkspaceElementsRepository")}async getElementsByType(e,t){const n=X.canBeIntegrationSpecific(e),r=await this.findAll(e,n?{layer:"universal"}:{});if(!X.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 B.withClient(n=>n[ce[e.type].element](e.data.id).get());return X.fromData(e.type,t)}async createElement(e,t){const n=e.clean();this.transformElementForCreate(e,n,t);const r=await B.withClient(o=>o[ce[e.type].elements].create(n)),i=X.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 B.withClient(a=>a[ce[e.type].element](t.data.id).restore());const r=e.clean();this.transformElementForUpdate(e,r,n);const i=await B.withClient(a=>a[ce[e.type].element](t.data.id).put(r)),o=X.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 B.withClient(t=>t[ce[e.type].element](e.data.id).archive()),b.debug(`[remote] Deleted ${e.id}`)}async getIntegrations(){const e=await B.withClient(n=>n.integrations.findAll());if(!e)return[];const t=e.map(n=>X.fromData(x.Integration,n));return t.length>0&&b.debug(`[remote] Fetched ${t.length} integrations`),t}async getByInternalId(e,t){let n;if(n=await B.withClient(r=>r[ce[t].element](e).get(),!1),!!n)return X.fromData(t,n)}transformElementForCreate(e,t,n){if(e.integrationKey){const r=n.elements.find(i=>i.type===x.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===x.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===x.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===x.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!==x.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 B.withClient(i=>i[ce[e].elements].findAll(t));return r?r.filter(i=>i.key).map(i=>(n&&!i.integrationKey&&(i.integrationKey=n),X.fromData(e,i))):[]}}const or=Symbol.for("yaml.alias"),ar=Symbol.for("yaml.document"),Ke=Symbol.for("yaml.map"),uo=Symbol.for("yaml.pair"),Ee=Symbol.for("yaml.scalar"),bt=Symbol.for("yaml.seq"),me=Symbol.for("yaml.node.type"),Be=c(s=>!!s&&typeof s=="object"&&s[me]===or,"isAlias"),Ze=c(s=>!!s&&typeof s=="object"&&s[me]===ar,"isDocument"),St=c(s=>!!s&&typeof s=="object"&&s[me]===Ke,"isMap"),V=c(s=>!!s&&typeof s=="object"&&s[me]===uo,"isPair"),H=c(s=>!!s&&typeof s=="object"&&s[me]===Ee,"isScalar$1"),Ct=c(s=>!!s&&typeof s=="object"&&s[me]===bt,"isSeq");function z(s){if(s&&typeof s=="object")switch(s[me]){case Ke:case bt:return!0}return!1}c(z,"isCollection$1");function Y(s){if(s&&typeof s=="object")switch(s[me]){case or:case Ke:case Ee:case bt:return!0}return!1}c(Y,"isNode");const fo=c(s=>(H(s)||z(s))&&!!s.anchor,"hasAnchor"),le=Symbol("break visit"),ho=Symbol("skip children"),_e=Symbol("remove node");function et(s,e){const t=po(e);Ze(s)?vt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):vt(null,s,t,Object.freeze([]))}c(et,"visit$1"),et.BREAK=le,et.SKIP=ho,et.REMOVE=_e;function vt(s,e,t,n){const r=mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),vt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=vt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=vt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=vt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(vt,"visit_");async function Fn(s,e){const t=po(e);Ze(s)?await kt(null,s.contents,t,Object.freeze([s]))===_e&&(s.contents=null):await kt(null,s,t,Object.freeze([]))}c(Fn,"visitAsync"),Fn.BREAK=le,Fn.SKIP=ho,Fn.REMOVE=_e;async function kt(s,e,t,n){const r=await mo(s,e,t,n);if(Y(r)||V(r))return go(s,n,r),kt(s,r,t,n);if(typeof r!="symbol"){if(z(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const o=await kt(i,e.items[i],t,n);if(typeof o=="number")i=o-1;else{if(o===le)return le;o===_e&&(e.items.splice(i,1),i-=1)}}}else if(V(e)){n=Object.freeze(n.concat(e));const i=await kt("key",e.key,t,n);if(i===le)return le;i===_e&&(e.key=null);const o=await kt("value",e.value,t,n);if(o===le)return le;o===_e&&(e.value=null)}}return r}c(kt,"visitAsync_");function po(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(po,"initVisitor");function mo(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(St(e))return t.Map?.(s,e,n);if(Ct(e))return t.Seq?.(s,e,n);if(V(e))return t.Pair?.(s,e,n);if(H(e))return t.Scalar?.(s,e,n);if(Be(e))return t.Alias?.(s,e,n)}c(mo,"callVisitor");function go(s,e,t){const n=e[e.length-1];if(z(n))n.items[s]=t;else if(V(n))s==="key"?n.key=t:n.value=t;else if(Ze(n))n.contents=t;else{const r=Be(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(go,"replaceNode");const Gl={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},zl=c(s=>s.replace(/[!,[\]{}]/g,e=>Gl[e]),"escapeTagName");class oe{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},oe.defaultYaml,e),this.tags=Object.assign({},oe.defaultTags,t)}clone(){const e=new oe(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new oe(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:oe.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},oe.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:oe.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},oe.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+zl(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&&Y(e.contents)){const i={};et(e.contents,(o,a)=>{Y(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(`
4
+ `)}}oe.defaultYaml={explicit:!1,version:"1.2"},oe.defaultTags={"!!":"tag:yaml.org,2002:"};function yo(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(yo,"anchorIsValid");function wo(s){const e=new Set;return et(s,{Value(t,n){n.anchor&&e.add(n.anchor)}}),e}c(wo,"anchorNames");function bo(s,e){for(let t=1;;++t){const n=`${s}${t}`;if(!e.has(n))return n}}c(bo,"findNewAnchor");function Yl(s,e){const t=[],n=new Map;let r=null;return{onAnchor:c(i=>{t.push(i),r??(r=wo(s));const o=bo(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&&(H(o.node)||z(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(Yl,"createNodeAnchors");function Tt(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=Tt(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=Tt(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=Tt(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=Tt(s,n,r,i);o===void 0?delete n[r]:o!==i&&(n[r]=o)}return s.call(e,t,n)}c(Tt,"applyReviver");function ge(s,e,t){if(Array.isArray(s))return s.map((n,r)=>ge(n,String(r),t));if(s&&typeof s.toJSON=="function"){if(!t||!fo(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(ge,"toJS");class cr{static{c(this,"NodeBase")}constructor(e){Object.defineProperty(this,me,{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(!Ze(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=ge(this,"",o);if(typeof r=="function")for(const{count:l,res:u}of o.anchors.values())r(u,l);return typeof i=="function"?Tt(i,{"":a},"",a):a}}class qn extends cr{static{c(this,"Alias")}constructor(e){super(or),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=[],et(e,{Node:c((i,o)=>{(Be(o)||fo(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||(ge(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=Kn(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(yo(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 Kn(s,e,t){if(Be(e)){const n=e.resolve(s),r=t&&n&&t.get(n);return r?r.count*r.aliasCount:0}else if(z(e)){let n=0;for(const r of e.items){const i=Kn(s,r,t);i>n&&(n=i)}return n}else if(V(e)){const n=Kn(s,e.key,t),r=Kn(s,e.value,t);return Math.max(n,r)}return 1}c(Kn,"getAliasCount");const So=c(s=>!s||typeof s!="function"&&typeof s!="object","isScalarValue");class R extends cr{static{c(this,"Scalar")}constructor(e){super(Ee),this.value=e}toJSON(e,t){return t?.keep?this.value:ge(this.value,e,t)}toString(){return String(this.value)}}R.BLOCK_FOLDED="BLOCK_FOLDED",R.BLOCK_LITERAL="BLOCK_LITERAL",R.PLAIN="PLAIN",R.QUOTE_DOUBLE="QUOTE_DOUBLE",R.QUOTE_SINGLE="QUOTE_SINGLE";const Xl="tag:yaml.org,2002:";function Ql(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(Ql,"findTagObject");function Ht(s,e,t){if(Ze(s)&&(s=s.contents),Y(s))return s;if(V(s)){const f=t.schema[Ke].createNode?.(t.schema,null,t);return f.items.push(s),f}(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 qn(l.anchor);l={anchor:null,node:null},a.set(s,l)}e?.startsWith("!!")&&(e=Xl+e.slice(2));let u=Ql(s,e,o.tags);if(!u){if(s&&typeof s.toJSON=="function"&&(s=s.toJSON()),!s||typeof s!="object"){const f=new R(s);return l&&(l.node=f),f}u=s instanceof Map?o[Ke]:Symbol.iterator in Object(s)?o[bt]:o[Ke]}i&&(i(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,s,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,s,t):new R(s);return e?d.tag=e:u.default||(d.tag=u.tag),l&&(l.node=d),d}c(Ht,"createNode");function Bn(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 Ht(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(Bn,"collectionFromPath");const Vt=c(s=>s==null||typeof s=="object"&&!!s[Symbol.iterator]().next().done,"isEmptyPath");class Co extends cr{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=>Y(n)||V(n)?n.clone(e):n),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Vt(e))this.add(t);else{const[n,...r]=e,i=this.get(n,!0);if(z(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Bn(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(z(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&&H(i)?i.value:i:z(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!V(t))return!1;const n=t.value;return n==null||e&&H(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 z(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(z(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(n,Bn(this.schema,r,t));else throw new Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}const Zl=c(s=>s.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function Ne(s,e){return/^\n+$/.test(s)?s.substring(1):e?s.replace(/^(?! *$)/gm,e):s}c(Ne,"indentComment");const tt=c((s,e,t)=>s.endsWith(`
5
+ `)?Ne(t,e):t.includes(`
6
6
  `)?`
7
- `+Ie(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),uo="flow",tr="block",Ln="quoted";function Dn(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 p,m,y=!1,h=-1,w=-1,k=-1;t===tr&&(h=fo(s,h,e.length),h!==-1&&(d=h+l));for(let I;I=s[h+=1];){if(t===Ln&&I==="\\"){switch(w=h,s[h+1]){case"x":h+=3;break;case"u":h+=5;break;case"U":h+=9;break;default:h+=1}k=h}if(I===`
8
- `)t===tr&&(h=fo(s,h,e.length)),d=h+e.length+l,p=void 0;else{if(I===" "&&m&&m!==" "&&m!==`
9
- `&&m!==" "){const E=s[h+1];E&&E!==" "&&E!==`
10
- `&&E!==" "&&(p=h)}if(h>=d)if(p)u.push(p),d=p+l,p=void 0;else if(t===Ln){for(;m===" "||m===" ";)m=I,I=s[h+=1],y=!0;const E=h>k+1?h-2:w-1;if(f[E])return s;u.push(E),f[E]=!0,d=E+l,p=void 0}else y=!0}m=I}if(y&&a&&a(),u.length===0)return s;o&&o();let _=s.slice(0,u[0]);for(let I=0;I<u.length;++I){const E=u[I],$=u[I+1]||s.length;E===0?_=`
11
- ${e}${s.slice(0,$)}`:(t===Ln&&f[E]&&(_+=`${s[E]}\\`),_+=`
12
- ${e}${s.slice(E+1,$)}`)}return _}c(Dn,"foldFlowLines");function fo(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!==`
13
- `);n=e,r=e+1,i=s[r]}return n}c(fo,"consumeMoreIndentedLines");const jn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Fn=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function ql(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]===`
14
- `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(ql,"lineLengthOverLimit");function Bt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Fn(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)+`
7
+ `+Ne(t,e):(s.endsWith(" ")?"":" ")+t,"lineComment"),vo="flow",lr="block",Un="quoted";function Wn(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=[],d={};let f=r-e.length;typeof n=="number"&&(n>r-Math.max(2,i)?u.push(0):f=r-n);let h,g,y=!1,p=-1,w=-1,k=-1;t===lr&&(p=ko(s,p,e.length),p!==-1&&(f=p+l));for(let O;O=s[p+=1];){if(t===Un&&O==="\\"){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(O===`
8
+ `)t===lr&&(p=ko(s,p,e.length)),f=p+e.length+l,h=void 0;else{if(O===" "&&g&&g!==" "&&g!==`
9
+ `&&g!==" "){const I=s[p+1];I&&I!==" "&&I!==`
10
+ `&&I!==" "&&(h=p)}if(p>=f)if(h)u.push(h),f=h+l,h=void 0;else if(t===Un){for(;g===" "||g===" ";)g=O,O=s[p+=1],y=!0;const I=p>k+1?p-2:w-1;if(d[I])return s;u.push(I),d[I]=!0,f=I+l,h=void 0}else y=!0}g=O}if(y&&a&&a(),u.length===0)return s;o&&o();let E=s.slice(0,u[0]);for(let O=0;O<u.length;++O){const I=u[O],$=u[O+1]||s.length;I===0?E=`
11
+ ${e}${s.slice(0,$)}`:(t===Un&&d[I]&&(E+=`${s[I]}\\`),E+=`
12
+ ${e}${s.slice(I+1,$)}`)}return E}c(Wn,"foldFlowLines");function ko(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!==`
13
+ `);n=e,r=e+1,i=s[r]}return n}c(ko,"consumeMoreIndentedLines");const Jn=c((s,e)=>({indentAtStart:e?s.indent.length:s.indentAtStart,lineWidth:s.options.lineWidth,minContentWidth:s.options.minContentWidth}),"getFoldOptions"),Hn=c(s=>/^(%|---|\.\.\.)/m.test(s),"containsDocumentMarker");function eu(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]===`
14
+ `){if(i-o>n)return!0;if(o=i+1,r-o<=n)return!1}return!0}c(eu,"lineLengthOverLimit");function Gt(s,e){const t=JSON.stringify(s);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:n}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(Hn(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 d=t.substr(l+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(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)+`
15
15
 
16
16
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
17
- `,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:Dn(o,i,Ln,jn(e,!1))}c(Bt,"doubleQuotedString");function nr(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
18
- `)||/[ \t]\n|\n[ \t]/.test(s))return Bt(s,e);const t=e.indent||(Fn(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
19
- ${t}`)+"'";return e.implicitKey?n:Dn(n,t,uo,jn(e,!1))}c(nr,"singleQuotedString");function St(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Bt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=nr:i&&!r?n=Bt:n=t?nr:Bt}return n(s,e)}c(St,"quotedString");let sr;try{sr=new RegExp(`(^|(?<!
17
+ `,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:Wn(o,i,Un,Jn(e,!1))}c(Gt,"doubleQuotedString");function ur(s,e){if(e.options.singleQuote===!1||e.implicitKey&&s.includes(`
18
+ `)||/[ \t]\n|\n[ \t]/.test(s))return Gt(s,e);const t=e.indent||(Hn(s)?" ":""),n="'"+s.replace(/'/g,"''").replace(/\n+/g,`$&
19
+ ${t}`)+"'";return e.implicitKey?n:Wn(n,t,vo,Jn(e,!1))}c(ur,"singleQuotedString");function Et(s,e){const{singleQuote:t}=e.options;let n;if(t===!1)n=Gt;else{const r=s.includes('"'),i=s.includes("'");r&&!i?n=ur:i&&!r?n=Gt:n=t?ur:Gt}return n(s,e)}c(Et,"quotedString");let dr;try{dr=new RegExp(`(^|(?<!
20
20
  ))
21
21
  +(?!
22
- |$)`,"g")}catch{sr=/\n+(?!\n|$)/g}function qn({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 St(t,n);const u=n.indent||(n.forceBlockIndent||Fn(t)?" ":""),f=o==="literal"?!0:o==="folded"||e===P.BLOCK_FOLDED?!1:e===P.BLOCK_LITERAL?!0:!ql(t,l,u.length);if(!t)return f?`|
22
+ |$)`,"g")}catch{dr=/\n+(?!\n|$)/g}function Vn({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 Et(t,n);const u=n.indent||(n.forceBlockIndent||Hn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===R.BLOCK_FOLDED?!1:e===R.BLOCK_LITERAL?!0:!eu(t,l,u.length);if(!t)return d?`|
23
23
  `:`>
24
- `;let d,p;for(p=t.length;p>0;--p){const $=t[p-1];if($!==`
25
- `&&$!==" "&&$!==" ")break}let m=t.substring(p);const y=m.indexOf(`
26
- `);y===-1?d="-":t===m||y!==m.length-1?(d="+",i&&i()):d="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
27
- `&&(m=m.slice(0,-1)),m=m.replace(sr,`$&${u}`));let h=!1,w,k=-1;for(w=0;w<t.length;++w){const $=t[w];if($===" ")h=!0;else if($===`
28
- `)k=w;else break}let _=t.substring(0,k<w?k+1:w);_&&(t=t.substring(_.length),_=_.replace(/\n+/g,`$&${u}`));let E=(h?u?"2":"1":"")+d;if(s&&(E+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!f){const $=t.replace(/\n+/g,`
29
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let N=!1;const D=jn(n,!0);o!=="folded"&&e!==P.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});const A=Dn(`${_}${$}${m}`,u,tr,D);if(!N)return`>${E}
30
- ${u}${A}`}return t=t.replace(/\n+/g,`$&${u}`),`|${E}
31
- ${u}${_}${t}${m}`}c(qn,"blockString");function Kl(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(`
32
- `)||f&&/[[\]{},]/.test(i))return St(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||f||!i.includes(`
33
- `)?St(i,e):qn(s,e,t,n);if(!a&&!f&&r!==P.PLAIN&&i.includes(`
34
- `))return qn(s,e,t,n);if(Fn(i)){if(l==="")return e.forceBlockIndent=!0,qn(s,e,t,n);if(a&&l===u)return St(i,e)}const d=i.replace(/\n+/g,`$&
35
- ${l}`);if(o){const p=c(h=>h.default&&h.tag!=="tag:yaml.org,2002:str"&&h.test?.test(d),"test"),{compat:m,tags:y}=e.doc.schema;if(y.some(p)||m?.some(p))return St(i,e)}return a?d:Dn(d,l,uo,jn(e,!1))}c(Kl,"plainString");function Ut(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!==P.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=P.QUOTE_DOUBLE);const l=c(f=>{switch(f){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return r||i?St(o.value,e):qn(o,e,t,n);case P.QUOTE_DOUBLE:return Bt(o.value,e);case P.QUOTE_SINGLE:return nr(o.value,e);case P.PLAIN:return Kl(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:f,defaultStringType:d}=e.options,p=r&&f||d;if(u=l(p),u===null)throw new Error(`Unsupported default string type ${p}`)}return u}c(Ut,"stringifyString");function ho(s,e){const t=Object.assign({blockQuote:!0,commentString:Fl,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(ho,"createStringifyContext");function Bl(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(Bl,"getTagObject");function Ul(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(J(s)||z(s))&&s.anchor;i&&io(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(Ul,"stringifyProps");function vt(s,e,t,n){if(V(s))return s.toString(e,t,n);if(Fe(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=Y(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=Bl(e.doc.schema.tags,i));const o=Ul(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)?Ut(i,e,t,n):i.toString(e,t,n);return o?J(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
- ${e.indent}${a}`:a}c(vt,"stringify$2");function Wl({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 p=Y(s)&&s.comment||null;if(d){if(p)throw new Error("With simple keys, key nodes cannot have comments");if(z(s)||!Y(s)&&typeof s=="object"){const D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let m=!d&&(!s||p&&e==null&&!t.inFlow||z(s)||(J(s)?s.type===P.BLOCK_FOLDED||s.type===P.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(d||!i),indent:a+l});let y=!1,h=!1,w=vt(s,t,()=>y=!0,()=>h=!0);if(!m&&!t.inFlow&&w.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return y&&n&&n(),w===""?"?":m?`? ${w}`:w}else if(i&&!d||e==null&&m)return w=`? ${w}`,p&&!y?w+=Xe(w,t.indent,u(p)):h&&r&&r(),w;y&&(p=null),m?(p&&(w+=Xe(w,t.indent,u(p))),w=`? ${w}
37
- ${a}:`):(w=`${w}:`,p&&(w+=Xe(w,t.indent,u(p))));let k,_,I;Y(e)?(k=!!e.spaceBefore,_=e.commentBefore,I=e.comment):(k=!1,_=null,I=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!p&&J(e)&&(t.indentAtStart=w.length+1),h=!1,!f&&l.length>=2&&!t.inFlow&&!m&&gt(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let E=!1;const $=vt(e,t,()=>E=!0,()=>h=!0);let N=" ";if(p||k||_){if(N=k?`
38
- `:"",_){const D=u(_);N+=`
39
- ${Ie(D,t.indent)}`}$===""&&!t.inFlow?N===`
24
+ `;let f,h;for(h=t.length;h>0;--h){const $=t[h-1];if($!==`
25
+ `&&$!==" "&&$!==" ")break}let g=t.substring(h);const y=g.indexOf(`
26
+ `);y===-1?f="-":t===g||y!==g.length-1?(f="+",i&&i()):f="",g&&(t=t.slice(0,-g.length),g[g.length-1]===`
27
+ `&&(g=g.slice(0,-1)),g=g.replace(dr,`$&${u}`));let p=!1,w,k=-1;for(w=0;w<t.length;++w){const $=t[w];if($===" ")p=!0;else if($===`
28
+ `)k=w;else break}let E=t.substring(0,k<w?k+1:w);E&&(t=t.substring(E.length),E=E.replace(/\n+/g,`$&${u}`));let I=(p?u?"2":"1":"")+f;if(s&&(I+=" "+a(s.replace(/ ?[\r\n]+/g," ")),r&&r()),!d){const $=t.replace(/\n+/g,`
29
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let N=!1;const D=Jn(n,!0);o!=="folded"&&e!==R.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});const A=Wn(`${E}${$}${g}`,u,lr,D);if(!N)return`>${I}
30
+ ${u}${A}`}return t=t.replace(/\n+/g,`$&${u}`),`|${I}
31
+ ${u}${E}${t}${g}`}c(Vn,"blockString");function tu(s,e,t,n){const{type:r,value:i}=s,{actualString:o,implicitKey:a,indent:l,indentStep:u,inFlow:d}=e;if(a&&i.includes(`
32
+ `)||d&&/[[\]{},]/.test(i))return Et(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
33
+ `)?Et(i,e):Vn(s,e,t,n);if(!a&&!d&&r!==R.PLAIN&&i.includes(`
34
+ `))return Vn(s,e,t,n);if(Hn(i)){if(l==="")return e.forceBlockIndent=!0,Vn(s,e,t,n);if(a&&l===u)return Et(i,e)}const f=i.replace(/\n+/g,`$&
35
+ ${l}`);if(o){const h=c(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:g,tags:y}=e.doc.schema;if(y.some(h)||g?.some(h))return Et(i,e)}return a?f:Wn(f,l,vo,Jn(e,!1))}c(tu,"plainString");function zt(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!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=R.QUOTE_DOUBLE);const l=c(d=>{switch(d){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return r||i?Et(o.value,e):Vn(o,e,t,n);case R.QUOTE_DOUBLE:return Gt(o.value,e);case R.QUOTE_SINGLE:return ur(o.value,e);case R.PLAIN:return tu(o,e,t,n);default:return null}},"_stringify");let u=l(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=r&&d||f;if(u=l(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}c(zt,"stringifyString");function To(s,e){const t=Object.assign({blockQuote:!0,commentString:Zl,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(To,"createStringifyContext");function nu(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(H(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(nu,"getTagObject");function su(s,e,{anchors:t,doc:n}){if(!n.directives)return"";const r=[],i=(H(s)||z(s))&&s.anchor;i&&yo(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(su,"stringifyProps");function _t(s,e,t,n){if(V(s))return s.toString(e,t,n);if(Be(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=Y(s)?s:e.doc.createNode(s,{onTagObj:c(l=>r=l,"onTagObj")});r??(r=nu(e.doc.schema.tags,i));const o=su(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):H(i)?zt(i,e,t,n):i.toString(e,t,n);return o?H(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
36
+ ${e.indent}${a}`:a}c(_t,"stringify$2");function ru({key:s,value:e},t,n,r){const{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=Y(s)&&s.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(z(s)||!Y(s)&&typeof s=="object"){const D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let g=!f&&(!s||h&&e==null&&!t.inFlow||z(s)||(H(s)?s.type===R.BLOCK_FOLDED||s.type===R.BLOCK_LITERAL:typeof s=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!g&&(f||!i),indent:a+l});let y=!1,p=!1,w=_t(s,t,()=>y=!0,()=>p=!0);if(!g&&!t.inFlow&&w.length>1024){if(f)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&&!f||e==null&&g)return w=`? ${w}`,h&&!y?w+=tt(w,t.indent,u(h)):p&&r&&r(),w;y&&(h=null),g?(h&&(w+=tt(w,t.indent,u(h))),w=`? ${w}
37
+ ${a}:`):(w=`${w}:`,h&&(w+=tt(w,t.indent,u(h))));let k,E,O;Y(e)?(k=!!e.spaceBefore,E=e.commentBefore,O=e.comment):(k=!1,E=null,O=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!g&&!h&&H(e)&&(t.indentAtStart=w.length+1),p=!1,!d&&l.length>=2&&!t.inFlow&&!g&&Ct(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let I=!1;const $=_t(e,t,()=>I=!0,()=>p=!0);let N=" ";if(h||k||E){if(N=k?`
38
+ `:"",E){const D=u(E);N+=`
39
+ ${Ne(D,t.indent)}`}$===""&&!t.inFlow?N===`
40
40
  `&&(N=`
41
41
 
42
42
  `):N+=`
43
- ${t.indent}`}else if(!m&&z(e)){const D=$[0],A=$.indexOf(`
44
- `),te=A!==-1,Le=t.inFlow??e.flow??e.items.length===0;if(te||!Le){let st=!1;if(te&&(D==="&"||D==="!")){let ne=$.indexOf(" ");D==="&"&&ne!==-1&&ne<A&&$[ne+1]==="!"&&(ne=$.indexOf(" ",ne+1)),(ne===-1||A<ne)&&(st=!0)}st||(N=`
43
+ ${t.indent}`}else if(!g&&z(e)){const D=$[0],A=$.indexOf(`
44
+ `),te=A!==-1,je=t.inFlow??e.flow??e.items.length===0;if(te||!je){let lt=!1;if(te&&(D==="&"||D==="!")){let ne=$.indexOf(" ");D==="&"&&ne!==-1&&ne<A&&$[ne+1]==="!"&&(ne=$.indexOf(" ",ne+1)),(ne===-1||A<ne)&&(lt=!0)}lt||(N=`
45
45
  ${t.indent}`)}}else($===""||$[0]===`
46
- `)&&(N="");return w+=N+$,t.inFlow?E&&n&&n():I&&!E?w+=Xe(w,t.indent,u(I)):h&&r&&r(),w}c(Wl,"stringifyPair");function po(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(po,"warn");const Kn="<<",$e={identify:c(s=>s===Kn||typeof s=="symbol"&&s.description===Kn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new P(Symbol(Kn)),{addToJSMap:mo}),"resolve"),stringify:c(()=>Kn,"stringify")},Jl=c((s,e)=>($e.identify(e)||J(e)&&(!e.type||e.type===P.PLAIN)&&$e.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===$e.tag&&t.default),"isMergeKey");function mo(s,e,t){if(t=s&&Fe(t)?t.resolve(s.doc):t,gt(t))for(const n of t.items)rr(s,e,n);else if(Array.isArray(t))for(const n of t)rr(s,e,n);else rr(s,e,t)}c(mo,"addMergeToJSMap");function rr(s,e,t){const n=s&&Fe(t)?t.resolve(s.doc):t;if(!mt(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(rr,"mergeValue");function go(s,e,{key:t,value:n}){if(Y(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(Jl(s,t))mo(s,e,n);else{const r=me(t,"",s);if(e instanceof Map)e.set(r,me(n,r,s));else if(e instanceof Set)e.add(r);else{const i=Hl(t,r,s),o=me(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c(go,"addPairToJSMap");function Hl(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Y(s)&&t?.doc){const n=ho(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)+'..."'),po(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(Hl,"stringifyKey");function ir(s,e,t){const n=qt(s,void 0,t),r=qt(e,void 0,t);return new se(n,r)}c(ir,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,pe,{value:Zi}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Y(t)&&(t=t.clone(e)),Y(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return go(t,n,this)}toString(e,t,n){return e?.doc?Wl(this,e,t,n):JSON.stringify(this)}}function yo(s,e,t){return(e.inFlow??s.flow?Gl:Vl)(s,e,t)}c(yo,"stringifyCollection");function Vl({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 p=[];for(let y=0;y<e.length;++y){const h=e[y];let w=null;if(Y(h))!d&&h.spaceBefore&&p.push(""),Bn(t,p,h.commentBefore,d),h.comment&&(w=h.comment);else if(V(h)){const _=Y(h.key)?h.key:null;_&&(!d&&_.spaceBefore&&p.push(""),Bn(t,p,_.commentBefore,d))}d=!1;let k=vt(h,f,()=>w=null,()=>d=!0);w&&(k+=Xe(k,i,u(w))),d&&w&&(d=!1),p.push(n+k)}let m;if(p.length===0)m=r.start+r.end;else{m=p[0];for(let y=1;y<p.length;++y){const h=p[y];m+=h?`
47
- ${l}${h}`:`
48
- `}}return s?(m+=`
49
- `+Ie(u(s),l),a&&a()):d&&o&&o(),m}c(Vl,"stringifyBlockCollection");function Gl({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 h=s[y];let w=null;if(Y(h))h.spaceBefore&&d.push(""),Bn(e,d,h.commentBefore,!1),h.comment&&(w=h.comment);else if(V(h)){const _=Y(h.key)?h.key:null;_&&(_.spaceBefore&&d.push(""),Bn(e,d,_.commentBefore,!1),_.comment&&(u=!0));const I=Y(h.value)?h.value:null;I?(I.comment&&(w=I.comment),I.commentBefore&&(u=!0)):h.value==null&&_?.comment&&(w=_.comment)}w&&(u=!0);let k=vt(h,l,()=>w=null);y<s.length-1&&(k+=","),w&&(k+=Xe(k,n,a(w))),!u&&(d.length>f||k.includes(`
50
- `))&&(u=!0),d.push(k),f=d.length}const{start:p,end:m}=t;if(d.length===0)return p+m;if(!u){const y=d.reduce((h,w)=>h+w.length+2,2);u=e.options.lineWidth>0&&y>e.options.lineWidth}if(u){let y=p;for(const h of d)y+=h?`
51
- ${i}${r}${h}`:`
46
+ `)&&(N="");return w+=N+$,t.inFlow?I&&n&&n():O&&!I?w+=tt(w,t.indent,u(O)):p&&r&&r(),w}c(ru,"stringifyPair");function Eo(s,e){(s==="debug"||s==="warn")&&console.warn(e)}c(Eo,"warn");const Gn="<<",xe={identify:c(s=>s===Gn||typeof s=="symbol"&&s.description===Gn,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:c(()=>Object.assign(new R(Symbol(Gn)),{addToJSMap:_o}),"resolve"),stringify:c(()=>Gn,"stringify")},iu=c((s,e)=>(xe.identify(e)||H(e)&&(!e.type||e.type===R.PLAIN)&&xe.identify(e.value))&&s?.doc.schema.tags.some(t=>t.tag===xe.tag&&t.default),"isMergeKey");function _o(s,e,t){if(t=s&&Be(t)?t.resolve(s.doc):t,Ct(t))for(const n of t.items)fr(s,e,n);else if(Array.isArray(t))for(const n of t)fr(s,e,n);else fr(s,e,t)}c(_o,"addMergeToJSMap");function fr(s,e,t){const n=s&&Be(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(fr,"mergeValue");function Io(s,e,{key:t,value:n}){if(Y(t)&&t.addToJSMap)t.addToJSMap(s,e,n);else if(iu(s,t))_o(s,e,n);else{const r=ge(t,"",s);if(e instanceof Map)e.set(r,ge(n,r,s));else if(e instanceof Set)e.add(r);else{const i=ou(t,r,s),o=ge(n,i,s);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}c(Io,"addPairToJSMap");function ou(s,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Y(s)&&t?.doc){const n=To(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)+'..."'),Eo(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(ou,"stringifyKey");function hr(s,e,t){const n=Ht(s,void 0,t),r=Ht(e,void 0,t);return new se(n,r)}c(hr,"createPair");class se{static{c(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,me,{value:uo}),this.key=e,this.value=t}clone(e){let{key:t,value:n}=this;return Y(t)&&(t=t.clone(e)),Y(n)&&(n=n.clone(e)),new se(t,n)}toJSON(e,t){const n=t?.mapAsMap?new Map:{};return Io(t,n,this)}toString(e,t,n){return e?.doc?ru(this,e,t,n):JSON.stringify(this)}}function Ao(s,e,t){return(e.inFlow??s.flow?cu:au)(s,e,t)}c(Ao,"stringifyCollection");function au({comment:s,items:e},t,{blockItemPrefix:n,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){const{indent:l,options:{commentString:u}}=t,d=Object.assign({},t,{indent:i,type:null});let f=!1;const h=[];for(let y=0;y<e.length;++y){const p=e[y];let w=null;if(Y(p))!f&&p.spaceBefore&&h.push(""),zn(t,h,p.commentBefore,f),p.comment&&(w=p.comment);else if(V(p)){const E=Y(p.key)?p.key:null;E&&(!f&&E.spaceBefore&&h.push(""),zn(t,h,E.commentBefore,f))}f=!1;let k=_t(p,d,()=>w=null,()=>f=!0);w&&(k+=tt(k,i,u(w))),f&&w&&(f=!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?`
47
+ ${l}${p}`:`
48
+ `}}return s?(g+=`
49
+ `+Ne(u(s),l),a&&a()):f&&o&&o(),g}c(au,"stringifyBlockCollection");function cu({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,d=0;const f=[];for(let y=0;y<s.length;++y){const p=s[y];let w=null;if(Y(p))p.spaceBefore&&f.push(""),zn(e,f,p.commentBefore,!1),p.comment&&(w=p.comment);else if(V(p)){const E=Y(p.key)?p.key:null;E&&(E.spaceBefore&&f.push(""),zn(e,f,E.commentBefore,!1),E.comment&&(u=!0));const O=Y(p.value)?p.value:null;O?(O.comment&&(w=O.comment),O.commentBefore&&(u=!0)):p.value==null&&E?.comment&&(w=E.comment)}w&&(u=!0);let k=_t(p,l,()=>w=null);y<s.length-1&&(k+=","),w&&(k+=tt(k,n,a(w))),!u&&(f.length>d||k.includes(`
50
+ `))&&(u=!0),f.push(k),d=f.length}const{start:h,end:g}=t;if(f.length===0)return h+g;if(!u){const y=f.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 f)y+=p?`
51
+ ${i}${r}${p}`:`
52
52
  `;return`${y}
53
- ${r}${m}`}else return`${p}${o}${d.join(" ")}${o}${m}`}c(Gl,"stringifyFlowCollection");function Bn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Ie(e(n),s);t.push(i.trimStart())}}c(Bn,"addCommentBefore");function Qe(s,e){const t=J(e)?e.value:e;for(const n of s)if(V(n)&&(n.key===e||n.key===t||J(n.key)&&n.key.value===t))return n}c(Qe,"findPair");class ue extends lo{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(je,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(ir(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;V(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new se(e,e?.value):n=new se(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`);J(r.value)&&co(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&&J(r)?r.value:r)??void 0}has(e){return!!Qe(this.items,e)}set(e,t){this.add(new se(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)go(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!V(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})),yo(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const Ct={collection:"map",default:!0,nodeClass:ue,tag:"tag:yaml.org,2002:map",resolve(s,e){return mt(s)||e("Expected a mapping for this tag"),s},createNode:c((s,e,t)=>ue.from(s,e,t),"createNode")};class qe extends lo{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(pt,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Un(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Un(e);if(typeof n!="number")return;const r=this.items[n];return!t&&J(r)?r.value:r}has(e){const t=Un(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Un(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];J(r)&&co(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(me(i,String(r++),t));return n}toString(e,t,n){return e?yo(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(qt(a,void 0,n))}}return i}}function Un(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(Un,"asItemIndex");const kt={collection:"seq",default:!0,nodeClass:qe,tag:"tag:yaml.org,2002:seq",resolve(s,e){return gt(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>qe.from(s,e,t),"createNode")},Wn={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),Ut(s,e,t,n)}},Jn={identify:c(s=>s==null,"identify"),createNode:c(()=>new P(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new P(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Jn.test.test(s)?s:e.options.nullStr,"stringify")},or={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 P(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&or.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 we({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(we,"stringifyNumber");const wo={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:we},bo={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():we(s)}},So={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 P(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:we},Hn=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),ar=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function vo(s,e,t){const{value:n}=s;return Hn(n)&&n>=0?t+n.toString(e):we(s)}c(vo,"intStringify$1");const Co={identify:c(s=>Hn(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>ar(s,2,8,t),"resolve"),stringify:c(s=>vo(s,8,"0o"),"stringify")},ko={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>ar(s,0,10,t),"resolve"),stringify:we},To={identify:c(s=>Hn(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)=>ar(s,2,16,t),"resolve"),stringify:c(s=>vo(s,16,"0x"),"stringify")},zl=[Ct,kt,Wn,Jn,or,Co,ko,To,wo,bo,So];function _o(s){return typeof s=="bigint"||Number.isInteger(s)}c(_o,"intIdentify$1");const Vn=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),Yl=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:Vn},{identify:c(s=>s==null,"identify"),createNode:c(()=>new P(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:Vn},{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:Vn},{identify:_o,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})=>_o(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:Vn}],Xl={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},Ql=[Ct,kt].concat(Yl,Xl),cr={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=P.BLOCK_LITERAL),e!==P.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,p=0;d<u;++d,p+=l)f[d]=a.substr(p,l);a=f.join(e===P.BLOCK_LITERAL?`
54
- `:" ")}return Ut({comment:s,type:e,value:a},n,r,i)}};function Eo(s,e){if(gt(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!V(n)){if(mt(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new P(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
53
+ ${r}${g}`}else return`${h}${o}${f.join(" ")}${o}${g}`}c(cu,"stringifyFlowCollection");function zn({indent:s,options:{commentString:e}},t,n,r){if(n&&r&&(n=n.replace(/^\n+/,"")),n){const i=Ne(e(n),s);t.push(i.trimStart())}}c(zn,"addCommentBefore");function nt(s,e){const t=H(e)?e.value:e;for(const n of s)if(V(n)&&(n.key===e||n.key===t||H(n.key)&&n.key.value===t))return n}c(nt,"findPair");class ue extends Co{static{c(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ke,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(hr(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;V(e)?n=e:!e||typeof e!="object"||!("key"in e)?n=new se(e,e?.value):n=new se(e.key,e.value);const r=nt(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${n.key} already set`);H(r.value)&&So(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=nt(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const r=nt(this.items,e)?.value;return(!t&&H(r)?r.value:r)??void 0}has(e){return!!nt(this.items,e)}set(e,t){this.add(new se(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)Io(t,r,i);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(const r of this.items)if(!V(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})),Ao(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:n,onComment:t})}}const It={collection:"map",default:!0,nodeClass:ue,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)=>ue.from(s,e,t),"createNode")};class Ue extends Co{static{c(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(bt,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=Yn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const n=Yn(e);if(typeof n!="number")return;const r=this.items[n];return!t&&H(r)?r.value:r}has(e){const t=Yn(e);return typeof t=="number"&&t<this.items.length}set(e,t){const n=Yn(e);if(typeof n!="number")throw new Error(`Expected a valid index, not ${e}.`);const r=this.items[n];H(r)&&So(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(ge(i,String(r++),t));return n}toString(e,t,n){return e?Ao(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(Ht(a,void 0,n))}}return i}}function Yn(s){let e=H(s)?s.value:s;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}c(Yn,"asItemIndex");const At={collection:"seq",default:!0,nodeClass:Ue,tag:"tag:yaml.org,2002:seq",resolve(s,e){return Ct(s)||e("Expected a sequence for this tag"),s},createNode:c((s,e,t)=>Ue.from(s,e,t),"createNode")},Xn={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),zt(s,e,t,n)}},Qn={identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:c(()=>new R(null),"resolve"),stringify:c(({source:s},e)=>typeof s=="string"&&Qn.test.test(s)?s:e.options.nullStr,"stringify")},pr={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 R(s[0]==="t"||s[0]==="T"),"resolve"),stringify({source:s,value:e},t){if(s&&pr.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 Se({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(Se,"stringifyNumber");const Oo={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:Se},$o={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():Se(s)}},No={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 R(parseFloat(s)),t=s.indexOf(".");return t!==-1&&s[s.length-1]==="0"&&(e.minFractionDigits=s.length-t-1),e},stringify:Se},Zn=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify$2"),mr=c((s,e,t,{intAsBigInt:n})=>n?BigInt(s):parseInt(s.substring(e),t),"intResolve$1");function xo(s,e,t){const{value:n}=s;return Zn(n)&&n>=0?t+n.toString(e):Se(s)}c(xo,"intStringify$1");const Po={identify:c(s=>Zn(s)&&s>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:c((s,e,t)=>mr(s,2,8,t),"resolve"),stringify:c(s=>xo(s,8,"0o"),"stringify")},Ro={identify:Zn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:c((s,e,t)=>mr(s,0,10,t),"resolve"),stringify:Se},Mo={identify:c(s=>Zn(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)=>mr(s,2,16,t),"resolve"),stringify:c(s=>xo(s,16,"0x"),"stringify")},lu=[It,At,Xn,Qn,pr,Po,Ro,Mo,Oo,$o,No];function Lo(s){return typeof s=="bigint"||Number.isInteger(s)}c(Lo,"intIdentify$1");const es=c(({value:s})=>JSON.stringify(s),"stringifyJSON"),uu=[{identify:c(s=>typeof s=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:c(s=>s,"resolve"),stringify:es},{identify:c(s=>s==null,"identify"),createNode:c(()=>new R(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:c(()=>null,"resolve"),stringify:es},{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:es},{identify:Lo,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})=>Lo(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:es}],du={default:!0,tag:"",test:/^/,resolve(s,e){return e(`Unresolved plain scalar ${JSON.stringify(s)}`),s}},fu=[It,At].concat(uu,du),gr={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=R.BLOCK_LITERAL),e!==R.QUOTE_DOUBLE){const l=Math.max(n.options.lineWidth-n.indent.length,n.options.minContentWidth),u=Math.ceil(a.length/l),d=new Array(u);for(let f=0,h=0;f<u;++f,h+=l)d[f]=a.substr(h,l);a=d.join(e===R.BLOCK_LITERAL?`
54
+ `:" ")}return zt({comment:s,type:e,value:a},n,r,i)}};function Do(s,e){if(Ct(s))for(let t=0;t<s.items.length;++t){let n=s.items[t];if(!V(n)){if(St(n)){n.items.length>1&&e("Each pair must have its own sequence indicator");const r=n.items[0]||new se(new R(null));if(n.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${n.commentBefore}
55
55
  ${r.key.commentBefore}`:n.commentBefore),n.comment){const i=r.value??r.key;i.comment=i.comment?`${n.comment}
56
- ${i.comment}`:n.comment}n=r}s.items[t]=V(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(Eo,"resolvePairs");function Oo(s,e,t){const{replacer:n}=t,r=new qe(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(ir(a,l,t))}return r}c(Oo,"createPairs");const lr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Eo,createNode:Oo};class Mt extends qe{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ue.prototype.add.bind(this),this.delete=ue.prototype.delete.bind(this),this.get=ue.prototype.get.bind(this),this.has=ue.prototype.has.bind(this),this.set=ue.prototype.set.bind(this),this.tag=Mt.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(V(r)?(i=me(r.key,"",t),o=me(r.value,i,t)):i=me(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=Oo(e,t,n),i=new this;return i.items=r.items,i}}Mt.tag="tag:yaml.org,2002:omap";const ur={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:Mt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Eo(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 Mt,t)},createNode:c((s,e,t)=>Mt.from(s,e,t),"createNode")};function Ao({value:s,source:e},t){return e&&(s?Io:$o).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Ao,"boolStringify");const Io={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 P(!0),"resolve"),stringify:Ao},$o={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 P(!1),"resolve"),stringify:Ao},Zl={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:we},eu={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():we(s)}},tu={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 P(parseFloat(s.replace(/_/g,""))),t=s.indexOf(".");if(t!==-1){const n=s.substring(t+1).replace(/_/g,"");n[n.length-1]==="0"&&(e.minFractionDigits=n.length)}return e},stringify:we},Wt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function Gn(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(Gn,"intResolve");function fr(s,e,t){const{value:n}=s;if(Wt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return we(s)}c(fr,"intStringify");const nu={identify:Wt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>Gn(s,2,2,t),"resolve"),stringify:c(s=>fr(s,2,"0b"),"stringify")},su={identify:Wt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>Gn(s,1,8,t),"resolve"),stringify:c(s=>fr(s,8,"0"),"stringify")},ru={identify:Wt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>Gn(s,0,10,t),"resolve"),stringify:we},iu={identify:Wt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>Gn(s,2,16,t),"resolve"),stringify:c(s=>fr(s,16,"0x"),"stringify")};class Rt extends ue{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Rt.tag}add(e){let t;V(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new se(e.key,null):t=new se(e,null),Qe(this.items,t.key)||this.items.push(t)}get(e,t){const n=Qe(this.items,e);return!t&&V(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=Qe(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new se(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(ir(o,null,n));return i}}Rt.tag="tag:yaml.org,2002:set";const dr={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Rt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Rt.from(s,e,t),"createNode"),resolve(s,e){if(mt(s)){if(s.hasAllNullValues(!0))return Object.assign(new Rt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function hr(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(hr,"parseSexagesimal");function No(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 we(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(No,"stringifySexagesimal");const xo={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})=>hr(s,t),"resolve"),stringify:No},Po={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=>hr(s,!1),"resolve"),stringify:No},zn={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(zn.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=hr(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")},Mo=[Ct,kt,Wn,Jn,Io,$o,nu,su,ru,iu,Zl,eu,tu,cr,$e,ur,lr,dr,xo,Po,zn],Ro=new Map([["core",zl],["failsafe",[Ct,kt,Wn]],["json",Ql],["yaml11",Mo],["yaml-1.1",Mo]]),Lo={binary:cr,bool:or,float:So,floatExp:bo,floatNaN:wo,floatTime:Po,int:ko,intHex:To,intOct:Co,intTime:xo,map:Ct,merge:$e,null:Jn,omap:ur,pairs:lr,seq:kt,set:dr,timestamp:zn},ou={"tag:yaml.org,2002:binary":cr,"tag:yaml.org,2002:merge":$e,"tag:yaml.org,2002:omap":ur,"tag:yaml.org,2002:pairs":lr,"tag:yaml.org,2002:set":dr,"tag:yaml.org,2002:timestamp":zn};function pr(s,e,t){const n=Ro.get(e);if(n&&!s)return t&&!n.includes($e)?n.concat($e):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(Ro.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($e)),r.reduce((i,o)=>{const a=typeof o=="string"?Lo[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(Lo).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(pr,"getTags");const au=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class $s{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?pr(e,"compat"):e?pr(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?ou:{},this.tags=pr(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,je,{value:Ct}),Object.defineProperty(this,Te,{value:Wn}),Object.defineProperty(this,pt,{value:kt}),this.sortMapEntries=typeof o=="function"?o:o===!0?au:null}clone(){const e=Object.create($s.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function cu(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=ho(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(Ie(l,""))}let o=!1,a=null;if(s.contents){if(Y(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const f=i(s.contents.commentBefore);t.push(Ie(f,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=vt(s.contents,r,()=>a=null,l);a&&(u+=Xe(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(vt(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
57
- `)?(t.push("..."),t.push(Ie(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(Ie(i(l),"")))}return t.join(`
56
+ ${i.comment}`:n.comment}n=r}s.items[t]=V(n)?n:new se(n)}}else e("Expected a sequence for this tag");return s}c(Do,"resolvePairs");function jo(s,e,t){const{replacer:n}=t,r=new Ue(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(hr(a,l,t))}return r}c(jo,"createPairs");const yr={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Do,createNode:jo};class qt extends Ue{static{c(this,"YAMLOMap")}constructor(){super(),this.add=ue.prototype.add.bind(this),this.delete=ue.prototype.delete.bind(this),this.get=ue.prototype.get.bind(this),this.has=ue.prototype.has.bind(this),this.set=ue.prototype.set.bind(this),this.tag=qt.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(V(r)?(i=ge(r.key,"",t),o=ge(r.value,i,t)):i=ge(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=jo(e,t,n),i=new this;return i.items=r.items,i}}qt.tag="tag:yaml.org,2002:omap";const wr={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:qt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Do(s,e),n=[];for(const{key:r}of t.items)H(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new qt,t)},createNode:c((s,e,t)=>qt.from(s,e,t),"createNode")};function Fo({value:s,source:e},t){return e&&(s?qo:Ko).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Fo,"boolStringify");const qo={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 R(!0),"resolve"),stringify:Fo},Ko={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 R(!1),"resolve"),stringify:Fo},hu={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:Se},pu={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():Se(s)}},mu={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 R(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:Se},Yt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function ts(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(ts,"intResolve");function br(s,e,t){const{value:n}=s;if(Yt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return Se(s)}c(br,"intStringify");const gu={identify:Yt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>ts(s,2,2,t),"resolve"),stringify:c(s=>br(s,2,"0b"),"stringify")},yu={identify:Yt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>ts(s,1,8,t),"resolve"),stringify:c(s=>br(s,8,"0"),"stringify")},wu={identify:Yt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>ts(s,0,10,t),"resolve"),stringify:Se},bu={identify:Yt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>ts(s,2,16,t),"resolve"),stringify:c(s=>br(s,16,"0x"),"stringify")};class Kt extends ue{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=Kt.tag}add(e){let t;V(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new se(e.key,null):t=new se(e,null),nt(this.items,t.key)||this.items.push(t)}get(e,t){const n=nt(this.items,e);return!t&&V(n)?H(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=nt(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new se(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(hr(o,null,n));return i}}Kt.tag="tag:yaml.org,2002:set";const Sr={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:Kt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>Kt.from(s,e,t),"createNode"),resolve(s,e){if(St(s)){if(s.hasAllNullValues(!0))return Object.assign(new Kt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function Cr(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(Cr,"parseSexagesimal");function Bo(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 Se(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(Bo,"stringifySexagesimal");const Uo={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})=>Cr(s,t),"resolve"),stringify:Bo},Wo={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=>Cr(s,!1),"resolve"),stringify:Bo},ns={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(ns.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 d=e[8];if(d&&d!=="Z"){let f=Cr(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:c(({value:s})=>s?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},Jo=[It,At,Xn,Qn,qo,Ko,gu,yu,wu,bu,hu,pu,mu,gr,xe,wr,yr,Sr,Uo,Wo,ns],Ho=new Map([["core",lu],["failsafe",[It,At,Xn]],["json",fu],["yaml11",Jo],["yaml-1.1",Jo]]),Vo={binary:gr,bool:pr,float:No,floatExp:$o,floatNaN:Oo,floatTime:Wo,int:Ro,intHex:Mo,intOct:Po,intTime:Uo,map:It,merge:xe,null:Qn,omap:wr,pairs:yr,seq:At,set:Sr,timestamp:ns},Su={"tag:yaml.org,2002:binary":gr,"tag:yaml.org,2002:merge":xe,"tag:yaml.org,2002:omap":wr,"tag:yaml.org,2002:pairs":yr,"tag:yaml.org,2002:set":Sr,"tag:yaml.org,2002:timestamp":ns};function vr(s,e,t){const n=Ho.get(e);if(n&&!s)return t&&!n.includes(xe)?n.concat(xe):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(Ho.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(xe)),r.reduce((i,o)=>{const a=typeof o=="string"?Vo[o]:o;if(!a){const l=JSON.stringify(o),u=Object.keys(Vo).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(a)||i.push(a),i},[])}c(vr,"getTags");const Cu=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Ls{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?vr(e,"compat"):e?vr(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?Su:{},this.tags=vr(t,this.name,n),this.toStringOptions=a??null,Object.defineProperty(this,Ke,{value:It}),Object.defineProperty(this,Ee,{value:Xn}),Object.defineProperty(this,bt,{value:At}),this.sortMapEntries=typeof o=="function"?o:o===!0?Cu:null}clone(){const e=Object.create(Ls.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function vu(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=To(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(Ne(l,""))}let o=!1,a=null;if(s.contents){if(Y(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const d=i(s.contents.commentBefore);t.push(Ne(d,""))}r.forceBlockIndent=!!s.comment,a=s.contents.comment}const l=a?void 0:()=>o=!0;let u=_t(s.contents,r,()=>a=null,l);a&&(u+=tt(u,"",i(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(_t(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
57
+ `)?(t.push("..."),t.push(Ne(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(Ne(i(l),"")))}return t.join(`
58
58
  `)+`
59
- `}c(cu,"stringifyDocument");class Lt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,pe,{value:Zs});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 oe({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(Lt.prototype,{[pe]:{value:Zs}});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=Y(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Tt(this.contents)&&this.contents.add(e)}addIn(e,t){Tt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=oo(this);e.anchor=!t||n.has(t)?ao(t||"a",n):t}return new Pn(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(_=>typeof _=="number"||_ instanceof String||_ 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:p,sourceObjects:m}=Ll(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:m},h=qt(e,f,y);return a&&z(h)&&(h.flow=!0),p(),h}createPair(e,t,n={}){const r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new se(r,i)}delete(e){return Tt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Kt(e)?this.contents==null?!1:(this.contents=null,!0):Tt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return z(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Kt(e)?!t&&J(this.contents)?this.contents.value:this.contents:z(this.contents)?this.contents.getIn(e,t):void 0}has(e){return z(this.contents)?this.contents.has(e):!1}hasIn(e){return Kt(e)?this.contents!==void 0:z(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Rn(this.schema,[e],t):Tt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Kt(e)?this.contents=t:this.contents==null?this.contents=Rn(this.schema,Array.from(e),t):Tt(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 oe({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 oe({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 $s(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=me(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"?bt(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 cu(this,e)}}function Tt(s){if(z(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Tt,"assertCollection");class mr 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 Ze extends mr{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Do extends mr{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const Yn=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
59
+ `}c(vu,"stringifyDocument");class Bt{static{c(this,"Document")}constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,me,{value:ar});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 oe({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){const e=Object.create(Bt.prototype,{[me]:{value:ar}});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=Y(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ot(this.contents)&&this.contents.add(e)}addIn(e,t){Ot(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const n=wo(this);e.anchor=!t||n.has(t)?bo(t||"a",n):t}return new qn(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(E=>typeof E=="number"||E instanceof String||E 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:d}=n??{},{onAnchor:f,setAnchors:h,sourceObjects:g}=Yl(this,o||"a"),y={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:f,onTagObj:u,replacer:r,schema:this.schema,sourceObjects:g},p=Ht(e,d,y);return a&&z(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 se(r,i)}delete(e){return Ot(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Vt(e)?this.contents==null?!1:(this.contents=null,!0):Ot(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return z(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Vt(e)?!t&&H(this.contents)?this.contents.value:this.contents:z(this.contents)?this.contents.getIn(e,t):void 0}has(e){return z(this.contents)?this.contents.has(e):!1}hasIn(e){return Vt(e)?this.contents!==void 0:z(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Bn(this.schema,[e],t):Ot(this.contents)&&this.contents.set(e,t)}setIn(e,t){Vt(e)?this.contents=t:this.contents==null?this.contents=Bn(this.schema,Array.from(e),t):Ot(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 oe({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 oe({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 Ls(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=ge(this.contents,t??"",a);if(typeof i=="function")for(const{count:u,res:d}of a.anchors.values())i(d,u);return typeof o=="function"?Tt(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 vu(this,e)}}function Ot(s){if(z(s))return!0;throw new Error("Expected a YAML collection as document contents")}c(Ot,"assertCollection");class kr 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 st extends kr{static{c(this,"YAMLParseError")}constructor(e,t,n){super("YAMLParseError",e,t,n)}}class Go extends kr{static{c(this,"YAMLWarning")}constructor(e,t,n){super("YAMLWarning",e,t,n)}}const ss=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
60
60
  `),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+=`:
61
61
 
62
62
  ${o}
63
63
  ${u}
64
- `}},"prettifyError");function _t(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,f=a,d="",p="",m=!1,y=!1,h=null,w=null,k=null,_=null,I=null,E=null,$=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),h&&(u&&A.type!=="comment"&&A.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),A.type){case"space":!e&&(t!=="doc-start"||n?.type!=="flow-collection")&&A.source.includes(" ")&&(h=A),f=!0;break;case"comment":{f||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const te=A.source.substring(1)||" ";d?d+=p+te:d=te,p="",u=!1;break}case"newline":u?d?d+=A.source:(!E||t!=="seq-item-ind")&&(l=!0):p+=A.source,u=!0,m=!0,(w||k)&&(_=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,$??($=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,$??($=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`),E&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),E=A,u=t==="seq-item-ind"||t==="explicit-key-ind",f=!1;break;case"comma":if(e){I&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),I=A,u=!1,f=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,f=!1}const N=s[s.length-1],D=N?N.offset+N.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"),h&&(u&&h.indent<=o||n?.type==="block-map"||n?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:I,found:E,spaceBefore:l,comment:d,hasNewline:m,anchor:w,tag:k,newlineAfterProp:_,end:D,start:$??D}}c(_t,"resolveProps");function Jt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
65
- `))return!0;if(s.end){for(const e of s.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of s.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(Jt(e.key)||Jt(e.value))return!0}return!1;default:return!0}}c(Jt,"containsNewline");function gr(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Jt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(gr,"flowIndentCheck");function jo(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(jo,"mapIncludes");const Fo="All mapping items must start at the same column";function lu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??ue,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:p,sep:m,value:y}=f,h=_t(d,{indicator:"explicit-key-ind",next:p??m?.[0],offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0}),w=!h.found;if(w){if(p&&(p.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in p&&p.indent!==n.indent&&r(l,"BAD_INDENT",Fo)),!h.anchor&&!h.tag&&!m){u=h.end,h.comment&&(a.comment?a.comment+=`
66
- `+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||Jt(p))&&r(p??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==n.indent&&r(l,"BAD_INDENT",Fo);t.atKey=!0;const k=h.end,_=p?s(t,p,h,r):e(t,k,d,null,h,r);t.schema.compat&&gr(n.indent,p,r),t.atKey=!1,jo(t,a.items,_)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const I=_t(m??[],{indicator:"map-value-ind",next:y,offset:_.range[2],onError:r,parentIndent:n.indent,startOnNewline:!p||p.type==="block-scalar"});if(l=I.end,I.found){w&&(y?.type==="block-map"&&!I.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<I.found.offset-1024&&r(_.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const E=y?s(t,y,I,r):e(t,l,m,null,I,r);t.schema.compat&&gr(n.indent,y,r),l=E.range[2];const $=new se(_,E);t.options.keepSourceTokens&&($.srcToken=f),a.items.push($)}else{w&&r(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),I.comment&&(_.comment?_.comment+=`
67
- `+I.comment:_.comment=I.comment);const E=new se(_);t.options.keepSourceTokens&&(E.srcToken=f),a.items.push(E)}}return u&&u<l&&r(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[n.offset,l,u??l],a}c(lu,"resolveBlockMap");function uu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??qe,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 p=_t(f,{indicator:"seq-item-ind",next:d,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!p.found)if(p.anchor||p.tag||d)d&&d.type==="block-seq"?r(p.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{u=p.end,p.comment&&(a.comment=p.comment);continue}const m=d?s(t,d,p,r):e(t,p.end,f,null,p,r);t.schema.compat&&gr(n.indent,d,r),l=m.range[2],a.items.push(m)}return a.range=[n.offset,l,u??l],a}c(uu,"resolveBlockSeq");function Ht(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(Ht,"resolveEnd");const yr="Block collections are not allowed within flow collections",wr=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function fu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:qe),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:_,key:I,sep:E,value:$}=k,N=_t(_,{flow:a,indicator:"explicit-key-ind",next:I??E?.[0],offset:d,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!E&&!$){w===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(u.comment?u.comment+=`
68
- `+N.comment:u.comment=N.comment),d=N.end;continue}!o&&t.options.strict&&Jt(I)&&r(I,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(const A of _)switch(A.type){case"comma":case"space":break;case"comment":D=A.source.substring(1);break e;default:break e}if(D){let A=u.items[u.items.length-1];V(A)&&(A=A.value??A.key),A.comment?A.comment+=`
69
- `+D:A.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!E&&!N.found){const D=$?s(t,$,N,r):e(t,N.end,E,null,N,r);u.items.push(D),d=D.range[2],wr($)&&r(D.range,"BLOCK_IN_FLOW",yr)}else{t.atKey=!0;const D=N.end,A=I?s(t,I,N,r):e(t,D,_,null,N,r);wr(I)&&r(A.range,"BLOCK_IN_FLOW",yr),t.atKey=!1;const te=_t(E??[],{flow:a,indicator:"map-value-ind",next:$,offset:A.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(te.found){if(!o&&!N.found&&t.options.strict){if(E)for(const ne of E){if(ne===te.found)break;if(ne.type==="newline"){r(ne,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<te.found.offset-1024&&r(te.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else $&&("source"in $&&$.source&&$.source[0]===":"?r($,"MISSING_CHAR",`Missing space after : in ${a}`):r(te.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const Le=$?s(t,$,te,r):te.found?e(t,te.end,E,null,te,r):null;Le?wr($)&&r(Le.range,"BLOCK_IN_FLOW",yr):te.comment&&(A.comment?A.comment+=`
70
- `+te.comment:A.comment=te.comment);const st=new se(A,Le);if(t.options.keepSourceTokens&&(st.srcToken=k),o){const ne=u;jo(t,ne.items,A)&&r(D,"DUPLICATE_KEY","Map keys must be unique"),ne.items.push(st)}else{const ne=new ue(t.schema);ne.flow=!0,ne.items.push(st);const pi=(Le??A).range;ne.range=[A.range[0],pi[1],pi[2]],u.items.push(ne)}d=Le?Le.range[2]:te.end}}const p=o?"}":"]",[m,...y]=n.end;let h=d;if(m&&m.source===p)h=m.offset+m.source.length;else{const w=a[0].toUpperCase()+a.substring(1),k=f?`${w} must end with a ${p}`:`${w} in block collection must be sufficiently indented and end with a ${p}`;r(d,f?"MISSING_CHAR":"BAD_INDENT",k),m&&m.source.length!==1&&y.unshift(m)}if(y.length>0){const w=Ht(y,h,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
71
- `+w.comment:u.comment=w.comment),u.range=[n.offset,h,w.offset]}else u.range=[n.offset,h,h];return u}c(fu,"resolveFlowCollection");function br(s,e,t,n,r,i){const o=t.type==="block-map"?lu(s,e,t,n,i):t.type==="block-seq"?uu(s,e,t,n,i):fu(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(br,"resolveCollection");function du(s,e,t,n,r){const i=n.tag,o=i?e.directives.tagName(i.source,p=>r(i,"TAG_RESOLVE_FAILED",p)):null;if(t.type==="block-seq"){const{anchor:p,newlineAfterProp:m}=n,y=p&&i?p.offset>i.offset?p:i:p??i;y&&(!m||m.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===ue.tagName&&a==="map"||o===qe.tagName&&a==="seq")return br(s,e,t,r,o);let l=e.schema.tags.find(p=>p.tag===o&&p.collection===a);if(!l){const p=e.schema.knownTags[o];if(p&&p.collection===a)e.schema.tags.push(Object.assign({},p,{default:!1})),l=p;else return p?r(i,"BAD_COLLECTION_TYPE",`${p.tag} used for ${a} collection, but expects ${p.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),br(s,e,t,r,o)}const u=br(s,e,t,r,o,l),f=l.resolve?.(u,p=>r(i,"TAG_RESOLVE_FAILED",p),e.options)??u,d=Y(f)?f:new P(f);return d.range=u.range,d.tag=o,l?.format&&(d.format=l.format),d}c(du,"composeCollection");function qo(s,e,t){const n=e.offset,r=hu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?P.BLOCK_FOLDED:P.BLOCK_LITERAL,o=e.source?pu(e.source):[];let a=o.length;for(let h=o.length-1;h>=0;--h){const w=o[h][1];if(w===""||w==="\r")a=h;else break}if(a===0){const h=r.chomp==="+"&&o.length>0?`
72
- `.repeat(Math.max(1,o.length-1)):"";let w=n+r.length;return e.source&&(w+=e.source.length),{value:h,type:i,comment:r.comment,range:[n,w,w]}}let l=e.indent+r.indent,u=e.offset+r.length,f=0;for(let h=0;h<a;++h){const[w,k]=o[h];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=h,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 h=o.length-1;h>=a;--h)o[h][0].length>l&&(a=h+1);let d="",p="",m=!1;for(let h=0;h<f;++h)d+=o[h][0].slice(l)+`
73
- `;for(let h=f;h<a;++h){let[w,k]=o[h];u+=w.length+k.length+1;const _=k[k.length-1]==="\r";if(_&&(k=k.slice(0,-1)),k&&w.length<l){const E=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(u-k.length-(_?2:1),"BAD_INDENT",E),w=""}i===P.BLOCK_LITERAL?(d+=p+w.slice(l)+k,p=`
74
- `):w.length>l||k[0]===" "?(p===" "?p=`
75
- `:!m&&p===`
76
- `&&(p=`
77
-
78
- `),d+=p+w.slice(l)+k,p=`
79
- `,m=!0):k===""?p===`
80
- `?d+=`
81
- `:p=`
82
- `:(d+=p+k,p=" ",m=!1)}switch(r.chomp){case"-":break;case"+":for(let h=a;h<o.length;++h)d+=`
83
- `+o[h][0].slice(l);d[d.length-1]!==`
84
- `&&(d+=`
85
- `);break;default:d+=`
86
- `}const y=n+r.length+e.source.length;return{value:d,type:i,comment:r.comment,range:[n,y,y]}}c(qo,"resolveBlockScalar");function hu({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 p=1;p<r.length;++p){const m=r[p];if(!a&&(m==="-"||m==="+"))a=m;else{const y=Number(m);!o&&y?o=y:l===-1&&(l=s+p)}}l!==-1&&n(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let u=!1,f="",d=r.length;for(let p=1;p<e.length;++p){const m=e[p];switch(m.type){case"space":u=!0;case"newline":d+=m.source.length;break;case"comment":t&&!u&&n(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=m.source.length,f=m.source.substring(1);break;case"error":n(m,"UNEXPECTED_TOKEN",m.message),d+=m.source.length;break;default:{const y=`Unexpected token in block scalar header: ${m.type}`;n(m,"UNEXPECTED_TOKEN",y);const h=m.source;h&&typeof h=="string"&&(d+=h.length)}}}return{mode:i,indent:o,chomp:a,comment:f,length:d}}c(hu,"parseBlockScalarHeader");function pu(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(pu,"splitLines");function Ko(s,e,t){const{offset:n,type:r,source:i,end:o}=s;let a,l;const u=c((p,m,y)=>t(n+p,m,y),"_onError");switch(r){case"scalar":a=P.PLAIN,l=mu(i,u);break;case"single-quoted-scalar":a=P.QUOTE_SINGLE,l=gu(i,u);break;case"double-quoted-scalar":a=P.QUOTE_DOUBLE,l=yu(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=Ht(o,f,e,t);return{value:l,type:a,comment:d.comment,range:[n,f,d.offset]}}c(Ko,"resolveFlowScalar");function mu(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}`),Bo(s)}c(mu,"plainValue");function gu(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Bo(s.slice(1,-1)).replace(/''/g,"'")}c(gu,"singleQuotedValue");function Bo(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
64
+ `}},"prettifyError");function $t(s,{flow:e,indicator:t,next:n,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,u=a,d=a,f="",h="",g=!1,y=!1,p=null,w=null,k=null,E=null,O=null,I=null,$=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),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const te=A.source.substring(1)||" ";f?f+=h+te:f=te,h="",u=!1;break}case"newline":u?f?f+=A.source:(!I||t!=="seq-item-ind")&&(l=!0):h+=A.source,u=!0,g=!0,(w||k)&&(E=A),d=!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,$??($=A.offset),u=!1,d=!1,y=!0;break;case"tag":{k&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),k=A,$??($=A.offset),u=!1,d=!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",d=!1;break;case"comma":if(e){O&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),O=A,u=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),u=!1,d=!1}const N=s[s.length-1],D=N?N.offset+N.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:O,found:I,spaceBefore:l,comment:f,hasNewline:g,anchor:w,tag:k,newlineAfterProp:E,end:D,start:$??D}}c($t,"resolveProps");function Xt(s){if(!s)return null;switch(s.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(s.source.includes(`
65
+ `))return!0;if(s.end){for(const e of s.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of s.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(Xt(e.key)||Xt(e.value))return!0}return!1;default:return!0}}c(Xt,"containsNewline");function Tr(s,e,t){if(e?.type==="flow-collection"){const n=e.end[0];n.indent===s&&(n.source==="]"||n.source==="}")&&Xt(e)&&t(n,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}c(Tr,"flowIndentCheck");function zo(s,e,t){const{uniqueKeys:n}=s.options;if(n===!1)return!1;const r=typeof n=="function"?n:(i,o)=>i===o||H(i)&&H(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}c(zo,"mapIncludes");const Yo="All mapping items must start at the same column";function ku({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=n.offset,u=null;for(const d of n.items){const{start:f,key:h,sep:g,value:y}=d,p=$t(f,{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",Yo)),!p.anchor&&!p.tag&&!g){u=p.end,p.comment&&(a.comment?a.comment+=`
66
+ `+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||Xt(h))&&r(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==n.indent&&r(l,"BAD_INDENT",Yo);t.atKey=!0;const k=p.end,E=h?s(t,h,p,r):e(t,k,f,null,p,r);t.schema.compat&&Tr(n.indent,h,r),t.atKey=!1,zo(t,a.items,E)&&r(k,"DUPLICATE_KEY","Map keys must be unique");const O=$t(g??[],{indicator:"map-value-ind",next:y,offset:E.range[2],onError:r,parentIndent:n.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=O.end,O.found){w&&(y?.type==="block-map"&&!O.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<O.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=y?s(t,y,O,r):e(t,l,g,null,O,r);t.schema.compat&&Tr(n.indent,y,r),l=I.range[2];const $=new se(E,I);t.options.keepSourceTokens&&($.srcToken=d),a.items.push($)}else{w&&r(E.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),O.comment&&(E.comment?E.comment+=`
67
+ `+O.comment:E.comment=O.comment);const I=new se(E);t.options.keepSourceTokens&&(I.srcToken=d),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(ku,"resolveBlockMap");function Tu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=i?.nodeClass??Ue,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=n.offset,u=null;for(const{start:d,value:f}of n.items){const h=$t(d,{indicator:"seq-item-ind",next:f,offset:l,onError:r,parentIndent:n.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.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=f?s(t,f,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Tr(n.indent,f,r),l=g.range[2],a.items.push(g)}return a.range=[n.offset,l,u??l],a}c(Tu,"resolveBlockSeq");function Qt(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 d=l.substring(1)||" ";r?r+=o+d:r=d,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(Qt,"resolveEnd");const Er="Block collections are not allowed within flow collections",_r=c(s=>s&&(s.type==="block-map"||s.type==="block-seq"),"isBlock");function Eu({composeNode:s,composeEmptyNode:e},t,n,r,i){const o=n.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?ue:Ue),u=new l(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=n.offset+n.start.source.length;for(let w=0;w<n.items.length;++w){const k=n.items[w],{start:E,key:O,sep:I,value:$}=k,N=$t(E,{flow:a,indicator:"explicit-key-ind",next:O??I?.[0],offset:f,onError:r,parentIndent:n.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!I&&!$){w===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):w<n.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(u.comment?u.comment+=`
68
+ `+N.comment:u.comment=N.comment),f=N.end;continue}!o&&t.options.strict&&Xt(O)&&r(O,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(w===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(const A of E)switch(A.type){case"comma":case"space":break;case"comment":D=A.source.substring(1);break e;default:break e}if(D){let A=u.items[u.items.length-1];V(A)&&(A=A.value??A.key),A.comment?A.comment+=`
69
+ `+D:A.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!I&&!N.found){const D=$?s(t,$,N,r):e(t,N.end,I,null,N,r);u.items.push(D),f=D.range[2],_r($)&&r(D.range,"BLOCK_IN_FLOW",Er)}else{t.atKey=!0;const D=N.end,A=O?s(t,O,N,r):e(t,D,E,null,N,r);_r(O)&&r(A.range,"BLOCK_IN_FLOW",Er),t.atKey=!1;const te=$t(I??[],{flow:a,indicator:"map-value-ind",next:$,offset:A.range[2],onError:r,parentIndent:n.indent,startOnNewline:!1});if(te.found){if(!o&&!N.found&&t.options.strict){if(I)for(const ne of I){if(ne===te.found)break;if(ne.type==="newline"){r(ne,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<te.found.offset-1024&&r(te.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else $&&("source"in $&&$.source&&$.source[0]===":"?r($,"MISSING_CHAR",`Missing space after : in ${a}`):r(te.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const je=$?s(t,$,te,r):te.found?e(t,te.end,I,null,te,r):null;je?_r($)&&r(je.range,"BLOCK_IN_FLOW",Er):te.comment&&(A.comment?A.comment+=`
70
+ `+te.comment:A.comment=te.comment);const lt=new se(A,je);if(t.options.keepSourceTokens&&(lt.srcToken=k),o){const ne=u;zo(t,ne.items,A)&&r(D,"DUPLICATE_KEY","Map keys must be unique"),ne.items.push(lt)}else{const ne=new ue(t.schema);ne.flow=!0,ne.items.push(lt);const Ti=(je??A).range;ne.range=[A.range[0],Ti[1],Ti[2]],u.items.push(ne)}f=je?je.range[2]:te.end}}const h=o?"}":"]",[g,...y]=n.end;let p=f;if(g&&g.source===h)p=g.offset+g.source.length;else{const w=a[0].toUpperCase()+a.substring(1),k=d?`${w} must end with a ${h}`:`${w} in block collection must be sufficiently indented and end with a ${h}`;r(f,d?"MISSING_CHAR":"BAD_INDENT",k),g&&g.source.length!==1&&y.unshift(g)}if(y.length>0){const w=Qt(y,p,t.options.strict,r);w.comment&&(u.comment?u.comment+=`
71
+ `+w.comment:u.comment=w.comment),u.range=[n.offset,p,w.offset]}else u.range=[n.offset,p,p];return u}c(Eu,"resolveFlowCollection");function Ir(s,e,t,n,r,i){const o=t.type==="block-map"?ku(s,e,t,n,i):t.type==="block-seq"?Tu(s,e,t,n,i):Eu(s,e,t,n,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}c(Ir,"resolveCollection");function _u(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===ue.tagName&&a==="map"||o===Ue.tagName&&a==="seq")return Ir(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),Ir(s,e,t,r,o)}const u=Ir(s,e,t,r,o,l),d=l.resolve?.(u,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??u,f=Y(d)?d:new R(d);return f.range=u.range,f.tag=o,l?.format&&(f.format=l.format),f}c(_u,"composeCollection");function Xo(s,e,t){const n=e.offset,r=Iu(e,s.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[n,n,n]};const i=r.mode===">"?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=e.source?Au(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?`
72
+ `.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,d=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),d=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 f="",h="",g=!1;for(let p=0;p<d;++p)f+=o[p][0].slice(l)+`
73
+ `;for(let p=d;p<a;++p){let[w,k]=o[p];u+=w.length+k.length+1;const E=k[k.length-1]==="\r";if(E&&(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-(E?2:1),"BAD_INDENT",I),w=""}i===R.BLOCK_LITERAL?(f+=h+w.slice(l)+k,h=`
74
+ `):w.length>l||k[0]===" "?(h===" "?h=`
75
+ `:!g&&h===`
76
+ `&&(h=`
77
+
78
+ `),f+=h+w.slice(l)+k,h=`
79
+ `,g=!0):k===""?h===`
80
+ `?f+=`
81
+ `:h=`
82
+ `:(f+=h+k,h=" ",g=!1)}switch(r.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)f+=`
83
+ `+o[p][0].slice(l);f[f.length-1]!==`
84
+ `&&(f+=`
85
+ `);break;default:f+=`
86
+ `}const y=n+r.length+e.source.length;return{value:f,type:i,comment:r.comment,range:[n,y,y]}}c(Xo,"resolveBlockScalar");function Iu({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,d="",f=r.length;for(let h=1;h<e.length;++h){const g=e[h];switch(g.type){case"space":u=!0;case"newline":f+=g.source.length;break;case"comment":t&&!u&&n(g,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=g.source.length,d=g.source.substring(1);break;case"error":n(g,"UNEXPECTED_TOKEN",g.message),f+=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"&&(f+=p.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:f}}c(Iu,"parseBlockScalarHeader");function Au(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(Au,"splitLines");function Qo(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=R.PLAIN,l=Ou(i,u);break;case"single-quoted-scalar":a=R.QUOTE_SINGLE,l=$u(i,u);break;case"double-quoted-scalar":a=R.QUOTE_DOUBLE,l=Nu(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 d=n+i.length,f=Qt(o,d,e,t);return{value:l,type:a,comment:f.comment,range:[n,d,f.offset]}}c(Qo,"resolveFlowScalar");function Ou(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}`),Zo(s)}c(Ou,"plainValue");function $u(s,e){return(s[s.length-1]!=="'"||s.length===1)&&e(s.length,"MISSING_CHAR","Missing closing 'quote"),Zo(s.slice(1,-1)).replace(/''/g,"'")}c($u,"singleQuotedValue");function Zo(s){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
87
87
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
88
88
  `,"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===`
89
89
  `?r+=i:i=`
90
- `:(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(Bo,"foldLines");function yu(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
90
+ `:(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(Zo,"foldLines");function Nu(s,e){let t="";for(let n=1;n<s.length-1;++n){const r=s[n];if(!(r==="\r"&&s[n+1]===`
91
91
  `))if(r===`
92
- `){const{fold:i,offset:o}=wu(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=bu[i];if(o)t+=o;else if(i===`
92
+ `){const{fold:i,offset:o}=xu(s,n);t+=i,n=o}else if(r==="\\"){let i=s[++n];const o=Pu[i];if(o)t+=o;else if(i===`
93
93
  `)for(i=s[n+1];i===" "||i===" ";)i=s[++n+1];else if(i==="\r"&&s[n+1]===`
94
- `)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+=Su(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!==`
94
+ `)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+=Ru(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!==`
95
95
  `&&!(o==="\r"&&s[n+2]===`
96
- `)&&(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(yu,"doubleQuotedValue");function wu(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
96
+ `)&&(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(Nu,"doubleQuotedValue");function xu(s,e){let t="",n=s[e+1];for(;(n===" "||n===" "||n===`
97
97
  `||n==="\r")&&!(n==="\r"&&s[e+2]!==`
98
98
  `);)n===`
99
99
  `&&(t+=`
100
- `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(wu,"foldNewline");const bu={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Su(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(Su,"parseCharCode");function Uo(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?qo(s,e,n):Ko(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[Te]:l?u=vu(s.schema,r,l,t,n):e.type==="scalar"?u=Cu(s,r,e,n):u=s.schema[Te];let f;try{const d=u.resolve(r,p=>n(t??e,"TAG_RESOLVE_FAILED",p),s.options);f=J(d)?d:new P(d)}catch(d){const p=d instanceof Error?d.message:String(d);n(t??e,"TAG_RESOLVE_FAILED",p),f=new P(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(Uo,"composeScalar");function vu(s,e,t,n,r){if(t==="!")return s[Te];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[Te])}c(vu,"findScalarTagByName");function Cu({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[Te];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[Te];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(Cu,"findScalarTagByTest");function ku(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(ku,"emptyScalarPosition");const Tu={composeNode:Wo,composeEmptyNode:Sr};function Wo(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=_u(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=Uo(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=du(Tu,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=Sr(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(Wo,"composeNode");function Sr(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const f={type:"scalar",offset:ku(e,t,n),indent:-1,source:""},d=Uo(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(Sr,"composeEmptyNode");function _u({options:s},{offset:e,source:t,end:n},r){const i=new Pn(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=Ht(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(_u,"composeAlias");function Eu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Lt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},f=_t(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?Wo(u,r,f,o):Sr(u,f.end,n,null,f,o);const d=l.contents.range[2],p=Ht(i,d,!1,o);return p.comment&&(l.comment=p.comment),l.range=[t,d,p.offset],l}c(Eu,"composeDoc");function Vt(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(Vt,"getErrorPos");function Jo(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?`
100
+ `),e+=1,n=s[e+1];return t||(t=" "),{fold:t,offset:e}}c(xu,"foldNewline");const Pu={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
101
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function Ru(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(Ru,"parseCharCode");function ea(s,e,t,n){const{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?Xo(s,e,n):Qo(e,s.options.strict,n),l=t?s.directives.tagName(t.source,f=>n(t,"TAG_RESOLVE_FAILED",f)):null;let u;s.options.stringKeys&&s.atKey?u=s.schema[Ee]:l?u=Mu(s.schema,r,l,t,n):e.type==="scalar"?u=Lu(s,r,e,n):u=s.schema[Ee];let d;try{const f=u.resolve(r,h=>n(t??e,"TAG_RESOLVE_FAILED",h),s.options);d=H(f)?f:new R(f)}catch(f){const h=f instanceof Error?f.message:String(f);n(t??e,"TAG_RESOLVE_FAILED",h),d=new R(r)}return d.range=a,d.source=r,i&&(d.type=i),l&&(d.tag=l),u.format&&(d.format=u.format),o&&(d.comment=o),d}c(ea,"composeScalar");function Mu(s,e,t,n,r){if(t==="!")return s[Ee];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[Ee])}c(Mu,"findScalarTagByName");function Lu({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[Ee];if(t.compat){const a=t.compat.find(l=>l.default&&l.test?.test(n))??t[Ee];if(o.tag!==a.tag){const l=e.tagString(o.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${l} or ${u}`;i(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}c(Lu,"findScalarTagByTest");function Du(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(Du,"emptyScalarPosition");const ju={composeNode:ta,composeEmptyNode:Ar};function ta(s,e,t,n){const r=s.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t;let u,d=!0;switch(e.type){case"alias":u=Fu(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=ea(s,e,l,n),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=_u(ju,s,e,t,n),a&&(u.anchor=a.source.substring(1));break;default:{const f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;n(e,"UNEXPECTED_TOKEN",f),u=Ar(s,e.offset,void 0,null,t,n),d=!1}}return a&&u.anchor===""&&n(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&s.options.stringKeys&&(!H(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&&d&&(u.srcToken=e),u}c(ta,"composeNode");function Ar(s,e,t,n,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},u){const d={type:"scalar",offset:Du(e,t,n),indent:-1,source:""},f=ea(s,d,a,u);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(f.spaceBefore=!0),i&&(f.comment=i,f.range[2]=l),f}c(Ar,"composeEmptyNode");function Fu({options:s},{offset:e,source:t,end:n},r){const i=new qn(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=Qt(n,o,s.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}c(Fu,"composeAlias");function qu(s,e,{offset:t,start:n,value:r,end:i},o){const a=Object.assign({_directives:e},s),l=new Bt(void 0,a),u={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=$t(n,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?ta(u,r,d,o):Ar(u,d.end,n,null,d,o);const f=l.contents.range[2],h=Qt(i,f,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,f,h.offset],l}c(qu,"composeDoc");function Zt(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(Zt,"getErrorPos");function na(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?`
102
102
 
103
103
  `:`
104
- `)+(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(Jo,"parsePrelude");class vr{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=Vt(t);i?this.warnings.push(new Do(o,n,r)):this.errors.push(new Ze(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=Jo(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
104
+ `)+(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(na,"parsePrelude");class Or{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=Zt(t);i?this.warnings.push(new Go(o,n,r)):this.errors.push(new st(o,n,r))},this.directives=new oe({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:n,afterEmptyLine:r}=na(this.prelude);if(n){const i=e.contents;if(t)e.comment=e.comment?`${e.comment}
105
105
  ${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(z(i)&&!i.flow&&i.items.length>0){let o=i.items[0];V(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${n}
106
106
  ${a}`:n}else{const o=i.commentBefore;i.commentBefore=o?`${n}
107
- ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Jo(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=Vt(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=Eu(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 Ze(Vt(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 Ze(Vt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=Ht(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
108
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ze(Vt(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 Lt(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 Ou(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 Ze([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Ko(s,e,n);case"block-scalar":return qo({options:{strict:e}},s,n)}}return null}c(Ou,"resolveAsScalar");function Au(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=Ut({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:`
107
+ ${o}`:n}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:na(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=Zt(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=qu(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 st(Zt(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 st(Zt(e),"UNEXPECTED_TOKEN",n));break}this.doc.directives.docEnd=!0;const t=Qt(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const n=this.doc.comment;this.doc.comment=n?`${n}
108
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new st(Zt(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 Bt(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 Ku(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 st([a,a+1],i,o)},"_onError");switch(s.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return Qo(s,e,n);case"block-scalar":return Xo({options:{strict:e}},s,n)}}return null}c(Ku,"resolveAsScalar");function Bu(s,e){const{implicitKey:t=!1,indent:n,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=zt({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:`
109
109
  `}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
110
- `),f=a.substring(0,u),d=a.substring(u+1)+`
111
- `,p=[{type:"block-scalar-header",offset:i,indent:n,source:f}];return Ho(p,l)||p.push({type:"newline",offset:-1,indent:n,source:`
112
- `}),{type:"block-scalar",offset:i,indent:n,props:p,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(Au,"createScalarToken");function Iu(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=Ut({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">":$u(s,l);break;case'"':Cr(s,l,"double-quoted-scalar");break;case"'":Cr(s,l,"single-quoted-scalar");break;default:Cr(s,l,"scalar")}}c(Iu,"setScalarValue");function $u(s,e){const t=e.indexOf(`
110
+ `),d=a.substring(0,u),f=a.substring(u+1)+`
111
+ `,h=[{type:"block-scalar-header",offset:i,indent:n,source:d}];return sa(h,l)||h.push({type:"newline",offset:-1,indent:n,source:`
112
+ `}),{type:"block-scalar",offset:i,indent:n,props:h,source:f}}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(Bu,"createScalarToken");function Uu(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=zt({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">":Wu(s,l);break;case'"':$r(s,l,"double-quoted-scalar");break;case"'":$r(s,l,"single-quoted-scalar");break;default:$r(s,l,"scalar")}}c(Uu,"setScalarValue");function Wu(s,e){const t=e.indexOf(`
113
113
  `),n=e.substring(0,t),r=e.substring(t+1)+`
114
- `;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}];Ho(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
- `});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($u,"setBlockScalarValue");function Ho(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(Ho,"addEndtoBlockProps");function Cr(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:`
116
- `};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(Cr,"setFlowScalarValue");const Nu=c(s=>"type"in s?Xn(s):Qn(s),"stringify$1");function Xn(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=Xn(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=Qn(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=Qn(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=Qn(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(Xn,"stringifyToken");function Qn({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=Xn(e)),t)for(const i of t)r+=i.source;return n&&(r+=Xn(n)),r}c(Qn,"stringifyItem");const kr=Symbol("break visit"),xu=Symbol("skip children"),Vo=Symbol("remove item");function et(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),Go(Object.freeze([]),s,e)}c(et,"visit"),et.BREAK=kr,et.SKIP=xu,et.REMOVE=Vo,et.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},et.parentCollection=(s,e)=>{const t=et.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 Go(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=Go(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===kr)return kr;a===Vo&&(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(Go,"_visit");const Zn="\uFEFF",es="",ts="",Gt="",Pu=c(s=>!!s&&"items"in s,"isCollection"),Mu=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function Ru(s){switch(s){case Zn:return"<BOM>";case es:return"<DOC>";case ts:return"<FLOW_END>";case Gt:return"<SCALAR>";default:return JSON.stringify(s)}}c(Ru,"prettyToken");function zo(s){switch(s){case Zn:return"byte-order-mark";case es:return"doc-mode";case ts:return"flow-error-end";case Gt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
114
+ `;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}];sa(a,"end"in s?s.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
115
+ `});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(Wu,"setBlockScalarValue");function sa(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(sa,"addEndtoBlockProps");function $r(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:`
116
+ `};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($r,"setFlowScalarValue");const Ju=c(s=>"type"in s?rs(s):is(s),"stringify$1");function rs(s){switch(s.type){case"block-scalar":{let e="";for(const t of s.props)e+=rs(t);return e+s.source}case"block-map":case"block-seq":{let e="";for(const t of s.items)e+=is(t);return e}case"flow-collection":{let e=s.start.source;for(const t of s.items)e+=is(t);for(const t of s.end)e+=t.source;return e}case"document":{let e=is(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(rs,"stringifyToken");function is({start:s,key:e,sep:t,value:n}){let r="";for(const i of s)r+=i.source;if(e&&(r+=rs(e)),t)for(const i of t)r+=i.source;return n&&(r+=rs(n)),r}c(is,"stringifyItem");const Nr=Symbol("break visit"),Hu=Symbol("skip children"),ra=Symbol("remove item");function rt(s,e){"type"in s&&s.type==="document"&&(s={start:s.start,value:s.value}),ia(Object.freeze([]),s,e)}c(rt,"visit"),rt.BREAK=Nr,rt.SKIP=Hu,rt.REMOVE=ra,rt.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},rt.parentCollection=(s,e)=>{const t=rt.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 ia(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=ia(Object.freeze(s.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Nr)return Nr;a===ra&&(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(ia,"_visit");const os="\uFEFF",as="",cs="",en="",Vu=c(s=>!!s&&"items"in s,"isCollection"),Gu=c(s=>!!s&&(s.type==="scalar"||s.type==="single-quoted-scalar"||s.type==="double-quoted-scalar"||s.type==="block-scalar"),"isScalar");function zu(s){switch(s){case os:return"<BOM>";case as:return"<DOC>";case cs:return"<FLOW_END>";case en:return"<SCALAR>";default:return JSON.stringify(s)}}c(zu,"prettyToken");function oa(s){switch(s){case os:return"byte-order-mark";case as:return"doc-mode";case cs:return"flow-error-end";case en:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
117
117
  `:case`\r
118
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}c(zo,"tokenType");var Lu=Object.freeze({__proto__:null,BOM:Zn,DOCUMENT:es,FLOW_END:ts,SCALAR:Gt,createScalarToken:Au,isCollection:Pu,isScalar:Mu,prettyToken:Ru,resolveAsScalar:Ou,setScalarValue:Iu,stringify:Nu,tokenType:zo,visit:et});function be(s){switch(s){case void 0:case" ":case`
119
- `:case"\r":case" ":return!0;default:return!1}}c(be,"isEmpty");const Yo=new Set("0123456789ABCDEFabcdef"),Du=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ns=new Set(",[]{}"),ju=new Set(` ,[]{}
120
- \r `),Tr=c(s=>!s||ju.has(s),"isNotAnchorChar");class Xo{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===`
118
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(s[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}c(oa,"tokenType");var Yu=Object.freeze({__proto__:null,BOM:os,DOCUMENT:as,FLOW_END:cs,SCALAR:en,createScalarToken:Bu,isCollection:Vu,isScalar:Gu,prettyToken:zu,resolveAsScalar:Ku,setScalarValue:Uu,stringify:Ju,tokenType:oa,visit:rt});function Ce(s){switch(s){case void 0:case" ":case`
119
+ `:case"\r":case" ":return!0;default:return!1}}c(Ce,"isEmpty");const aa=new Set("0123456789ABCDEFabcdef"),Xu=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ls=new Set(",[]{}"),Qu=new Set(` ,[]{}
120
+ \r `),xr=c(s=>!s||Qu.has(s),"isNotAnchorChar");class ca{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
121
  `?!0:t==="\r"?this.buffer[e+1]===`
122
122
  `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===" ";)t=this.buffer[++n+e];if(t==="\r"){const r=this.buffer[n+e+1];if(r===`
123
123
  `||!r&&!this.atEnd)return e+n+1}return t===`
124
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&be(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(`
125
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Zn&&(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 es,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==="...")&&be(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&&!be(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===":")&&be(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(Tr),"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("..."))&&be(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield ts,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(Tr),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||be(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(`
124
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t==="-"||t==="."){const n=this.buffer.substr(e,3);if((n==="---"||n==="...")&&Ce(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
125
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===os&&(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 as,yield*this.parseLineStart()}*parseLineStart(){const e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");const t=this.peek(3);if((t==="---"||t==="...")&&Ce(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ce(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){const[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ce(t)){const n=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=n,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(xr),"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("..."))&&Ce(r[3]))&&!(n===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield cs,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(xr),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||Ce(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let 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(`
126
126
  `,this.pos);if(r!==-1){for(;r!==-1;){const i=this.continueScalar(r+1);if(i===-1)break;r=n.indexOf(`
127
- `,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=>be(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`
127
+ `,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=>Ce(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`
128
128
  `:e=i,t=0;break;case"\r":{const o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
129
129
  `)break}default:break e}if(!n&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{const i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
130
130
  `,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===" ";)n=this.buffer[++r];if(n===" "){for(;n===" "||n===" "||n==="\r"||n===`
131
131
  `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);const a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
132
- `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Gt,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(be(i)||e&&ns.has(i))break;t=n}else if(be(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
132
+ `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield en,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(Ce(i)||e&&ls.has(i))break;t=n}else if(Ce(r)){let i=this.buffer[n+1];if(r==="\r"&&(i===`
133
133
  `?(n+=1,r=`
134
- `,i=this.buffer[n+1]):t=n),i==="#"||e&&ns.has(i))break;if(r===`
135
- `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&ns.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Gt,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(Tr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(be(t)||e&&ns.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(;!be(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(Du.has(t))t=this.buffer[++e];else if(t==="%"&&Yo.has(this.buffer[e+1])&&Yo.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===`
134
+ `,i=this.buffer[n+1]):t=n),i==="#"||e&&ls.has(i))break;if(r===`
135
+ `){const o=this.continueScalar(n+1);if(o===-1)break;n=Math.max(n,o-2)}}else{if(e&&ls.has(r))break;t=n}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield en,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(xr))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(Ce(t)||e&&ls.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ce(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Xu.has(t))t=this.buffer[++e];else if(t==="%"&&aa.has(this.buffer[e+1])&&aa.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===`
136
136
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
137
- `?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 Qo{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 Ke(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(Ke,"includesToken");function Zo(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(Zo,"findNonEmptyIndex");function ea(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(ea,"isFlowToken");function ss(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(ss,"getPrevProps");function Et(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(Et,"getFirstKeyStartProps");function ta(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!Ke(e.start,"explicit-key-ind")&&!Ke(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,ea(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(ta,"fixFlowSeqItems");class _r{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 Xo,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=zo(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"&&ta(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&&Zo(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":{Zo(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=ss(this.peek(2)),n=Et(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(`
137
+ `?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 la{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 We(s,e){for(let t=0;t<s.length;++t)if(s[t].type===e)return!0;return!1}c(We,"includesToken");function ua(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(ua,"findNonEmptyIndex");function da(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(da,"isFlowToken");function us(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(us,"getPrevProps");function Nt(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(Nt,"getFirstKeyStartProps");function fa(s){if(s.start.type==="flow-seq-start")for(const e of s.items)e.sep&&!e.value&&!We(e.start,"explicit-key-ind")&&!We(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,da(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(fa,"fixFlowSeqItems");class Pr{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 ca,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=oa(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"&&fa(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&&ua(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":{ua(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=us(this.peek(2)),n=Nt(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(`
138
138
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
139
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const 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(Ke(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(ea(t.key)&&!Ke(t.sep,"newline")){const o=Et(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(Ke(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Et(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]}):Ke(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);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&&!Ke(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else n&&e.items.push({start: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||Ke(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const n=this.startBlockValue(e);if(n){this.stack.push(n);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let n;do yield*this.pop(),n=this.peek(1);while(n&&n.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const 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=ss(n),i=Et(r);ta(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(`
139
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const n="end"in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type==="comment"?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const 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(We(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(da(t.key)&&!We(t.sep,"newline")){const o=Nt(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(We(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Nt(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]}):We(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&&!We(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||We(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=us(n),i=Nt(r);fa(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(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=ss(e),n=Et(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=ss(e),n=Et(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 na(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new Qo||null,prettyErrors:e}}c(na,"parseOptions");function Fu(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(Yn(s,t)),a.warnings.forEach(Yn(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Fu,"parseAllDocuments");function sa(s,e={}){const{lineCounter:t,prettyErrors:n}=na(e),r=new _r(t?.addNewLine),i=new vr(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 Ze(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(Yn(s,t)),o.warnings.forEach(Yn(s,t))),o}c(sa,"parseDocument");function qu(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=sa(s,t);if(!r)return null;if(r.warnings.forEach(i=>po(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(qu,"parse");function Ku(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 ze(s)&&!n?s.toString(t):new Lt(s,n,t).toString(t)}c(Ku,"stringify");var Bu=Object.freeze({__proto__:null,Alias:Pn,CST:Lu,Composer:vr,Document:Lt,Lexer:Xo,LineCounter:Qo,Pair:se,Parser:_r,Scalar:P,Schema:$s,YAMLError:mr,YAMLMap:ue,YAMLParseError:Ze,YAMLSeq:qe,YAMLWarning:Do,isAlias:Fe,isCollection:z,isDocument:ze,isMap:mt,isNode:Y,isPair:V,isScalar:J,isSeq:gt,parse:qu,parseAllDocuments:Fu,parseDocument:sa,stringify:Ku,visit:Ye,visitAsync:xn});const fe={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},Uu={ignored:fl,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 Wu extends Gs{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=ot(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=qc.watch(this.membraneDir,Uu),this.watcher.on("add",e=>this.handleFileSystemEvent(fe.Updated,e)).on("change",e=>this.handleFileSystemEvent(fe.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(fe.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(fe.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===fe.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 L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?Bu.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 jc.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(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Er=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Er||{});const Ju={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class Hu extends Gs{static{c(this,"RemoteElementWatcher")}constructor(e=Ju){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 U.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 Kc(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!==$c.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===R.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 ra{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())}}async function Vu(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await U.withClient(n=>n.integrations.findAll());e.integration=t.map(n=>Or("integration",n));for(const n of Object.keys(le)){const r=le[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await U.withClient(a=>a[r.elements].findAll());if(i.push(...o.map(a=>Or(n,a))),r.integrationSpecific)for(const a of t){const l=await U.withClient(u=>u[r.elements].findAll({integrationId:a.id}));i.push(...l.map(u=>(u.integrationKey=a.key,Or(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(Vu,"getWorkspaceData");function Or(s,e){return e=Il(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(Or,"cleanUpForExport");const Ot="connectors",Ne="development",Ar={};async function Gu(){const s=await Vu("minified"),t=(await U.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await U.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=Be(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=B.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(B.join(i,l)),f=await Ir(l);if(!f)continue;if("baseUri"in f&&delete f.baseUri,f.uuid&&s.connector?.find(p=>p.uuid==f.uuid))n[f.id]=s.connector.find(p=>p.uuid==f.uuid).id,b.info(`[connectors] Matched ${f.name} uuid: ${f.uuid}`);else if(!n[f.id]){let p=!1;try{const m=await $r({connectorId:f.id});m&&m.isPublic&&(p=!0)}catch{}if(!p){b.info(`[connectors] Creating custom connector ${f.name} (${f.key})`);const m=await U.withClient(y=>y.post("connectors",{...f,workspaceId:t}));n[f.id]=m.id}}const d=u.filter(p=>F.statSync(B.join(i,l,p)).isDirectory());for(const p of d)await Xu({connector:f,version:p,connectorId:n[f.id]})}return n}c(Gu,"pushConnectors");async function ia({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=ki(),o=await $r({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await Qu({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await Zu({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ia,"pullRemoteConnector");function Be(){const s=Vs();return B.join(s.membraneDirPath,Ot)}c(Be,"getConnectorsPath");async function Ir(s){const e=B.join(Be(),s,`${s}.yml`);return Xs(e,!1)}c(Ir,"readConnector");async function zu(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=Bc("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=B.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(zu,"createZipArchive");async function Yu(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=Wc.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=B.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=B.join(e,o),u=B.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(Yu,"extractZipArchive");async function Xu({connector:s,version:e,connectorId:t}){const n=B.join(Be(),xe(s),oa(e)),r=B.join(n,"src"),i=B.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await zu(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new Uc;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Ne)b.info(`[connectors] Uploading connector ${t}`),await U.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await U.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 U.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(Xu,"pushConnectorVersion");async function $r({connectorId:s}){if(s){if(Ar[s])return Ar[s];try{const e=await U.withClient(t=>t.get(`connectors/${s}`));return Ar[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c($r,"getConnector");async function Qu({basePath:s,connector:e}){const t=xe(e),n=B.join(s,Ot,t);F.mkdirSync(n,{recursive:!0});const r=B.join(n,`${xe(e)}.yml`);F.writeFileSync(r,Dt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(Qu,"pullConnector");async function Zu({connector:s,connectorVersion:e,basePath:t}){const n=xe(s),r=oa(e),i=B.join(t,"connectors",n,r),o=await U.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=B.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=B.join(i,"src");F.mkdirSync(l,{recursive:!0}),await Yu(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(Zu,"pullConnectorVersion");function xe(s){return s.key}c(xe,"getConnectorDirName");function oa(s){return s??Ne}c(oa,"getConnectorVersionDirName");function ef(s){const e=ki(),t=xe(s);return B.join(e,Ot,t)}c(ef,"getConnectorDirPath");function tf(s){return s.match(`${Ot}/[^/]+/${Ne}/src/.*`)!==null}c(tf,"isConnectorSourceFile");async function nf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(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 U.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(nf,"putConnectorFile");async function sf(s){const e=s.match(`${Ot}/([^/]+)/${Ne}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Ir(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await U.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(sf,"deleteConnectorFile");async function rf(s,e){try{const t=await U.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await U.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=xe(t),i=B.join(Be(),r,Ne,"src",e);F.mkdirSync(B.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}`)}}c(rf,"pullConnectorFile");async function of(s,e){const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(of,"deleteLocalConnectorFile");async function af(s,e,t){if(t&&e!==t)try{const n=await U.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=xe(n),i=B.join(Be(),r,Ne,"src"),o=B.join(i,e),a=B.join(i,t);F.existsSync(o)&&(F.mkdirSync(B.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(af,"renameLocalConnectorDirectory");async function cf(s,e){try{const t=await U.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=xe(t),r=B.join(Be(),n,Ne,"src",e);if(F.existsSync(r)){const i=B.resolve(Be());if(!B.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(cf,"deleteLocalConnectorDirectory");const aa=[R.DataSource,R.FieldMapping,R.Action,R.Flow,R.Package,R.AppDataSchema,R.AppEventType];class wn{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ra,this.remoteCache=new ra,this.localRepo=new xl(this.localCache),this.remoteRepo=new Pl(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(R.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ia({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await Gu();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new Wu({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(fe.Updated,e=>this.handleLocalEvent(e,fe.Updated)),this.localWatcher.on(fe.Deleted,e=>this.handleLocalEvent(e,fe.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new Hu,this.remoteWatcher.on(Er.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Er.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(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===R.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await $r({connectorId:o});if(!l?.key)return;const u=ef(l);await this.localWatcher?.executeWithPathLock(u,async()=>ia({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 Ds.ConnectorFileDeleted:await of(e,t);break;case Ds.ConnectorDirectoryRenamed:await af(e,t,r);break;case Ds.ConnectorDirectoryDeleted:await cf(e,t);break;default:await rf(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(tf(e.filePath))switch(t){case fe.Updated:await nf(e.filePath);break;case fe.Deleted:await sf(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${Al.toSentenceCase(t)}: ${n.id}`),t){case fe.Updated:await this.updateElement(n,ae.OUTGOING);break;case fe.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=wn.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=wn.getChanges(ae.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===R.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==R.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of aa){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 aa){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 Ae.DELETE:return this.deleteElement(e.element,e.direction);case Ae.CREATE:return this.updateElement(e.element,e.direction);case Ae.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=wn.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 ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:Ae.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:Ae.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:Ae.UPDATE,element:e,direction:n,isConflict:!1}:null}}const Ue=K.join(Jc.tmpdir(),"membrane-mcp-status"),ca=3e4;class lf{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=rs(void 0,e),n=la(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function rs(s,e){try{const t=e||process.cwd();if(!s){const r=la(t);return r.length===0?null:r[0]}const n=Pr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ca)return zt(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ca)return zt(s,t),null}return l}}catch{s&&e&&zt(s,e)}return null}c(rs,"getMcpStatus");function la(s){try{const e=s||process.cwd(),t=xr(e);if(!L.existsSync(Ue))return[];const n=L.readdirSync(Ue),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=rs(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(la,"getAllMcpStatusFiles");function Nr(s){try{const t={...rs(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(Ue)||L.mkdirSync(Ue,{recursive:!0});const n=Pr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Nr,"updateMcpStatus");function zt(s,e){try{const t=e||process.cwd();if(s){const n=Pr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=xr(t);if(L.existsSync(Ue)){const r=L.readdirSync(Ue);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(Ue,i))}}}catch{}}c(zt,"clearMcpStatus");function uf(s,e){const t=rs(s,e);t&&Nr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(uf,"trackToolExecution");function xr(s){return Fc("md5").update(s).digest("hex").slice(0,8)}c(xr,"getCwdHash");function Pr(s,e){const t=xr(e);return K.join(Ue,`mcp-${t}-${s}.json`)}c(Pr,"getStatusFilePath");const Yt={Agent:"agent",Cli:"cli"},x={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 ua{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new lf,this.syncService=new wn,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={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(x.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&U.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(x.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(x.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(x.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(x.SYNCED),e.watch&&(await this.notifier.setState(x.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(x.NOT_INITIALIZED);try{await this.loadConfig(),Ft.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(x.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(x.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(x.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Ft.loadConfig(this.cwd),this.notifier.setConfig(this.currentConfig)}async updateConfig(e){const t={...this.currentConfig,...e};if(!(JSON.stringify(t)!==JSON.stringify(this.currentConfig)))return;await this.stopServices();const r=Ft.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===Yt.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===Yt.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===Yt.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 fa=mi(null);function ff({children:s,membraneCLIService:e}){const{data:t}=yi("/account"),[n,r]=H(x.NOT_INITIALIZED),[i,o]=H([]),[a,l]=H({}),[u,f]=H([]),[d,p]=H(null),y=t?.workspaces?.find(h=>h.workspaceKey===d?.workspaceKey)||null;return Ge(()=>{const h=c(({state:E})=>r(E),"handleStateChanged"),w=c(({stats:E})=>l(E),"handleStatsChanged"),k=c(({log:E})=>f($=>[...$,E]),"handleLogAdded"),_=c(({conflicts:E})=>o(E),"handleConflictsUpdated"),I=c(({config:E})=>p(E),"handleConfigChanged");return e.notifier.on(Q.StateChanged,h),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,k),e.notifier.on(Q.ConflictsChanged,_),e.notifier.on(Q.ConfigChanged,I),e.init(),()=>{e.notifier.off(Q.StateChanged,h),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,k),e.notifier.off(Q.ConflictsChanged,_),e.notifier.off(Q.ConfigChanged,I)}},[]),g(fa.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:d,updateConfig:c(h=>e.updateConfig(h),"updateConfig"),resolveConflicts:c(h=>e.syncWorkspaces(h),"resolveConflicts"),pull:c(h=>e.pullWorkspace(h),"pull"),push:c(h=>e.pushWorkspace(h),"push"),exit:c(()=>e.shutdown(),"exit")},children:s})}c(ff,"MembraneCLIServiceProvider");function Se(){const s=gi(fa);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(Se,"useMembraneCLIService");const da=mi(process.cwd());function df({cwd:s,children:e}){return g(da.Provider,{value:s,children:e})}c(df,"CwdProvider");function hf(){return gi(da)}c(hf,"useCwd");function is({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return g(df,{cwd:n,children:g(Tc,{value:{fetcher:cl()},children:g(ff,{membraneCLIService:t,children:e})})})}c(is,"Layout");const Mr=[{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=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function pf({onExit:s,onComplete:e}){const[t,n]=H(0),[r,i]=H(!1),[o,a]=H(null),[l,u]=H(""),[f,d]=H("");rt((y,h)=>{if(l||f){(h.escape||y==="q"||h.return)&&e();return}if(r)h.return||y===" "?p(o):h.escape&&(i(!1),a(null));else if(h.escape)s();else if(h.upArrow||y==="k")n(Math.max(0,t-1));else if(h.downArrow||y==="j")n(Math.min(Mr.length-1,t+1));else if(h.return||y===" "){const w=Mr[t];a(w),i(!0)}});const p=c(y=>{try{const h=y.addConfig();u(h)}catch(h){d(`Failed to write configuration: ${h.message||h}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return l?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"green",children:"Success"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"green",children:l}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(v,{marginTop:1,paddingLeft:2,children:g(C,{color:"white",children:"[esc/q/enter: exit]"})})]}):f?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"red",children:"Error"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:g(C,{color:"red",children:f})}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Confirmation"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[O(C,{children:["Connect ",g(C,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,children:g(C,{color:"yellow",bold:!0,children:o.actionDescription})}),g(v,{marginTop:2,marginBottom:1,children:O(C,{children:[g(C,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(C,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(C,{color:"cyan",children:"Select Agent"})]})}),O(v,{flexDirection:"column",paddingLeft:2,children:[g(C,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(v,{marginTop:1,flexDirection:"column",children:Mr.map((y,h)=>O(v,{children:[O(C,{color:t===h?"cyan":"white",children:[t===h?"\u25B6 ":" ",y.name]}),O(C,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(pf,"AddMcpServerScreen");function mf(){const[s,e]=H(null),[t,n]=H([]),[r,i]=H(null);return Ge(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.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(mf,"useMcpStatus");function gf(){const{error:s,serverCount:e,allMcpServers:t}=mf(),n=Math.min(100,process.stdout.columns||100);return O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(v,{marginTop:-1,marginBottom:0,flexDirection:"column",children:O(C,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?g(C,{color:"red",children:"error reading status"}):e===0?g(C,{color:"yellow",children:"none"}):g(C,{color:"green",children:e})]})}),!s&&e===0&&g(v,{marginTop:1,children:O(C,{color:"grey",children:["Connect your AI agents to Membrane.",g(Cc,{}),"It will give them tools and context to build integrations."]})}),t.length>0&&g(v,{flexDirection:"column",paddingLeft:2,marginTop:1,children:t.map((r,i)=>g(v,{children:O(C,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"[a: connect an agent]"})})]})}c(gf,"Agent");const os=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function ha(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(ha,"truncateText");function Rr({children:s}){const{state:e,logs:t}=Se();return!e||e===x.NOT_INITIALIZED?O(v,{gap:1,flexDirection:"row",children:[g(Vc,{type:"dots"}),g(C,{children:"Initializing..."})]}):e===x.SETTING_UP?g(v,{gap:1,flexDirection:"row",children:g(C,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===x.ERROR?g(v,{flexDirection:"column",children:t.slice().map((n,r)=>g(C,{color:os(n.type),children:n.message},n.timestamp+r))}):s}c(Rr,"EnsureInitialized");function pa({onExit:s,showEscOption:e=!0}){const[t,n]=H(""),{data:r,error:i,isLoading:o}=yi("/account"),{updateConfig:a}=Se(),l=r?.workspaces,u=o;if(rt((h,w)=>{w.escape&&s?.()}),u)return O(v,{children:[g(vn,{}),g(C,{children:" Fetching workspaces..."})]});if(i)return O(v,{flexDirection:"column",children:[O(C,{color:"red",children:["Error: ",i.message]}),g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]});const f=l?.filter(h=>h.name.toLowerCase().includes(t.toLowerCase()))??[],d=f.map(h=>({label:h.name,value:h.id})),p=d.length,m=l?.length??0;async function y(h){const w=f.find(I=>I.id===h);if(!w)return;const{key:k,secret:_}=w;!k||!_||(await a({workspaceKey:k,workspaceSecret:_}),s?.())}return c(y,"handleSelect"),O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,children:g(C,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),O(v,{marginTop:1,children:[g(C,{children:"Search: "}),g(Gc,{placeholder:"Enter a search query...",onChange:n})]}),m>5&&O(C,{children:["Showing ",p," of ",m," workspaces."]}),g(v,{marginTop:1,children:g(zc,{options:d,onChange:c(h=>{h&&y(h)},"onChange")})}),e&&g(v,{marginTop:1,children:g(C,{color:"grey",children:"Press ESC to go back"})})]})}c(pa,"SelectWorkspace");function yf({currentPat:s,onSubmit:e}){const[t,n]=H(""),[r,i]=H(!1),[o,a]=H(null);return O(v,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(v,{marginTop:-1,marginBottom:1,children:g(C,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(C,{children:"Please provide your Personal Access Token. You can find it here:"}),g(v,{marginTop:1,marginBottom:1,children:g(C,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&g(C,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Yc,{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&&g(v,{marginTop:1,children:O(C,{children:[g(vn,{type:"dots"})," Validating token..."]})}),o&&g(C,{color:"red",children:o})]})}c(yf,"PersonalAccessTokenInput");var Xt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(Xt||{});const wf={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Lr=[Xt.Authenticate,Xt.ConnectWorkspace];function ma({onComplete:s}){const{config:e}=Se(),[t,n]=H(!1),[r,i]=H(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=_i(),l=Lr[r],u=r+1,f=Lr.length,d=Lr.map((y,h)=>{let w="pending";return h<r?w="done":h===r&&(w="current"),{id:y,label:wf[y],status:w}});async function p(y){const h=a&&y===""?a:y,w=new Ei;try{await w.request("/account",{headers:{Authorization:`Bearer ${h}`}}),al(h),i(k=>k+1)}catch(k){console.error(k)}}c(p,"handlePatSubmit");function m(){n(!0),s&&s()}return c(m,"handleWorkspaceSelected"),rt((y,h)=>{o&&h.escape&&s&&s()}),t?g(v,{children:g(C,{children:"\u2705 Setup complete. You are ready to go!"})}):O(v,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(v,{marginTop:-1,marginBottom:1,children:O(C,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",O(C,{color:"cyan",children:["Step ",u," of ",f]}),o&&g(C,{color:"grey",children:" [esc: go back]"})]})}),g(v,{flexDirection:"column",paddingLeft:2,children:d.map(y=>g(bf,{status:y.status,label:y.label},y.id))})]}),l===Xt.Authenticate&&g(yf,{currentPat:a,onSubmit:p}),l===Xt.ConnectWorkspace&&g(pa,{onExit:m,showEscOption:!1})]})}c(ma,"Setup");function bf({status:s,label:e}){return O(v,{children:[O(v,{width:2,children:[s==="current"&&g(vn,{type:"dots"}),s==="done"&&g(C,{children:"\u2705"})]}),g(C,{dimColor:s!=="current",children:e})]})}c(bf,"StepDisplay");function Dr(){const{stats:s}=Se(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:O(v,{flexDirection:"column",children:[g(v,{children:g(v,{width:12,children:g(C,{color:"grey",children:"Elements:"})})}),g(v,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>O(v,{children:[g(v,{width:20,children:O(C,{children:[t,":"]})}),g(C,{color:"green",children:n})]},t))})]})}c(Dr,"ElementStats");const jr=5,Sf=6;function vf(){const{logs:s}=Se(),[e,t]=H(0),n=Math.min(100,process.stdout.columns||100),r=jr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Sf,u=e<s.length-r,f=e>0;return rt((d,p)=>{if(s.length!==0)if(p.upArrow){const m=Math.max(0,s.length-r);t(y=>Math.min(m,y+1))}else p.downArrow?t(m=>Math.max(0,m-1)):(d==="G"||d==="g")&&t(0)}),O(v,{flexDirection:"column",paddingTop:1,children:[O(C,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>jr&&g(C,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((d,p)=>g(v,{marginLeft:1,children:g(C,{color:os(d.type),children:ha(d.message,l)})},d.timestamp+p)),s.length>jr&&O(v,{marginLeft:1,flexDirection:"row",children:[u&&g(C,{color:"grey",children:"\u2191 "}),f&&g(C,{color:"grey",children:"\u2193 "})]})]})}c(vf,"Logs");const as=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Cf(){const{state:s,resolveConflicts:e,exit:t}=Se(),[n,r]=H(0),[i,o]=H(!1),[a,l]=H(!1);return rt((u,f)=>{if(!i){if(f.ctrl&&u.toLowerCase()==="r"){l(!a);return}f.upArrow?r(d=>d>0?d-1:as.length-1):f.downArrow?r(d=>d<as.length-1?d+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(f.return||u===" ")&&(o(!0),as[n].value==="sync"?e({watch:!0}):t())}}),Ge(()=>{s!==x.CONFLICTS&&i&&o(!1)},[s,i]),O(v,{flexDirection:"column",paddingTop:1,children:[g(v,{children:g(v,{flexDirection:"row",gap:2,children:g(C,{bold:!0,color:"white",children:"Conflicts with remote"})})}),g(v,{children:g(C,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),g(v,{marginTop:1,marginLeft:2,children:g(Fr,{isExpanded:a})}),O(v,{marginTop:2,flexDirection:"row",gap:1,children:[g(C,{color:"white",bold:!0,children:"What would you like to do?"}),g(C,{color:"grey",children:"[up/down, enter]"})]}),g(v,{children:i?O(v,{flexDirection:"row",gap:1,children:[g(vn,{type:"dots"}),g(C,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):g(v,{flexDirection:"column",children:as.map((u,f)=>g(v,{flexDirection:"column",children:O(v,{flexDirection:"row",gap:1,children:[g(C,{color:n===f?"cyan":"grey",children:n===f?"\u25B6":" "}),g(C,{color:n===f?"cyan":"grey",bold:n===f,children:u.label})]})},u.value))})})]})}c(Cf,"ResolveChangesUI");const kf={[Ae.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[Ae.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[Ae.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Fr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=Se(),n=5,r=_c(()=>{const i={};return t.forEach(o=>{const a=`${o.type}-${o.direction}`;i[a]||(i[a]=[]),i[a].push(o)}),i},[t]);return g(v,{flexDirection:"column",children:Object.entries(r).map(([i,o])=>{if(o.length===0)return null;const[a,l]=i.split("-"),u=kf[a][l];return O(v,{flexDirection:"column",children:[O(v,{flexDirection:"row",gap:1,children:[O(C,{color:"yellow",children:[u.label," (",o.length,")"]}),g(C,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(f=>g(v,{marginLeft:2,children:O(C,{color:"grey",children:["\u2022 ",f.element.id," (",f.element.relativePath,")"]})},f.element.id)),!s&&o.length>n&&g(v,{marginLeft:2,children:O(C,{color:"cyan",children:["... and ",o.length-n," more",e?" (press Ctrl+R to show all)":""]})}),s&&o.length>n&&e&&g(v,{marginLeft:2,children:g(C,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Fr,"Conflicts");function Tf(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=Se(),i=n?.name,o=i?ha(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Ge(()=>{r({watch:!0})},[]),O(v,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[g(v,{marginTop:-1,marginBottom:1,children:O(v,{flexDirection:"row",gap:1,children:[g(C,{bold:!0,children:"\u{1F504} Workspace"}),O(C,{color:Ef(e),children:[" [",_f(e),"] "]})]})}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Local:"})}),g(C,{color:"grey",children:process.cwd()})]}),O(v,{children:[g(v,{width:12,children:g(C,{color:"grey",children:"Remote:"})}),s?.workspaceKey?O(C,{color:"grey",children:[o," [o: open in console] [w: change]"]}):O(C,{children:[g(C,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===x.CONFLICTS?g(Cf,{}):O(Rs,{children:[g(v,{paddingTop:1,children:g(Dr,{})}),t.length>0&&g(vf,{})]})]})}c(Tf,"Workspace");function _f(s){switch(s){case x.PULLING:return"pulling";case x.PUSHING:return"pushing";case x.CONFLICTS:return"conflicts";case x.SYNCED:return"synced";case x.ERROR:return"error";case x.WATCHING:return"tracking changes";case x.RESOLVING:return"resolving";case x.NOT_SYNCED:return"not synced";case x.INITIALIZED:return"initialized";case x.SETTING_UP:return"setup required";default:return"unknown"}}c(_f,"getStatusDisplay");function Ef(s){switch(s){case x.PULLING:return"yellow";case x.PUSHING:return"yellow";case x.CONFLICTS:return"red";case x.SYNCED:return"green";case x.ERROR:return"red";case x.WATCHING:return"green";case x.RESOLVING:return"yellow";case x.NOT_SYNCED:return"grey";case x.SETTING_UP:return"yellow";default:return"grey"}}c(Ef,"getStatusColor");const Of="https://console.integration.app/w";function Af(){const s=hf(),e=Ec(!0),{exit:t,state:n}=Se(),[r,i]=H(null),o=r??(n===x.SETTING_UP?"setup":"main");rt(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===x.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Ai(s),u=`${Of}/${l}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Hc(`${f} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Ge(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?g(pa,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?g(pf,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?g(ma,{onComplete:c(()=>i(null),"onComplete")},Date.now()):g(Rr,{children:O(v,{flexDirection:"column",children:[g(v,{flexGrow:1,children:g(gf,{})}),g(Tf,{}),g(v,{paddingLeft:2,children:g(C,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Af,"Main");const Qt=kc(process.argv.slice(2)),ga=Qt.cwd?Sc(Qt.cwd):process.cwd(),If=new ua(Yt.Agent,ga);if(Qt.verbose&&b.setVerboseMode(!0),Qt.rps!==void 0){const s=parseInt(Qt.rps,10);!isNaN(s)&&s>0&&s<=1e3?U.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const $f=c(()=>g(is,{cwd:ga,membraneCLIService:If,children:g(Af,{})}),"App");function Nf(){bn(g($f,{}))}c(Nf,"runAgent");function tt(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>tt({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?tt(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]=tt(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(tt)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=tt(s.additionalProperties)),s.required&&(e.required=s.required),e}c(tt,"convertDataSchemaToOpenAPI");function xf(s){const{membraneInterfaces:{actions:e}}=s,t=Pf(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(xf,"generateOpenAPIContent");function Pf(s){const e={};return s.forEach(t=>{const n=Us(Bs(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=tt(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=tt(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Pf,"generateOpenAPISchemas");function Mf(s){const{membraneInterfaces:{actions:e}}=s,t=el(e,"key"),n=new Zc({indentNumberOfSpaces:2,newLine:`
142
- `});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(),Rf(n,t),n.toString()}c(Mf,"generateTypeScriptContent");function Rf(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=Kr(t),r=t?.inputSchema;cs(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Br(t),o=t?.customOutputSchema||t?.outputSchema;cs(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),cs(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),cs(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=Kr(t),r=Br(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Rf,"generateModuleAugmentation");function cs(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&&Lf(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(cs,"generateTypeScriptInterface");function Lf(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=qr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(Lf,"generateTypeScriptProperties");function qr(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?qr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=qr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(qr,"convertJsonSchemaToTypeScript");function Kr(s){return`${Us(Bs(s.key))}Input`}c(Kr,"getInputTypeName");function Br(s){return`${Us(Bs(s.key))}Output`}c(Br,"getOutputTypeName");async function Df(s){const{out:e}=s;await L.promises.mkdir(e,{recursive:!0});const t=jf(s);for(const[n,r]of Object.entries(t)){const i=K.join(e,n);await L.promises.writeFile(i,r,"utf-8")}}c(Df,"generateCode");function jf(s){switch(s.target){case"openapi":return{"openapi.json":xf(s)};case"typescript":return{"generated.d.ts":Mf(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(jf,"generateContent");const Ur=c(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
143
- `),"createExperimentalWarning$1");function Ff(s,e){s.command("codegen").alias("install").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. (Alias: install)").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",Ur()).addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${T.gray("\u25B8")} ${T.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Ur()].join(`
144
- `)).action(async t=>{try{console.warn(Ur()),console.error(T.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await qf(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 Df(r),console.error(T.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(T.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Ff,"setupCodegenCommand");async function qf(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(R.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(qf,"loadMembraneInterfaces");function Kf(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(`
145
- `)).action(t=>{t.key&&t.secret?Ft.saveToFile({workspaceKey:t.key,workspaceSecret:t.secret})?(console.error("\u2705 Configuration saved to membrane.config.yml"),process.exit(0)):(console.error("Error writing configuration file"),process.exit(1)):t.key||t.secret?(console.error("Error: Both --key and --secret must be provided for non-interactive mode"),process.exit(1)):bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(ma,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(Kf,"setupInitCommand");async function ya(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),Ks.sign(n,e)}c(ya,"generateMcpAccessToken");async function Bf(s,e){return(await Ws.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(Bf,"fetchOpenApiSchema");function We(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return We(o,e,t,n)}return W.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]=We(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=We(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=We(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?We(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.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(We,"convertOpenApiSchemaToZod");function wa(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(wa,"extractPathParameters");function Uf(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={},p={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")d[y.name]=We(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const h=y.required===!0;p[y.name]=We(y.schema,h,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(d).length>0&&(f.params=W.object(d).describe("Path parameters")),Object.keys(p).length>0&&(f.query=W.object(p).describe("Query parameters")),s.requestBody&&s.requestBody.content){const y=s.requestBody.required===!0;if(s.requestBody.content["application/json"]){const h=s.requestBody.content["application/json"].schema;h?f.body=We(h,y,o).describe("Request body (JSON)"):f.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?f.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):f.body=W.any().describe("Request body")}const m=Object.keys(f).length>0?W.object(f):W.object({});return{name:l,description:u,parameters:m,async execute(y){try{const h=wa(e);if(h.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const N=h.filter(D=>!(D in y.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[N,D]of Object.entries(y.params)){const A=`{${N}}`;w.includes(A)&&(w=w.replace(A,String(D)))}const k=wa(w);if(k.length>0)throw new Error(`Unresolved path parameters: ${k.join(", ")}`);const _=new URLSearchParams;if(y.query)for(const[N,D]of Object.entries(y.query))D!=null&&_.append(N,String(D));_.toString()&&(w+=`?${_.toString()}`);const I=await ya(r,i,a),E={method:t.toUpperCase(),headers:{Authorization:`Bearer ${I}`}};y.body&&t.toLowerCase()!=="get"&&(s.requestBody?.content?.["application/json"]?(E.headers["Content-Type"]="application/json",E.data=y.body):s.requestBody?.content?.["application/octet-stream"]?(E.headers["Content-Type"]="application/octet-stream",E.data=y.body):s.requestBody?.content?.["text/plain"]?(E.headers["Content-Type"]="text/plain",E.data=y.body):(E.headers["Content-Type"]="application/json",E.data=y.body));const $=await Ws.request({url:w,...E});return{content:[{type:"text",text:$.data===""?"":JSON.stringify($.data,null,2)}]}}catch(h){return Ws.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}c(Uf,"createApiTool");function Wf(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=Uf(f,a,u,e,t,n,o,r);i.push(d)}}return i}c(Wf,"convertOpenApiToTools");function Jf(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(`
146
- `)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=Cn();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||Hs,n=await ya(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await Bf(t,n),i=Wf(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new tl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
141
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=us(e),n=Nt(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=us(e),n=Nt(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 ha(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new la||null,prettyErrors:e}}c(ha,"parseOptions");function Zu(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(e),o=Array.from(i.compose(r.parse(s)));if(n&&t)for(const a of o)a.errors.forEach(ss(s,t)),a.warnings.forEach(ss(s,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}c(Zu,"parseAllDocuments");function pa(s,e={}){const{lineCounter:t,prettyErrors:n}=ha(e),r=new Pr(t?.addNewLine),i=new Or(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 st(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(o.errors.forEach(ss(s,t)),o.warnings.forEach(ss(s,t))),o}c(pa,"parseDocument");function ed(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=pa(s,t);if(!r)return null;if(r.warnings.forEach(i=>Eo(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(ed,"parse");function td(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 Ze(s)&&!n?s.toString(t):new Bt(s,n,t).toString(t)}c(td,"stringify");var nd=Object.freeze({__proto__:null,Alias:qn,CST:Yu,Composer:Or,Document:Bt,Lexer:ca,LineCounter:la,Pair:se,Parser:Pr,Scalar:R,Schema:Ls,YAMLError:kr,YAMLMap:ue,YAMLParseError:st,YAMLSeq:Ue,YAMLWarning:Go,isAlias:Be,isCollection:z,isDocument:Ze,isMap:St,isNode:Y,isPair:V,isScalar:H,isSeq:Ct,parse:ed,parseAllDocuments:Zu,parseDocument:pa,stringify:td,visit:et,visitAsync:Fn});const de={Updated:"updated",Deleted:"deleted",Stopped:"stopped"},sd={ignored:_l,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 rd extends nr{static{c(this,"LocalElementWatcher")}constructor(e){super(),this.options=e,this.membraneDir=dt(this.options.cwd),this.lockTimeoutMs=this.options.lockTimeoutMs??1e3}isWatching=!1;watcher;membraneDir;contentCache={};ignoredPaths=new Set;lockTimeoutMs;async start(){this.isWatching||(L.existsSync(this.membraneDir)||L.mkdirSync(this.membraneDir,{recursive:!0}),this.initializeContentCache(),this.watcher=nl.watch(this.membraneDir,sd),this.watcher.on("add",e=>this.handleFileSystemEvent(de.Updated,e)).on("change",e=>this.handleFileSystemEvent(de.Updated,e)).on("unlink",e=>this.handleFileSystemEvent(de.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(de.Stopped))}getCwd(){return this.options.cwd}async executeWithPathLock(e,t){const n=K.resolve(e);this.ignoredPaths.add(n);try{await t()}finally{setTimeout(()=>{this.ignoredPaths.delete(n)},this.lockTimeoutMs)}}isPathLocked(e){const t=K.resolve(e);if(this.ignoredPaths.has(t))return!0;for(const n of this.ignoredPaths)if(t.startsWith(n+K.sep))return!0;return!1}clearAllLocks(){this.ignoredPaths.clear()}handleFileSystemEvent(e,t){const n=K.relative(this.membraneDir,t);if(this.isPathLocked(t))return;if(e===de.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 L.readFileSync(e,"utf8")}processFileEvent(e,t){const n=K.relative(this.membraneDir,e);let r;try{r=t?nd.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 el.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(){L.existsSync(this.membraneDir)&&this.scanDirectoryForCache(this.membraneDir)}scanDirectoryForCache(e){const t=L.readdirSync(e,{withFileTypes:!0});for(const n of t){const r=K.join(e,n.name);if(n.isDirectory())this.scanDirectoryForCache(r);else if(n.isFile())try{const i=L.readFileSync(r,"utf8"),o=K.relative(this.membraneDir,r);this.updateCache(o,i)}catch{}}}}var Rr=(s=>(s.Updated="updated",s.ConnectorFileUpdated="connector-file-updated",s.Connected="connected",s.Disconnected="disconnected",s.Error="error",s))(Rr||{});const id={debounceMs:2e3,reconnectIntervalMs:5e3,maxReconnectAttempts:1/0,maxBackoffMs:6e4,connectionTimeoutMs:3e5};class od extends nr{static{c(this,"RemoteElementWatcher")}constructor(e=id){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 B.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 sl(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!==Uc.ElementUpdate)return;const{elementId:t,elementType:n,data:r={}}=e;if(!(!t||!n)){if(n===x.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 ma{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())}}async function ad(s="full"){const e={};b.info("[connectors] Getting remote workspace data");const t=await B.withClient(n=>n.integrations.findAll());e.integration=t?.map(n=>Mr("integration",n))??[];for(const n of Object.keys(ce)){const r=ce[n];if(r.exportable===!1)continue;const i=[];b.info(`[connectors] Reading ${r.elements} from remote workspace`);const o=await B.withClient(a=>a[r.elements].findAll());if(o&&i.push(...o.map(a=>Mr(n,a))),r.integrationSpecific&&t)for(const a of t){const l=await B.withClient(u=>u[r.elements].findAll({integrationId:a.id}));l&&i.push(...l.map(u=>(u.integrationKey=a.key,Mr(n,u))))}i.length>0&&s=="full"&&(console.table(i.map(a=>({key:a.key,integrationKey:a.integrationKey,universal:!a.integrationKey})).reduce((a,l)=>(a||(a={}),a[l.key]||(a[l.key]={}),l.universal&&(a[l.key].universal=!0),l.integrationKey&&(a[l.key].integration?a[l.key].integration+=` ${l.integrationKey}`:a[l.key].integration=l.integrationKey),a),{})),console.groupEnd()),e[n]=i}return b.success("[connectors] Remote workspace data retrieved successfully"),e}c(ad,"getWorkspaceData");function Mr(s,e){return e=Ul(e),ce[s].exportCleanup?ce[s].exportCleanup(e):e}c(Mr,"cleanUpForExport");const xt="connectors",Pe="development",Lr={};async function cd(){const s=await ad("minified"),t=(await B.withClient(l=>l.get("org-workspace-id"))).id,n={};b.info("[connectors] Loading custom connectors");const r=await B.withClient(l=>l.get(`/connectors?workspaceId=${t}`));b.info("[connectors] Loading public connectors"),s.connector=r;const i=Je(),a=(F.existsSync(i)?F.readdirSync(i):[]).filter(l=>{if(l.startsWith("."))return!1;const u=U.join(i,l);try{return F.statSync(u).isDirectory()}catch{return!1}});for(const l of a){b.info(`[connectors] Loading connector from: ${l}`);const u=F.readdirSync(U.join(i,l)),d=await Dr(l);if(!d)continue;if("baseUri"in d&&delete d.baseUri,d.uuid&&s.connector?.find(h=>h.uuid==d.uuid))n[d.id]=s.connector.find(h=>h.uuid==d.uuid).id,b.info(`[connectors] Matched ${d.name} uuid: ${d.uuid}`);else if(!n[d.id]){let h=!1;try{const g=await jr({connectorId:d.id});g&&g.isPublic&&(h=!0)}catch{}if(!h){b.info(`[connectors] Creating custom connector ${d.name} (${d.key})`);const g=await B.withClient(y=>y.post("connectors",{...d,workspaceId:t}));n[d.id]=g.id}}const f=u.filter(h=>F.statSync(U.join(i,l,h)).isDirectory());for(const h of f)await dd({connector:d,version:h,connectorId:n[d.id]})}return n}c(cd,"pushConnectors");async function ga({connectorId:s,connectorVersion:e,allConnectors:t,pulledConnectors:n,pulledConnectorVersions:r}){if(!s||r[s]?.has(e))return;const i=xi(),o=await jr({connectorId:s});if(!o.isPublic||t){if(!o?.key){b.error(`[connectors] Connector ${s} has no key. Skipping..`);return}n.has(s)||(await fd({basePath:i,connector:o}),n.add(s)),r[s]||(r[s]=new Set),r[s].has(e)||(await hd({connector:o,connectorVersion:e,basePath:i}),r[s].add(e))}}c(ga,"pullRemoteConnector");function Je(){const s=tr();return U.join(s.membraneDirPath,xt)}c(Je,"getConnectorsPath");async function Dr(s){const e=U.join(Je(),s,`${s}.yml`);return ir(e,!1)}c(Dr,"readConnector");async function ld(s,e){return b.info(`[connectors] Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=F.createWriteStream(e),i=rl("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=U.join(s,a),u=F.statSync(l);u.isFile()?i.file(l,{name:a}):u.isDirectory()&&i.directory(l,a)}i.finalize()})}c(ld,"createZipArchive");async function ud(s,e){return b.info(`[connectors] Unzipping into ${e}`),new Promise((t,n)=>{const r=ol.Parse();r.on("entry",i=>{const o=i.path;if(i.type==="Directory"){const l=U.join(e,o);F.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=U.join(e,o),u=U.dirname(l);F.mkdirSync(u,{recursive:!0});const d=F.createWriteStream(l);i.pipe(d),d.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(ud,"extractZipArchive");async function dd({connector:s,version:e,connectorId:t}){const n=U.join(Je(),Re(s),ya(e)),r=U.join(n,"src"),i=U.join(n,"src.zip"),o=F.existsSync(i);if(F.existsSync(r)&&(b.info(`[connectors] Archiving source code for ${s.name} version ${e}`),await ld(r,i)),!F.existsSync(i)){b.warning(`[connectors] No source code found for ${s.name} version ${e}`);return}try{const a=new il;if(a.append("file",F.createReadStream(i),"file.zip"),b.info(`[connectors] Pushing connector version ${e} for ${s.name}`),e==Pe)b.info(`[connectors] Uploading connector ${t}`),await B.withClient(l=>l.post(`connectors/${t}/upload`,a,{headers:{...a.getHeaders()}}));else{if(a.append("version",e),a.append("changelog","Imported Version"),(await B.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 B.withClient(u=>u.post(`connectors/${t}/publish-version`,a,{headers:{...a.getHeaders()}}))}b.success(`Successfully pushed connector version ${e} for ${s.name}`)}catch(a){b.error(`Error pushing connector version ${e} for ${s.name}: ${a}`)}finally{!o&&F.existsSync(i)&&(b.info(`[connectors] Cleaning up temporary zip file for ${s.name} version ${e}`),F.unlinkSync(i))}}c(dd,"pushConnectorVersion");async function jr({connectorId:s}){if(s){if(Lr[s])return Lr[s];try{const e=await B.withClient(t=>t.get(`connectors/${s}`));return Lr[s]=e,e}catch(e){return b.error(`[connectors] Failed to get connector ${s}: ${e}`),null}}}c(jr,"getConnector");async function fd({basePath:s,connector:e}){const t=Re(e),n=U.join(s,xt,t);F.mkdirSync(n,{recursive:!0});const r=U.join(n,`${Re(e)}.yml`);F.writeFileSync(r,Wt.dump(e)),b.info(`[connectors] Pulled connector ${e.name}`)}c(fd,"pullConnector");async function hd({connector:s,connectorVersion:e,basePath:t}){const n=Re(s),r=ya(e),i=U.join(t,"connectors",n,r),o=await B.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=U.join(i,"src.zip");if(F.writeFileSync(a,o),!e){const l=U.join(i,"src");F.mkdirSync(l,{recursive:!0}),await ud(o,l)}b.info(`[connectors] Pulled connector version: ${s.name} (${r})`)}c(hd,"pullConnectorVersion");function Re(s){return s.key}c(Re,"getConnectorDirName");function ya(s){return s??Pe}c(ya,"getConnectorVersionDirName");function pd(s){const e=xi(),t=Re(s);return U.join(e,xt,t)}c(pd,"getConnectorDirPath");function md(s){return s.match(`${xt}/[^/]+/${Pe}/src/.*`)!==null}c(md,"isConnectorSourceFile");async function gd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(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 B.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(gd,"putConnectorFile");async function yd(s){const e=s.match(`${xt}/([^/]+)/${Pe}/src/(.*)`);if(!e)return;const t=e[1],n=e[2],r=await Dr(t);if(!r){b.warning(`[connectors] Connector ${t} not found. Ignoring file change`);return}const i=r.id;await B.withClient(o=>o.delete(`connectors/${i}/files/${n}`)),b.info(`[connectors] Deleted file ${n} for connector ${r.name}`)}c(yd,"deleteConnectorFile");async function wd(s,e){try{const t=await B.withClient(o=>o.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=await B.withClient(o=>o.get(`connectors/${s}/files/${e}`)),r=Re(t),i=U.join(Je(),r,Pe,"src",e);F.mkdirSync(U.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}`)}}c(wd,"pullConnectorFile");async function bd(s,e){const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);F.existsSync(r)&&(F.unlinkSync(r),b.info(`[connectors] Deleted file ${e} for connector ${n}`))}c(bd,"deleteLocalConnectorFile");async function Sd(s,e,t){if(t&&e!==t)try{const n=await B.withClient(l=>l.get(`connectors/${s}`));if(!n){b.warning(`[connectors] Connector ${s} not found`);return}const r=Re(n),i=U.join(Je(),r,Pe,"src"),o=U.join(i,e),a=U.join(i,t);F.existsSync(o)&&(F.mkdirSync(U.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(Sd,"renameLocalConnectorDirectory");async function Cd(s,e){try{const t=await B.withClient(i=>i.get(`connectors/${s}`));if(!t){b.warning(`[connectors] Connector ${s} not found`);return}const n=Re(t),r=U.join(Je(),n,Pe,"src",e);if(F.existsSync(r)){const i=U.resolve(Je());if(!U.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(Cd,"deleteLocalConnectorDirectory");const wa=[x.DataSource,x.FieldMapping,x.Action,x.Flow,x.Package,x.AppDataSchema,x.AppEventType];class En{static{c(this,"ElementSyncService")}localWatcher=void 0;remoteWatcher=void 0;notifier;changes=[];localCache;remoteCache;localRepo;remoteRepo;pulledConnectors=new Set;pulledConnectorVersions={};constructor(){this.notifier=Oe,this.localCache=new ma,this.remoteCache=new ma,this.localRepo=new Hl(this.localCache),this.remoteRepo=new Vl(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(x.Integration).map(n=>n.data);for(const n of t){const r=n.connectorId,i=n.connectorVersion;r&&await ga({connectorId:r,connectorVersion:i,allConnectors:e,pulledConnectors:this.pulledConnectors,pulledConnectorVersions:this.pulledConnectorVersions})}}async pushConnectors(){const e=await cd();this.remoteRepo.setConnectorsMapping(e)}getHandler(e){return e===ae.INCOMING?this.localRepo:(this.remoteRepo.setSourceCache(this.localCache),this.remoteRepo)}getCache(e){return e===ae.INCOMING?this.localCache:this.remoteCache}async startWatching(){this.localWatcher=new rd({cwd:process.cwd(),lockTimeoutMs:1e3}),this.localWatcher.on(de.Updated,e=>this.handleLocalEvent(e,de.Updated)),this.localWatcher.on(de.Deleted,e=>this.handleLocalEvent(e,de.Deleted)),await this.localWatcher.start(),b.success("[local] Tracking changes.."),this.remoteWatcher=new od,this.remoteWatcher.on(Rr.Updated,({elementId:e,elementType:t})=>this.handleRemoteElementEvent(e,t)),this.remoteWatcher.on(Rr.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(ae.INCOMING)}] Deleted: ${o.id}`),this.localWatcher?.executeWithPathLock(o.absolutePath,()=>this.deleteElement(o,ae.INCOMING))):void 0}if(b.info(`[${this.getDirectionLabel(ae.INCOMING)}] Updated: ${n.id}`),await this.localWatcher?.executeWithPathLock(n.absolutePath,async()=>this.updateElement(n,ae.INCOMING)),t===x.Integration){const o=n.data.connectorId,a=n.data.connectorVersion,l=await jr({connectorId:o});if(!l?.key)return;const u=pd(l);await this.localWatcher?.executeWithPathLock(u,async()=>ga({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 Js.ConnectorFileDeleted:await bd(e,t);break;case Js.ConnectorDirectoryRenamed:await Sd(e,t,r);break;case Js.ConnectorDirectoryDeleted:await Cd(e,t);break;default:await wd(e,t);break}}catch(i){b.error(`[sync] Error handling remote connector file event: ${i}`)}}async handleLocalEvent(e,t){try{if(md(e.filePath))switch(t){case de.Updated:await gd(e.filePath);break;case de.Deleted:await yd(e.filePath);break}else{let n=X.fromPathAndData(e.filePath,e.data);if(!n){const r=X.idFromPath(e.filePath);if(!r||(n=this.remoteCache.get(r),!n))return}switch(b.info(`[${this.getDirectionLabel(ae.OUTGOING)}] ${Bl.toSentenceCase(t)}: ${n.id}`),t){case de.Updated:await this.updateElement(n,ae.OUTGOING);break;case de.Deleted:await this.deleteElement(n,ae.OUTGOING);break}}}catch(n){b.error(`[sync] Error handling local event: ${n}`)}}detectIncomingChanges(){this.clearChanges();const e=En.getChanges(ae.INCOMING,this.remoteCache,this.localCache);return this.updateChanges(e),e}detectOutgoingChanges(){this.clearChanges();const e=En.getChanges(ae.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===x.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===ae.INCOMING?this.detectIncomingChanges():this.detectOutgoingChanges(),this.changes=this.changes.filter(r=>r.element.type!==x.Integration)),b.info("[resolver] Resolving universal elements");const t=this.changes.filter(r=>!r.element.hasParent());for(const r of wa){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 wa){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 $e.DELETE:return this.deleteElement(e.element,e.direction);case $e.CREATE:return this.updateElement(e.element,e.direction);case $e.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),d=n.get(l),f=En.detectChangeForElement(u,d,e);f&&a.push(f)}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 ae.INCOMING:return"local\u2190remote";case ae.OUTGOING:return"local\u2192remote"}}static detectChangeForElement(e,t,n){return e&&!t?{type:$e.CREATE,element:e,direction:n,isConflict:!1}:!e&&t?{type:$e.DELETE,element:t,direction:n,isConflict:!0}:e&&t&&!e.isEqual(t)?{type:$e.UPDATE,element:e,direction:n,isConflict:!1}:null}}const He=K.join(al.tmpdir(),"membrane-mcp-status"),ba=3e4;class vd{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=ds(void 0,e),n=Sa(e);t&&Oe.setMcpStatus(t),await Oe.setMcpServers(n)}catch{b.error("Failed to check MCP status")}}}function ds(s,e){try{const t=e||process.cwd();if(!s){const r=Sa(t);return r.length===0?null:r[0]}const n=Kr(s,t);if(L.existsSync(n)){const r=L.statSync(n),i=new Date;if(i.getTime()-r.mtime.getTime()>ba)return tn(s,t),null;const a=L.readFileSync(n,"utf8"),l=JSON.parse(a);if(l.isRunning){const u=new Date(l.lastActivity).getTime();if(i.getTime()-u>ba)return tn(s,t),null}return l}}catch{s&&e&&tn(s,e)}return null}c(ds,"getMcpStatus");function Sa(s){try{const e=s||process.cwd(),t=qr(e);if(!L.existsSync(He))return[];const n=L.readdirSync(He),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=ds(a,e);l&&r.push(l)}}return r.sort((i,o)=>new Date(o.startTime).getTime()-new Date(i.startTime).getTime())}catch{return[]}}c(Sa,"getAllMcpStatusFiles");function Fr(s){try{const t={...ds(s.processId,s.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:s.processId,cwd:s.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...s};L.existsSync(He)||L.mkdirSync(He,{recursive:!0});const n=Kr(s.processId,s.cwd);L.writeFileSync(n,JSON.stringify(t,null,2))}catch{}}c(Fr,"updateMcpStatus");function tn(s,e){try{const t=e||process.cwd();if(s){const n=Kr(s,t);L.existsSync(n)&&L.unlinkSync(n)}else{const n=qr(t);if(L.existsSync(He)){const r=L.readdirSync(He);for(const i of r)i.match(new RegExp(`^mcp-${n}-\\d+\\.json$`))&&L.unlinkSync(K.join(He,i))}}}catch{}}c(tn,"clearMcpStatus");function kd(s,e){const t=ds(s,e);t&&Fr({processId:s,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}c(kd,"trackToolExecution");function qr(s){return tl("md5").update(s).digest("hex").slice(0,8)}c(qr,"getCwdHash");function Kr(s,e){const t=qr(e);return K.join(He,`mcp-${t}-${s}.json`)}c(Kr,"getStatusFilePath");const nn={Agent:"agent",Cli:"cli"},P={NOT_INITIALIZED:"not_initialized",SETTING_UP:"setting_up",INITIALIZED:"initialized",NOT_SYNCED:"not_synced",PULLING:"pulling",PUSHING:"pushing",RESOLVING:"resolving",CONFLICTS:"conflicts",SYNCED:"synced",WATCHING:"watching",ERROR:"error"};class Ca{static{c(this,"MembraneCLIService")}constructor(e,t,n=()=>process.exit(0)){this.mode=e,this.cwd=t,this.onShutdown=n,this.notifier=Oe,this.mcpStatusService=new vd,this.syncService=new En,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={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PULLING),await this.syncService.fetchElements(),this.syncService.detectIncomingChanges(),this.syncService.needsForcedSync()&&!e.force)return this.notifier.setState(P.CONFLICTS);await this.syncService.pullConnectors(e.allConnectors),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to pull workspace: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async pushWorkspace(e={}){try{if(b.setVerboseMode(!!e.verbose),e.rps!==void 0&&B.init({maxRequestsPerSecond:e.rps}),await this.notifier.setState(P.PUSHING),await this.syncService.fetchElements(),this.syncService.detectOutgoingChanges(),this.syncService.needsForcedSync()&&!e.force)return await this.notifier.setState(P.CONFLICTS);await this.syncService.pushConnectors(),await this.syncWorkspaces(e)}catch(t){b.error(`Failed to push workspace: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}finally{return e.saveLogs&&b.saveLogsToFile(),e?.onComplete?.()}}async syncWorkspaces(e={}){try{e.verbose!==void 0&&b.setVerboseMode(!!e.verbose),await this.notifier.setState(P.RESOLVING),this.syncService.needsSync()&&await this.syncService.resolveChanges();const t=await this.syncService.getStats();this.notifier.setStats(t),await this.notifier.setState(P.SYNCED),e.watch&&(await this.notifier.setState(P.WATCHING),await this.syncService.startWatching())}catch(t){b.error(`Failed to sync local and remote workspaces: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error")}}async init({force:e=!1}={}){if(!(this.initialized&&!e)){await this.notifier.setState(P.NOT_INITIALIZED);try{await this.loadConfig(),Qe.isCacheDefined()?(await this.initServices(),this.initialized=!0,await this.notifier.setState(P.INITIALIZED)):(this.initialized=!1,await this.notifier.setState(P.SETTING_UP))}catch(t){b.error(`Failed to initialize services: ${t}`),await this.notifier.setState(P.ERROR),b.saveLogsToFile("error"),this.onShutdown()}}}async loadConfig(){this.currentConfig=Qe.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=Qe.updateConfig(t);this.currentConfig=r,await this.init({force:!0})}async shutdown(){!this.initialized||this.isShuttingDown||(this.isShuttingDown=!0,this.mode===nn.Agent&&(await this.notifier.cleanup(),await this.mcpStatusService.stop()),this.initialized=!1,this.onShutdown())}async initServices(){this.mode===nn.Agent&&(await this.notifier.connectToRemote(),await this.mcpStatusService.start()),this.syncService.clear()}async stopServices(){this.mode===nn.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 va=Bs(null);function Td({children:s,membraneCLIService:e}){const{data:t}=Ei("/account"),[n,r]=J(P.NOT_INITIALIZED),[i,o]=J([]),[a,l]=J({}),[u,d]=J([]),[f,h]=J(null),y=t?.workspaces?.find(p=>p.workspaceKey===f?.workspaceKey)||null;return Fe(()=>{const p=c(({state:I})=>r(I),"handleStateChanged"),w=c(({stats:I})=>l(I),"handleStatsChanged"),k=c(({log:I})=>d($=>[...$,I]),"handleLogAdded"),E=c(({conflicts:I})=>o(I),"handleConflictsUpdated"),O=c(({config:I})=>h(I),"handleConfigChanged");return e.notifier.on(Q.StateChanged,p),e.notifier.on(Q.StatsChanged,w),e.notifier.on(Q.LogAdded,k),e.notifier.on(Q.ConflictsChanged,E),e.notifier.on(Q.ConfigChanged,O),e.init(),()=>{e.notifier.off(Q.StateChanged,p),e.notifier.off(Q.StatsChanged,w),e.notifier.off(Q.LogAdded,k),e.notifier.off(Q.ConflictsChanged,E),e.notifier.off(Q.ConfigChanged,O)}},[]),m(va.Provider,{value:{state:n,stats:a,logs:u,currentWorkspace:y,conflicts:i,config:f,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(Td,"MembraneCLIServiceProvider");function fe(){const s=Us(va);if(!s)throw new Error("useMembraneCLIService must be used within MembraneCLIServiceProvider");return s}c(fe,"useMembraneCLIService");const ka=Bs(process.cwd());function Ed({cwd:s,children:e}){return m(ka.Provider,{value:s,children:e})}c(Ed,"CwdProvider");function _d(){return Us(ka)}c(_d,"useCwd");function sn({cwd:s,children:e,membraneCLIService:t}){const n=s||process.cwd();return m(Ed,{cwd:n,children:m(Dc,{value:{fetcher:kl()},children:m(Td,{membraneCLIService:t,children:e})})})}c(sn,"Layout");const Br=[{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=K.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(L.existsSync(s))try{t=JSON.parse(L.readFileSync(s,"utf8"))}catch{t={}}const n={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return L.writeFileSync(s,JSON.stringify(n,null,2)),`MCP server configuration added to ${s}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:c(()=>{const s=K.join(process.cwd(),".cursor"),e=K.join(s,"mcp.json");L.existsSync(s)||L.mkdirSync(s);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let n={};if(L.existsSync(e))try{n=JSON.parse(L.readFileSync(e,"utf8"))}catch{n={}}const r={...n,mcpServers:{...n.mcpServers,...t.mcpServers}};return L.writeFileSync(e,JSON.stringify(r,null,2)),`MCP server configuration added to ${e}`},"addConfig")}];function Id({onExit:s,onComplete:e}){const[t,n]=J(0),[r,i]=J(!1),[o,a]=J(null),[l,u]=J(""),[d,f]=J("");Xe((y,p)=>{if(l||d){(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(Br.length-1,t+1));else if(p.return||y===" "){const w=Br[t];a(w),i(!0)}});const h=c(y=>{try{const p=y.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),g=Math.min(80,process.stdout.columns||80);return l?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"green",children:"Success"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"green",children:l}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),m(S,{marginTop:1,paddingLeft:2,children:m(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"red",children:"Error"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:m(v,{color:"red",children:d})}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):r&&o?_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Confirmation"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[_(v,{children:["Connect ",m(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),m(S,{marginTop:1,children:m(v,{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(v,{color:"yellow",bold:!0,children:o.actionDescription})}),m(S,{marginTop:2,marginBottom:1,children:_(v,{children:[m(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",m(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:g,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",m(v,{color:"cyan",children:"Select Agent"})]})}),_(S,{flexDirection:"column",paddingLeft:2,children:[m(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),m(S,{marginTop:1,children:m(v,{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:Br.map((y,p)=>_(S,{children:[_(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",y.name]}),_(v,{color:"grey",children:[" \u2014 ",y.description]})]},y.id))})]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})}c(Id,"AddMcpServerScreen");function Ad(){const[s,e]=J(null),[t,n]=J([]),[r,i]=J(null);return Fe(()=>{const o=c(({status:l})=>{e(l),i(null)},"handleMcpStatusChanged"),a=c(({servers:l})=>{n(l),i(null)},"handleMcpServersChanged");return Oe.on(Q.McpStatusChanged,o),Oe.on(Q.McpServersChanged,a),()=>{Oe.off(Q.McpStatusChanged,o),Oe.off(Q.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(Ad,"useMcpStatus");function Od(){const{error:s,serverCount:e,allMcpServers:t}=Ad(),n=Math.min(100,process.stdout.columns||100);return _(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[m(S,{marginTop:-1,marginBottom:0,flexDirection:"column",children:_(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",s?m(v,{color:"red",children:"error reading status"}):e===0?m(v,{color:"yellow",children:"none"}):m(v,{color:"green",children:e})]})}),!s&&e===0&&m(S,{marginTop:1,children:_(v,{color:"grey",children:["Connect your AI agents to Membrane.",m(Mc,{}),"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:_(v,{color:"grey",children:["#",i+1," ",r.agentName,": ",r.totalRequests," calls"]})},r.processId))}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"[a: connect an agent]"})})]})}c(Od,"Agent");const fs=c(s=>{switch(s){case"error":return"red";case"success":return"green";case"warning":return"yellow";default:return}},"getLogColor");function Ta(s,e){return e<3?s.slice(0,Math.max(0,e)):s.length<=e?s:`${s.slice(0,e-3)}...`}c(Ta,"truncateText");function Ur({children:s}){const{state:e,logs:t}=fe();return!e||e===P.NOT_INITIALIZED?_(S,{gap:1,flexDirection:"row",children:[m(ll,{type:"dots"}),m(v,{children:"Initializing..."})]}):e===P.SETTING_UP?m(S,{gap:1,flexDirection:"row",children:m(v,{children:"No workspace selected. Please run `membrane init` to select a workspace."})}):e===P.ERROR?m(S,{flexDirection:"column",children:t.slice().map((n,r)=>m(v,{color:fs(n.type),children:n.message},n.timestamp+r))}):s}c(Ur,"EnsureInitialized");function Ea({onExit:s,showEscOption:e=!0}){const[t,n]=J(""),{data:r,error:i,isLoading:o}=Ei("/account"),{updateConfig:a}=fe(),l=r?.workspaces,u=o;if(Xe((p,w)=>{w.escape&&s?.()}),u)return _(S,{children:[m(An,{}),m(v,{children:" Fetching workspaces..."})]});if(i)return _(S,{flexDirection:"column",children:[_(v,{color:"red",children:["Error: ",i.message]}),m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]});const d=l?.filter(p=>p.name.toLowerCase().includes(t.toLowerCase()))??[],f=d.map(p=>({label:p.name,value:p.id})),h=f.length,g=l?.length??0;async function y(p){const w=d.find(O=>O.id===p);if(!w)return;const{key:k,secret:E}=w;!k||!E||(await a({workspaceKey:k,workspaceSecret:E}),s?.())}return c(y,"handleSelect"),_(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,children:m(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),_(S,{marginTop:1,children:[m(v,{children:"Search: "}),m(ul,{placeholder:"Enter a search query...",onChange:n})]}),g>5&&_(v,{children:["Showing ",h," of ",g," workspaces."]}),m(S,{marginTop:1,children:m(dl,{options:f,onChange:c(p=>{p&&y(p)},"onChange")})}),e&&m(S,{marginTop:1,children:m(v,{color:"grey",children:"Press ESC to go back"})})]})}c(Ea,"SelectWorkspace");function $d({currentPat:s,onSubmit:e}){const[t,n]=J(""),[r,i]=J(!1),[o,a]=J(null);return _(S,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[m(S,{marginTop:-1,marginBottom:1,children:m(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),m(v,{children:"Please provide your Personal Access Token. You can find it here:"}),m(S,{marginTop:1,marginBottom:1,children:m(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&m(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),m(Ni,{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:_(v,{children:[m(An,{type:"dots"})," Validating token..."]})}),o&&m(v,{color:"red",children:o})]})}c($d,"PersonalAccessTokenInput");var rn=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(rn||{});const Nd={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},Wr=[rn.Authenticate,rn.ConnectWorkspace];function _a({onComplete:s}){const{config:e}=fe(),[t,n]=J(!1),[r,i]=J(0),o=!!(e?.workspaceKey&&e?.workspaceSecret),a=Ri(),l=Wr[r],u=r+1,d=Wr.length,f=Wr.map((y,p)=>{let w="pending";return p<r?w="done":p===r&&(w="current"),{id:y,label:Nd[y],status:w}});async function h(y){const p=a&&y===""?a:y,w=new Mi;try{await w.request("/account",{headers:{Authorization:`Bearer ${p}`}}),vl(p),i(k=>k+1)}catch(k){console.error(k)}}c(h,"handlePatSubmit");function g(){n(!0),s&&s()}return c(g,"handleWorkspaceSelected"),Xe((y,p)=>{o&&p.escape&&s&&s()}),t?m(S,{children:m(v,{children:"\u2705 Setup complete. You are ready to go!"})}):_(S,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[m(S,{marginTop:-1,marginBottom:1,children:_(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",_(v,{color:"cyan",children:["Step ",u," of ",d]}),o&&m(v,{color:"grey",children:" [esc: go back]"})]})}),m(S,{flexDirection:"column",paddingLeft:2,children:f.map(y=>m(xd,{status:y.status,label:y.label},y.id))})]}),l===rn.Authenticate&&m($d,{currentPat:a,onSubmit:h}),l===rn.ConnectWorkspace&&m(Ea,{onExit:g,showEscOption:!1})]})}c(_a,"Setup");function xd({status:s,label:e}){return _(S,{children:[_(S,{width:2,children:[s==="current"&&m(An,{type:"dots"}),s==="done"&&m(v,{children:"\u2705"})]}),m(v,{dimColor:s!=="current",children:e})]})}c(xd,"StepDisplay");function Jr(){const{stats:s}=fe(),e=Object.entries(s).filter(([t,n])=>n>0);return e.length===0?null:_(S,{flexDirection:"column",children:[m(S,{children:m(S,{width:12,children:m(v,{color:"grey",children:"Elements:"})})}),m(S,{flexDirection:"column",marginLeft:1,children:e.map(([t,n])=>_(S,{children:[m(S,{width:20,children:_(v,{children:[t,":"]})}),m(v,{color:"green",children:n})]},t))})]})}c(Jr,"ElementStats");const Hr=5,Pd=6;function Rd(){const{logs:s}=fe(),[e,t]=J(0),n=Math.min(100,process.stdout.columns||100),r=Hr,i=Math.max(0,s.length-r-e),o=s.length-e,a=s.slice(i,o),l=n-Pd,u=e<s.length-r,d=e>0;return Xe((f,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)):(f==="G"||f==="g")&&t(0)}),_(S,{flexDirection:"column",paddingTop:1,children:[_(v,{color:"grey",children:["Recent Activity (",i+1,"-",o," of ",s.length,"):",s.length>Hr&&m(v,{color:"grey",children:" [arrows: scroll] [g: end]"})]}),a.map((f,h)=>m(S,{marginLeft:1,children:m(v,{color:fs(f.type),children:Ta(f.message,l)})},f.timestamp+h)),s.length>Hr&&_(S,{marginLeft:1,flexDirection:"row",children:[u&&m(v,{color:"grey",children:"\u2191 "}),d&&m(v,{color:"grey",children:"\u2193 "})]})]})}c(Rd,"Logs");const hs=[{value:"sync",label:"Continue (overwrite/delete)",key:""},{value:"exit",label:"Cancel",key:""}];function Md(){const{state:s,resolveConflicts:e,exit:t}=fe(),[n,r]=J(0),[i,o]=J(!1),[a,l]=J(!1);return Xe((u,d)=>{if(!i){if(d.ctrl&&u.toLowerCase()==="r"){l(!a);return}d.upArrow?r(f=>f>0?f-1:hs.length-1):d.downArrow?r(f=>f<hs.length-1?f+1:0):u.toLowerCase()==="y"?r(0):u.toLowerCase()==="n"?r(1):(d.return||u===" ")&&(o(!0),hs[n].value==="sync"?e({watch:!0}):t())}}),Fe(()=>{s!==P.CONFLICTS&&i&&o(!1)},[s,i]),_(S,{flexDirection:"column",paddingTop:1,children:[m(S,{children:m(S,{flexDirection:"row",gap:2,children:m(v,{bold:!0,color:"white",children:"Conflicts with remote"})})}),m(S,{children:m(v,{color:"grey",children:"The remote workspace has changes that aren't in your local workspace:"})}),m(S,{marginTop:1,marginLeft:2,children:m(Vr,{isExpanded:a})}),_(S,{marginTop:2,flexDirection:"row",gap:1,children:[m(v,{color:"white",bold:!0,children:"What would you like to do?"}),m(v,{color:"grey",children:"[up/down, enter]"})]}),m(S,{children:i?_(S,{flexDirection:"row",gap:1,children:[m(An,{type:"dots"}),m(v,{color:"blue",bold:!0,children:"Syncing with remote..."})]}):m(S,{flexDirection:"column",children:hs.map((u,d)=>m(S,{flexDirection:"column",children:_(S,{flexDirection:"row",gap:1,children:[m(v,{color:n===d?"cyan":"grey",children:n===d?"\u25B6":" "}),m(v,{color:n===d?"cyan":"grey",bold:n===d,children:u.label})]})},u.value))})})]})}c(Md,"ResolveChangesUI");const Ld={[$e.UPDATE]:{incoming:{label:"Elements updated in remote",description:"(to be overwritten from remote)"},outgoing:{label:"Elements updated locally",description:"(to be pushed to remote)"}},[$e.DELETE]:{incoming:{label:"Elements not existing in remote",description:"(to be deleted locally)"},outgoing:{label:"Elements deleted locally",description:"(to be deleted from remote)"}},[$e.CREATE]:{incoming:{label:"Elements created in remote",description:"(to be created locally)"},outgoing:{label:"Elements created locally",description:"(to be created in remote)"}}};function Vr({isExpanded:s,showControls:e=!0}){const{conflicts:t}=fe(),n=5,r=jc(()=>{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=Ld[a][l];return _(S,{flexDirection:"column",children:[_(S,{flexDirection:"row",gap:1,children:[_(v,{color:"yellow",children:[u.label," (",o.length,")"]}),m(v,{color:"white",children:u.description})]}),(s?o:o.slice(0,n)).map(d=>m(S,{marginLeft:2,children:_(v,{color:"grey",children:["\u2022 ",d.element.id," (",d.element.relativePath,")"]})},d.element.id)),!s&&o.length>n&&m(S,{marginLeft:2,children:_(v,{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(v,{color:"cyan",children:"(press Ctrl+R to collapse)"})})]},i)})})}c(Vr,"Conflicts");function Dd(){const{config:s,state:e,logs:t,currentWorkspace:n,pull:r}=fe(),i=n?.name,o=i?Ta(i,30):s?.workspaceKey,a=Math.min(100,process.stdout.columns||100);return Fe(()=>{r({watch:!0})},[]),_(S,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:a,children:[m(S,{marginTop:-1,marginBottom:1,children:_(S,{flexDirection:"row",gap:1,children:[m(v,{bold:!0,children:"\u{1F504} Workspace"}),_(v,{color:Fd(e),children:[" [",jd(e),"] "]})]})}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Local:"})}),m(v,{color:"grey",children:process.cwd()})]}),_(S,{children:[m(S,{width:12,children:m(v,{color:"grey",children:"Remote:"})}),s?.workspaceKey?_(v,{color:"grey",children:[o," [o: open in console] [w: change]"]}):_(v,{children:[m(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),e===P.CONFLICTS?m(Md,{}):_(ut,{children:[m(S,{paddingTop:1,children:m(Jr,{})}),t.length>0&&m(Rd,{})]})]})}c(Dd,"Workspace");function jd(s){switch(s){case P.PULLING:return"pulling";case P.PUSHING:return"pushing";case P.CONFLICTS:return"conflicts";case P.SYNCED:return"synced";case P.ERROR:return"error";case P.WATCHING:return"tracking changes";case P.RESOLVING:return"resolving";case P.NOT_SYNCED:return"not synced";case P.INITIALIZED:return"initialized";case P.SETTING_UP:return"setup required";default:return"unknown"}}c(jd,"getStatusDisplay");function Fd(s){switch(s){case P.PULLING:return"yellow";case P.PUSHING:return"yellow";case P.CONFLICTS:return"red";case P.SYNCED:return"green";case P.ERROR:return"red";case P.WATCHING:return"green";case P.RESOLVING:return"yellow";case P.NOT_SYNCED:return"grey";case P.SETTING_UP:return"yellow";default:return"grey"}}c(Fd,"getStatusColor");const qd="https://console.integration.app/w";function Kd(){const s=_d(),e=Ws(!0),{exit:t,state:n}=fe(),[r,i]=J(null),o=r??(n===P.SETTING_UP?"setup":"main");Xe(l=>{o==="main"&&(l==="w"&&i("workspace-selection"),l==="a"&&i("add-mcp-server"),l==="o"&&n===P.INITIALIZED&&a(),l==="s"&&i("setup"))});async function a(){try{const l=await Fi(s),u=`${qd}/${l}`,d=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";cl(`${d} "${u}"`)}catch(l){console.error("Failed to open workspace:",l),t()}}return c(a,"handleOpenWorkspace"),Fe(()=>(e.current=!0,()=>{e.current=!1}),[]),o==="workspace-selection"?m(Ea,{onExit:c(()=>i(null),"onExit")}):o==="add-mcp-server"?m(Id,{onExit:c(()=>i(null),"onExit"),onComplete:c(()=>i(null),"onComplete")}):o==="setup"?m(_a,{onComplete:c(()=>i(null),"onComplete")},Date.now()):m(Ur,{children:_(S,{flexDirection:"column",children:[m(S,{flexGrow:1,children:m(Od,{})}),m(Dd,{}),m(S,{paddingLeft:2,children:m(v,{color:"grey",children:"[s: (re-)setup]"})})]})})}c(Kd,"Main");const on=Lc(process.argv.slice(2)),Ia=on.cwd?Pc(on.cwd):process.cwd(),Bd=new Ca(nn.Agent,Ia);if(on.verbose&&b.setVerboseMode(!0),on.rps!==void 0){const s=parseInt(on.rps,10);!isNaN(s)&&s>0&&s<=1e3?B.init({maxRequestsPerSecond:s}):isNaN(s)||(b.error(`Invalid RPS value: ${s}. Must be between 1 and 1000.`),process.exit(1))}const Ud=c(()=>m(sn,{cwd:Ia,membraneCLIService:Bd,children:m(Kd,{})}),"App");function Wd(){Ut(m(Ud,{}))}c(Wd,"runAgent");function it(s){if(s.type){if(Array.isArray(s.type))return{anyOf:s.type.map(t=>it({...s,type:t}))};if(s.type==="array"){const t={type:"array",items:s.items?it(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]=it(n)}return s.anyOf&&(e.anyOf=s.anyOf.map(it)),s.additionalProperties!==void 0&&(typeof s.additionalProperties=="boolean"?e.additionalProperties=s.additionalProperties:e.additionalProperties=it(s.additionalProperties)),s.required&&(e.required=s.required),e}c(it,"convertDataSchemaToOpenAPI");function Jd(s){const{membraneInterfaces:{actions:e}}=s,t=Hd(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(Jd,"generateOpenAPIContent");function Hd(s){const e={};return s.forEach(t=>{const n=Xs(Ys(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=it(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=it(o);i.properties={...i.properties,data:a}}e[`${n}Response`]=i}),e}c(Hd,"generateOpenAPISchemas");function Vd(s){const{membraneInterfaces:{actions:e}}=s,t=ml(e,"key"),n=new pl({indentNumberOfSpaces:2,newLine:`
142
+ `});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(),Gd(n,t),n.toString()}c(Vd,"generateTypeScriptContent");function Gd(s,e){s.writeLine('declare module "@membranehq/sdk" {'),s.indent(()=>{e.forEach(t=>{const n=zr(t),r=t?.inputSchema;ps(s,{interfaceName:n,properties:r?.properties,required:r?.required||[]});const i=Yr(t),o=t?.customOutputSchema||t?.outputSchema;ps(s,{interfaceName:i,properties:o?.properties,required:o?.required||[],fallbackContent:"result: unknown"}),s.newLine()}),ps(s,{interfaceName:"MembraneClient",methods:e.map(t=>{const n=zr(t),r=Yr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ActionAccessor<${n}, ${r}>`}})}),s.newLine(),ps(s,{interfaceName:"ConnectionAccessor",methods:e.map(t=>{const n=zr(t),r=Yr(t);return{name:"action",parameters:`selector: "${t.key}"`,returnType:`ConnectionLevelActionAccessor<${n}, ${r}>`}})})}),s.writeLine("}")}c(Gd,"generateModuleAugmentation");function ps(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&&zd(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(ps,"generateTypeScriptInterface");function zd(s,e,t){Object.entries(e).forEach(([n,r])=>{const o=t.includes(n)?"":"?",a=Gr(r);s.writeLine(`readonly ${n}${o}: ${a}`)})}c(zd,"generateTypeScriptProperties");function Gr(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?Gr(s.items):"unknown"}[]`:s.type==="object"?s.properties?`{ ${Object.entries(s.properties).map(([t,n])=>{const i=(s.required||[]).includes(t)?"":"?",o=Gr(n);return`readonly ${t}${i}: ${o}`}).join("; ")} }`:"Record<string, unknown>":"unknown"}c(Gr,"convertJsonSchemaToTypeScript");function zr(s){return`${Xs(Ys(s.key))}Input`}c(zr,"getInputTypeName");function Yr(s){return`${Xs(Ys(s.key))}Output`}c(Yr,"getOutputTypeName");async function Xr(s){const{out:e}=s;await L.promises.mkdir(e,{recursive:!0});const t=Yd(s);for(const[n,r]of Object.entries(t)){const i=K.join(e,n);await L.promises.writeFile(i,r,"utf-8")}}c(Xr,"generateCode");function Yd(s){switch(s.target){case"openapi":return{"openapi.json":Jd(s)};case"typescript":return{"generated.d.ts":Vd(s)};default:throw new Error(`Unsupported target: ${s.target}`)}}c(Yd,"generateContent");const Qr=c(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The codegen command is experimental and subject to rapid changes.\u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
143
+ `),"createExperimentalWarning$1");function Xd(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",Qr()).addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane codegen --actions list-files,get-file-by-id --out src/generated --target openapi --schemasOnly")}`,` ${T.gray("\u25B8")} ${T.cyan("membrane install --actions delete-file --out src/generated --target typescript --schemasOnly")}`,"",Qr()].join(`
144
+ `)).action(async t=>{try{console.warn(Qr()),console.error(T.cyan("\u{1F527} Membrane Codegen")),console.error("Status: Loading membrane interfaces...");const n=await Qd(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 Xr(r),console.error(T.green("\u2705 Code generation completed successfully!")),process.exit(0)}catch(n){console.error(T.red("\u274C Code generation failed:")),console.error(n instanceof Error?n.message:"Unknown error occurred"),process.exit(1)}})}c(Xd,"setupCodegenCommand");async function Qd(s,e){return await s.fetchElements(),{actions:[...s.getSyncedElementsByType(x.Action).map(t=>t.data)].filter(t=>e.actions.includes(t.key||""))}}c(Qd,"loadMembraneInterfaces");const Zr=Bs(null),Aa=c(()=>{const s=Us(Zr);if(!s)throw new Error("useTree must be used within TreeView");return s},"useTree"),Zd=c(s=>Ae.Children.count(s)>0,"hasChildren");function ef(s){const e=Aa(),{label:t,value:n,isInitiallyExpanded:r}=s,i=Fc(),o=Ws(e.registerChildItem(t)).current,a=e.isActiveByRef(o),[l,u]=J(r??!1),d={props:s,ref:o,id:i,active:a,expanded:l,setExpanded:u,label:t,value:n,isInitiallyExpanded:r,isParent:!1},{children:f}=s,h=typeof f=="function"?f(d):f;return{...d,props:{...s,children:h},isParent:Zd(h)}}c(ef,"useTreeItem");function Pt(s){const e=Aa(),t=ef(s),{expanded:n,isParent:r,props:{children:i},setExpanded:o}=t,{renderValue:a=nf}=s,l=t.ref;_n(()=>{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 d(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(d,"registerChildItem");function f(){l.lastRenderedChild=u.prevSibling}return c(f,"commitChildren"),_n(()=>{f()}),_(ut,{children:[_(S,{marginLeft:e.depth*2,children:[m(S,{width:2,children:r&&m(v,{children:n?"\u25BC":"\u25B6"})}),tf(t),a(t)]}),n&&m(Zr.Provider,{value:{...e,depth:e.depth+1,registerChildItem:d},children:i})]})}c(Pt,"TreeItem");function tf({active:s,label:e}){return m(S,{width:32,children:m(v,{inverse:s,children:e})})}c(tf,"defaultRenderLabel");function nf(s){return m(v,{})}c(nf,"defaultRenderValue");const ot=c(({label:s,onPress:e,hotkey:t})=>m(Pt,{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(v,{children:`${t?` (${t})`:""}`})}),"renderValue")}),"ActionTreeItem"),Oa=c(({label:s,value:e,onChange:t,disabled:n=!1,mask:r,...i})=>{const[o,a]=J(e),[l,u]=J(!1);return _n(()=>{l||a(e)},[l,e]),m(Pt,{label:s,value:e,onInput:c(({key:d,active:f})=>n?!1:l?(d.escape&&u(!1),d.return&&(t(o),u(!1)),!0):f&&d.return?(u(!0),a(e),!0):!1,"onInput"),renderValue:c(()=>{const d=o,f=r?r.repeat(d.length):d;return m(S,{children:n||!l?m(v,{dimColor:!0,children:f}):_(ut,{children:[m(S,{width:f.length+1,children:m(Ni,{...i,focus:l,value:d,onChange:a})}),m(v,{dimColor:!0,children:" \u241B cancel"})]})})},"renderValue")})},"TreeTextField"),sf=c(s=>m(Oa,{...s,mask:"*"}),"SecretField"),ye=c(({children:s,showHelp:e=!1})=>{const t=Ws({parent:void 0,label:"<<ROOT>>",index:0}),[n,r]=J(t.current),i={depth:0,isActiveByRef:c(a=>n===a,"isActiveByRef"),registerChildItem:c(()=>t.current,"registerChildItem"),activeItemRef:n};_n(()=>{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"),Xe((a,l)=>{if(n.onInput?.({input:a,key:l,active:!0}))return;let u,d;for(const f of o(t.current))if(f.label!=null){if(u===n&&(d=f),f&&f.onInput?.({input:a,key:l,active:f===n}))return;u=f}l.upArrow?r(f=>f.prevSibling?.lastRenderedChild??f.prevSibling??f.parent??t.current):l.downArrow?r(f=>d??f):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(f=>f.parent??t.current):l.rightArrow&&r(f=>f.lastRenderedChild?f.firstChild:f)}),m(Zr.Provider,{value:i,children:_(S,{flexDirection:"column",children:[m(Pt,{isInitiallyExpanded:!0,label:"rootItem",children:s}),e&&m(S,{marginTop:1,flexDirection:"column",children:m(v,{dimColor:!0,children:"\u2191/\u2193 move \u2022 \u2190 collapse \u2022 \u2192 expand \u2022 Enter/Space select/edit \u2022 Esc exit"})})]})})},"TreeView");ye.Item=Pt,ye.TextField=Oa;function at({label:s,elementType:e,isActionExcluded:t,toggleAction:n,generateCode:r}){const[i,o]=J([]),{fetchElements:a,getSyncedElementsByType:l}=fe();return Fe(()=>{c(async()=>{try{await a();const d=l(e);o(d.map(f=>f.data))}catch(d){console.error(String(d))}},"loadElements")()},[e,a,l,o]),m(Pt,{label:s,children:i.map(u=>m(Pt,{label:u.name,children:e===x.Action&&_(ut,{children:[t&&n&&m(ot,{label:`Toggle ${t(u)?"":"(excluded)"}`,onPress:c(()=>{n(u)},"onPress")}),r&&m(ot,{label:"Generate code",onPress:c(()=>{r?.(u)},"onPress")})]})},u.id))})}c(at,"WorkspaceElementsTreeItem");function rf({onComplete:s}){const{config:e,updateConfig:t,fetchElements:n,getSyncedElementsByType:r}=fe(),[i,o]=J(""),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"),d=c(async()=>{try{if(e){const h=Qe.saveToFile(e);l(h?"\u2705 Configuration saved successfully!":"\u274C Failed to save configuration"),await n();const g=r(x.Action);await Xr({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"),f=c(async()=>{try{const h=Qe.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 _(S,{flexDirection:"column",gap:1,children:[m(v,{bold:!0,color:"cyan",children:"\u2699\uFE0F Membrane Configuration Manager"}),m(S,{paddingX:2,children:_(ye,{showHelp:!0,children:[_(ye.Item,{label:"Configuration",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project",children:[m(ye.TextField,{label:"Workspace Key",value:a?.workspaceKey??"",onChange:c(h=>u("workspaceKey",h),"onChange"),disabled:!0}),m(sf,{label:"Workspace Secret",value:a?.workspaceSecret??"",onChange:c(h=>u("workspaceSecret",h),"onChange"),disabled:!0}),m(ye.TextField,{label:"API URI",value:a?.apiUri??"",onChange:c(h=>u("apiUri",h),"onChange")}),m(ye.TextField,{label:"Test Customer ID",value:a?.testCustomerId??"",onChange:c(h=>u("testCustomerId",h),"onChange")})]}),_(ye.Item,{label:"Code Generation",isInitiallyExpanded:!0,children:[_(ye.Item,{label:"Project Type",isInitiallyExpanded:!0,value:a?.projectType,renderValue:c(({value:h})=>m(v,{children:h==="typescript"?"TypeScript":h==="openapi"?"OpenAPI":"(Not set)"}),"renderValue"),children:[m(ot,{label:"Update to TypeScript",onPress:c(()=>u("projectType","typescript"),"onPress")}),m(ot,{label:"Update to OpenAPI",onPress:c(()=>u("projectType","openapi"),"onPress")})]}),m(ye.TextField,{label:"Project dir",value:a?.outputDir??"",onChange:c(h=>u("outputDir",h),"onChange")})]}),_(ye.Item,{label:"Workspace Elements",children:[m(at,{label:"Actions",elementType:x.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 Xr({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(at,{label:"Flows",elementType:x.Flow}),m(at,{label:"Data Sources",elementType:x.DataSource}),m(at,{label:"Field Mappings",elementType:x.FieldMapping}),m(at,{label:"Packages",elementType:x.Package}),m(at,{label:"App Data Schemas",elementType:x.AppDataSchema}),m(at,{label:"App Event Types",elementType:x.AppEventType})]})]}),m(ot,{label:"Save Configuration",onPress:d,hotkey:"s"}),m(ot,{label:"Reload Configuration",onPress:f,hotkey:"r"}),m(ot,{label:"Exit",onPress:c(()=>s?.(),"onPress"),hotkey:"escape"})]})}),i&&m(S,{paddingX:2,children:m(v,{color:i.includes("\u2705")?"green":"red",children:i})})]})}c(rf,"ConfigManager");function of(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(()=>{Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(rf,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(of,"setupConfigCommand");function af(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?Qe.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)):Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(_a,{onComplete:c(()=>process.exit(0),"onComplete")})}))})}c(af,"setupInitCommand");const cf={name:Wc.REQUEST_TEST_CONNECTION,description:"Request user to create a test connection. Use this when you need to test membrane interface but no test connection exists. The tool will show a UI for user to create a connection.",parameters:W.object({integrationSelector:W.string().describe('Integration key (e.g., "slack", "github") or integration ID to create connection for')}),execute:c(async s=>JSON.stringify({status:Jc.AWAITING_USER_INPUT,args:s}),"execute")},lf=[cf];async function $a(s,e,t){const n={iss:s,exp:Math.floor(Date.now()/1e3)+600,isAdmin:!0};return t&&(n.id=t),zs.sign(n,e)}c($a,"generateMcpAccessToken");async function uf(s,e){return(await Qs.get(`${s}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}c(uf,"fetchOpenApiSchema");function Ve(s,e=!0,t,n=new Set){if(!s)return e?W.string():W.string().optional();if(Object.keys(s).length===0)return e?W.any():W.any().optional();if(s.$ref){const i=s.$ref.replace("#/components/schemas/","");if(n.has(i))return W.any();if(n.add(i),t?.schemas?.[i]){const o=t.schemas[i];return Ve(o,e,t,n)}return W.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]=Ve(a,l,t,n)}if(Object.keys(i).length>0){if(r=W.object(i),s.additionalProperties)if(typeof s.additionalProperties=="object"){const o=Ve(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=Ve(s.additionalProperties,!1,t,n);r=W.record(W.string(),o)}else r=W.record(W.string(),W.any())}else if(s.type==="array"){const i=s.items?Ve(s.items,!0,t,n):W.any();r=W.array(i)}else if(s.anyOf)r=W.any();else{switch(s.type){case"integer":r=W.coerce.number().int();break;case"number":r=W.coerce.number();break;case"boolean":r=W.coerce.boolean();break;case"string":default:r=W.string();break}s.format==="uuid"?r=W.string().uuid():s.format==="email"?r=W.string().email():s.format==="date"?r=W.string().regex(/^\d{4}-\d{2}-\d{2}$/):s.format==="date-time"&&(r=W.string().datetime()),s.enum&&(r=W.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(Ve,"convertOpenApiSchemaToZod");function Na(s){const e=s.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}c(Na,"extractPathParameters");function df(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}`,d={},f={},h={};if(s.parameters){for(const y of s.parameters)if(y.in==="path")f[y.name]=Ve(y.schema,!0,o).describe(y.description||`Path parameter: ${y.name}`);else if(y.in==="query"){const p=y.required===!0;h[y.name]=Ve(y.schema,p,o).describe(y.description||`Query parameter: ${y.name}`)}}if(Object.keys(f).length>0&&(d.params=W.object(f).describe("Path parameters")),Object.keys(h).length>0&&(d.query=W.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?d.body=Ve(p,y,o).describe("Request body (JSON)"):d.body=W.any().describe("Request body (JSON)")}else s.requestBody.content["application/octet-stream"]||s.requestBody.content["text/plain"]?d.body=y?W.string().describe("Request body (binary/text)"):W.string().optional().describe("Request body (binary/text)"):d.body=W.any().describe("Request body")}const g=Object.keys(d).length>0?W.object(d):W.object({});return{name:l,description:u,parameters:g,async execute(y){try{const p=Na(e);if(p.length>0){if(!y.params)throw new Error(`Missing required path parameters: ${p.join(", ")}`);const N=p.filter(D=>!(D in y.params));if(N.length>0)throw new Error(`Missing required path parameters: ${N.join(", ")}`)}let w=`${n}${e}`;if(y.params)for(const[N,D]of Object.entries(y.params)){const A=`{${N}}`;w.includes(A)&&(w=w.replace(A,String(D)))}const k=Na(w);if(k.length>0)throw new Error(`Unresolved path parameters: ${k.join(", ")}`);const E=new URLSearchParams;if(y.query)for(const[N,D]of Object.entries(y.query))D!=null&&E.append(N,String(D));E.toString()&&(w+=`?${E.toString()}`);const O=await $a(r,i,a),I={method:t.toUpperCase(),headers:{Authorization:`Bearer ${O}`}};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 $=await Qs.request({url:w,...I});return{content:[{type:"text",text:$.data===""?"":JSON.stringify($.data,null,2)}]}}catch(p){return Qs.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(df,"createApiTool");function ff(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,d]of Object.entries(l))if(["get","post","put","delete","patch"].includes(u)&&d&&typeof d=="object"){const f=df(d,a,u,e,t,n,o,r);i.push(f)}}return i}c(ff,"convertOpenApiToTools");function hf(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=On();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||er,n=await $a(e.workspaceKey,e.workspaceSecret,e.testCustomerId),r=await uf(t,n),i=ff(r,t,e.workspaceKey,e.workspaceSecret,e.testCustomerId),o=new gl({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
147
148
  Use it for anything related to Membrane or integrations.
148
- `,version:"1.0.0"});for(const u of i){const f=u.execute;u.execute=async d=>(uf(process.pid,process.cwd()),f(d)),o.addTool(u)}Nr({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(()=>{Nr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),l=c(async()=>{clearInterval(a),zt(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",()=>{zt(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(Jf,"setupMcpCommand");const Hf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Vf={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class Z{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${T.gray(new Date().toISOString())} `:"",i=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=Hf[t],l=Vf[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
149
+ `,version:"1.0.0"}),a=[...i,...lf];for(const d of a){const f=d.execute;d.execute=async h=>(kd(process.pid,process.cwd()),f(h)),o.addTool(d)}Fr({isRunning:!0,startTime:new Date().toISOString(),toolsCount:a.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const l=setInterval(()=>{Fr({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),u=c(async()=>{clearInterval(l),tn(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await u(),process.exit(0)}),process.on("SIGTERM",async()=>{await u(),process.exit(0)}),process.on("exit",()=>{tn(process.pid,process.cwd())}),process.on("uncaughtException",async d=>{console.error("Uncaught exception:",d.message),await u(),process.exit(1)}),process.on("unhandledRejection",async d=>{console.error("Unhandled rejection:",d),await u(),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(hf,"setupMcpCommand");const pf={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},mf={info:T.blue,success:T.green,warning:T.yellow,error:T.red,debug:T.gray};class Z{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${T.gray(new Date().toISOString())} `:"",i=n.prefix?`${T.gray(n.prefix)} `:"",o=n.suffix?` ${T.gray(n.suffix)}`:"",a=pf[t],l=mf[t];return`${r}${a} ${i}${l(e)}${o}`}static info(e,t){let n=T.blue;if(t?.color&&(n=T[t.color.toLowerCase()]||T.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${T.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(T.gray(`[${t.prefix}] ${e}`),t.error?`
149
150
  ${T.red(t.error)}`:""):console.debug(T.gray(e),t?.error?`
150
- ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function Gf(s){s.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
151
- `)).action(async()=>{try{Z.header("Opening Workspace in Browser"),Z.info("Loading configuration...");const e=Cn();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");Z.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Ai(process.cwd())}`;Z.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),Z.success("Browser opened successfully")}catch(e){e instanceof Error&&(Z.error(e.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(Gf,"setupOpenCommand");function zf(s){return g(Rr,{children:g(Yf,{options:s})})}c(zf,"Pull");function Yf({options:s}){const{logs:e,state:t,conflicts:n,pull:r}=Se();Ge(()=>{r(s)},[]);const i=t===x.CONFLICTS;return O(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:os(o.type),children:o.message},o.timestamp+a)),i&&O(Rs,{children:[O(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Fr,{isExpanded:!s.watch,showControls:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Dr,{})]})}c(Yf,"PullActivity");function ba(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(ba,"getWatchModeCallback");function Xf(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically"," membrane pull --rps 5 # Limit to 5 requests per second",""].join(`
152
- `)).action(async t=>{const n=t.watch?ba():()=>process.exit(0);bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(zf,{...t,onComplete:n})}))})}c(Xf,"setupPullCommand");function Qf(s){return g(Rr,{children:g(Zf,{options:s})})}c(Qf,"Push");function Zf({options:s}){const{logs:e,state:t,conflicts:n,push:r}=Se();Ge(()=>{r(s)},[]);const i=t===x.CONFLICTS;return O(v,{flexDirection:"column",children:[e.slice().map((o,a)=>g(C,{color:os(o.type),children:o.message},o.timestamp+a)),i&&O(Rs,{children:[O(C,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),g(Fr,{isExpanded:!s.watch,showControls:!1}),g(C,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===x.SYNCED&&g(Dr,{})]})}c(Zf,"PushActivity");function ed(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data"," membrane push --rps 5 # Limit to 5 requests per second",""].join(`
153
- `)).action(async t=>{const n=t.watch?ba():()=>process.exit(0);bn(it.createElement(is,{membraneCLIService:e,children:it.createElement(Qf,{...t,onComplete:n})}))})}c(ed,"setupPushCommand");class td{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=Vs(),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}function M(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}c(M,"__classPrivateFieldSet");function S(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}c(S,"__classPrivateFieldGet");let Sa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Sa=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))},"uuid4");function Zt(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(Zt,"isAbortError");const Wr=c(s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)},"castToError");class j extends Error{static{c(this,"AnthropicError")}}class re extends j{static{c(this,"APIError")}constructor(e,t,n,r){super(`${re.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new ls({message:n,cause:Wr(t)});const i=t;return e===400?new Ca(e,i,n,r):e===401?new ka(e,i,n,r):e===403?new Ta(e,i,n,r):e===404?new _a(e,i,n,r):e===409?new Ea(e,i,n,r):e===422?new Oa(e,i,n,r):e===429?new Aa(e,i,n,r):e>=500?new Ia(e,i,n,r):new re(e,i,n,r)}}class ve extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ls extends re{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class va extends ls{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ca extends re{static{c(this,"BadRequestError")}}class ka extends re{static{c(this,"AuthenticationError")}}class Ta extends re{static{c(this,"PermissionDeniedError")}}class _a extends re{static{c(this,"NotFoundError")}}class Ea extends re{static{c(this,"ConflictError")}}class Oa extends re{static{c(this,"UnprocessableEntityError")}}class Aa extends re{static{c(this,"RateLimitError")}}class Ia extends re{static{c(this,"InternalServerError")}}const nd=/^[a-z][a-z0-9+.-]*:/i,sd=c(s=>nd.test(s),"isAbsoluteURL");let Jr=c(s=>(Jr=Array.isArray,Jr(s)),"isArray"),$a=Jr;function Na(s){return typeof s!="object"?{}:s??{}}c(Na,"maybeObj");function rd(s){if(!s)return!0;for(const e in s)return!1;return!0}c(rd,"isEmptyObj");function id(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(id,"hasOwn");const od=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new j(`${s} must be an integer`);if(e<0)throw new j(`${s} must be a positive integer`);return e},"validatePositiveInteger"),xa=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),ad=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),At="0.62.0",cd=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function ld(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}c(ld,"getDetectedPlatform");const ud=c(()=>{const s=ld();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":Ma(Deno.build.os),"X-Stainless-Arch":Pa(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":Ma(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Pa(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=fd();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":At,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function fd(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}c(fd,"getBrowserInfo");const Pa=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),Ma=c(s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),"normalizePlatform");let Ra;const dd=c(()=>Ra??(Ra=ud()),"getPlatformHeaders");function hd(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}c(hd,"getDefaultFetch");function La(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}c(La,"makeReadableStream");function Da(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return La({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(Da,"ReadableStreamFrom");function Hr(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}c(Hr,"ReadableStreamToAsyncIterable");async function pd(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}c(pd,"CancelReadableStream");const md=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function gd(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}c(gd,"concatBytes");let ja;function Vr(s){let e;return(ja??(e=new globalThis.TextEncoder,ja=e.encode.bind(e)))(s)}c(Vr,"encodeUTF8");let Fa;function qa(s){let e;return(Fa??(e=new globalThis.TextDecoder,Fa=e.decode.bind(e)))(s)}c(qa,"decodeUTF8");var de,he;class en{static{c(this,"LineDecoder")}constructor(){de.set(this,void 0),he.set(this,void 0),M(this,de,new Uint8Array),M(this,he,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Vr(e):e;M(this,de,gd([S(this,de,"f"),t]));const n=[];let r;for(;(r=yd(S(this,de,"f"),S(this,he,"f")))!=null;){if(r.carriage&&S(this,he,"f")==null){M(this,he,r.index);continue}if(S(this,he,"f")!=null&&(r.index!==S(this,he,"f")+1||r.carriage)){n.push(qa(S(this,de,"f").subarray(0,S(this,he,"f")-1))),M(this,de,S(this,de,"f").subarray(S(this,he,"f"))),M(this,he,null);continue}const i=S(this,he,"f")!==null?r.preceding-1:r.preceding,o=qa(S(this,de,"f").subarray(0,i));n.push(o),M(this,de,S(this,de,"f").subarray(r.index)),M(this,he,null)}return n}flush(){return S(this,de,"f").length?this.decode(`
154
- `):[]}}de=new WeakMap,he=new WeakMap,en.NEWLINE_CHARS=new Set([`
155
- `,"\r"]),en.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function yd(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}c(yd,"findNewlineIndex");function wd(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}c(wd,"findDoubleNewlineIndex");const us={off:0,error:200,warn:300,info:400,debug:500},Ka=c((s,e,t)=>{if(s){if(id(us,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(us))}`)}},"parseLogLevel");function tn(){}c(tn,"noop");function fs(s,e,t){return!e||us[s]>us[t]?tn:e[s].bind(e)}c(fs,"makeLogFn");const bd={error:tn,warn:tn,info:tn,debug:tn};let Ba=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return bd;const n=Ba.get(e);if(n&&n[0]===t)return n[1];const r={error:fs("error",e,t),warn:fs("warn",e,t),info:fs("info",e,t),debug:fs("debug",e,t)};return Ba.set(e,[t,r]),r}c(ie,"loggerFor");const nt=c(s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s),"formatRequestDetails");var nn;class Ee{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,nn.set(this,void 0),this.controller=t,M(this,nn,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of Sd(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new re(void 0,xa(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(Zt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new en,l=Hr(e);for await(const u of l)for(const f of a.decode(u))yield f;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(Zt(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ee(o,t,n)}[(nn=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=c(i=>({next:c(()=>{if(i.length===0){const o=n.next();e.push(o),t.push(o)}return i.shift()},"next")}),"teeIterator");return[new Ee(()=>r(e),this.controller,S(this,nn,"f")),new Ee(()=>r(t),this.controller,S(this,nn,"f"))]}toReadableStream(){const e=this;let t;return La({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:i}=await t.next();if(i)return n.close();const o=Vr(JSON.stringify(r)+`
156
- `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*Sd(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");const t=new Cd,n=new en,r=Hr(s.body);for await(const i of vd(r))for(const o of n.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of n.flush()){const o=t.decode(i);o&&(yield o)}}c(Sd,"_iterSSEMessages");async function*vd(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Vr(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=wd(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(vd,"iterSSEChunks");class Cd{static{c(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
157
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=kd(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function kd(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(kd,"partition");async function Ua(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:i}=e,o=await(async()=>{if(e.options.stream)return ie(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Ee.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const d=await t.json();return Wa(d,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,nt({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(Ua,"defaultParseResponse");function Wa(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}c(Wa,"addRequestID");var sn;class Ns extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=Ua){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,sn.set(this,void 0),M(this,sn,e)}_thenUnwrap(e){return new Ns(S(this,sn,"f"),this.responsePromise,async(t,n)=>Wa(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(S(this,sn,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}sn=new WeakMap;var ds;class Td{static{c(this,"AbstractPage")}constructor(e,t,n,r){ds.set(this,void 0),M(this,ds,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,ds,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ds=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class _d extends Ns{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await Ua(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class rn extends Td{static{c(this,"Page")}constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...Na(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...Na(this.options.query),after_id:e}}:null}}const Ja=c(()=>{if(typeof File>"u"){const{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function It(s,e,t){return Ja(),new File(s,e??"unknown_file",t)}c(It,"makeFile");function hs(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}c(hs,"getName");const Ha=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),Ed=c(async(s,e)=>({...s,body:await Ad(s.body,e)}),"multipartFormRequestOptions"),Va=new WeakMap;function Od(s){const e=typeof s=="function"?s:s.fetch,t=Va.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return Va.set(e,n),n}c(Od,"supportsFormData");const Ad=c(async(s,e)=>{if(!await Od(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>Gr(t,n,r))),t},"createForm"),Id=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),Gr=c(async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response){let n={};const r=t.headers.get("Content-Type");r&&(n={type:r}),s.append(e,It([await t.blob()],hs(t),n))}else if(Ha(t))s.append(e,It([await new Response(Da(t)).blob()],hs(t)));else if(Id(t))s.append(e,It([t],hs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>Gr(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Gr(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue"),Ga=c(s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function","isBlobLike"),$d=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Ga(s),"isFileLike"),Nd=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function xd(s,e,t){if(Ja(),s=await s,e||(e=hs(s)),$d(s))return s instanceof File&&e==null&&t==null?s:It([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(Nd(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),It(await zr(r),e,t)}const n=await zr(s);if(!t?.type){const r=n.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return It(n,e,t)}c(xd,"toFile");async function zr(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Ga(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(Ha(s))for await(const t of s)e.push(...await zr(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Pd(s)}`)}return e}c(zr,"getBytes");function Pd(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(Pd,"propsForError");class Pe{static{c(this,"APIResource")}constructor(e){this._client=e}}const za=Symbol.for("brand.privateNullableHeaders");function*Md(s){if(!s)return;if(za in s){const{values:n,nulls:r}=s;yield*n.entries();for(const i of r)yield[i,null];return}let e=!1,t;s instanceof Headers?t=s.entries():$a(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=$a(n[1])?n[1]:[n[1]];let o=!1;for(const a of i)a!==void 0&&(e&&!o&&(o=!0,yield[r,null]),yield[r,a])}}c(Md,"iterateHeaders");const G=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of Md(n)){const a=i.toLowerCase();r.has(a)||(e.delete(i),r.add(a)),o===null?(e.delete(i),t.add(a)):(e.append(i,o),t.delete(a))}}return{[za]:!0,values:e,nulls:t}},"buildHeaders");function Ya(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(Ya,"encodeURIPath");const Xa=Object.freeze(Object.create(null)),Rd=c((s=Ya)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((f,d,p)=>{/[?#]/.test(d)&&(r=!0);const m=n[p];let y=(r?encodeURIComponent:s)(""+m);return p!==n.length&&(m==null||typeof m=="object"&&m.toString===Object.getPrototypeOf(Object.getPrototypeOf(m.hasOwnProperty??Xa)??Xa)?.toString)&&(y=m+"",i.push({start:f.length+d.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(m).slice(8,-1)} is not a valid path parameter`})),f+d+(p===n.length?"":y)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(a))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((f,d)=>f.start-d.start),i.length>0){let f=0;const d=i.reduce((p,m)=>{const y=" ".repeat(m.start-f),h="^".repeat(m.length);return f=m.start+m.length,p+y+h},"");throw new j(`Path parameters result in path with invalid segments:
158
- ${i.map(p=>p.error).join(`
151
+ ${T.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(T.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const n=t||Object.keys(e[0]),r=e.map(i=>{const o={};return n.forEach(a=>{o[a]=i[a]}),o});console.table(r,n)}static divider(){}}function gf(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{Z.header("Opening Workspace in Browser"),Z.info("Loading configuration...");const e=On();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");Z.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await Fi(process.cwd())}`;Z.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),Z.success("Browser opened successfully")}catch(e){e instanceof Error&&(Z.error(e.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(gf,"setupOpenCommand");function yf(s){return m(Ur,{children:m(wf,{options:s})})}c(yf,"Pull");function wf({options:s}){const{logs:e,state:t,conflicts:n,pull:r}=fe();Fe(()=>{r(s)},[]);const i=t===P.CONFLICTS;return _(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(v,{color:fs(o.type),children:o.message},o.timestamp+a)),i&&_(ut,{children:[_(v,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Vr,{isExpanded:!s.watch,showControls:!1}),m(v,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===P.SYNCED&&m(Jr,{})]})}c(wf,"PullActivity");function xa(){const s=setInterval(()=>{},3e4),e=c(()=>{clearInterval(s)},"cleanup");return process.on("SIGINT",()=>{e(),process.exit(0)}),process.on("SIGTERM",()=>{e(),process.exit(0)}),process.on("exit",e),()=>{}}c(xa,"getWatchModeCallback");function bf(s,e){s.command("pull").description("Pull workspace data from specified workspace").option("--force","Overwrite conflicts with remote data",!1).option("--watch","Watch for changes and pull automatically",!1).option("--all-connectors","Include public connectors in export - to push to the self-hosted instance",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull --force # Overwrite conflicts with remote data"," membrane pull --all-connectors # Pull all connectors"," membrane pull --watch # Watch for changes and pull automatically"," membrane pull --rps 5 # Limit to 5 requests per second",""].join(`
153
+ `)).action(async t=>{const n=t.watch?xa():()=>process.exit(0);Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(yf,{...t,onComplete:n})}))})}c(bf,"setupPullCommand");function Sf(s){return m(Ur,{children:m(Cf,{options:s})})}c(Sf,"Push");function Cf({options:s}){const{logs:e,state:t,conflicts:n,push:r}=fe();Fe(()=>{r(s)},[]);const i=t===P.CONFLICTS;return _(S,{flexDirection:"column",children:[e.slice().map((o,a)=>m(v,{color:fs(o.type),children:o.message},o.timestamp+a)),i&&_(ut,{children:[_(v,{color:"yellow",bold:!0,children:["Found ",n.length," conflicts with remote:"]}),m(Vr,{isExpanded:!s.watch,showControls:!1}),m(v,{color:"red",children:"Out of sync with remote, use --force to overwrite conflict changes"})]}),t===P.SYNCED&&m(Jr,{})]})}c(Cf,"PushActivity");function vf(s,e){s.command("push").description("Push workspace data to specified workspace").option("--force","Overwrite conflicts with local data",!1).option("--watch","Watch for changes and push automatically",!1).option("--save-logs","Save logs to a file",!1).option("--verbose","Show verbose debug logs",!1).option("--rps <number>","Maximum requests per second (default: 80)",t=>parseInt(t,10)).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push --force # Overwrite conflicts with local data"," membrane push --rps 5 # Limit to 5 requests per second",""].join(`
154
+ `)).action(async t=>{const n=t.watch?xa():()=>process.exit(0);Ut(Ae.createElement(sn,{membraneCLIService:e,children:Ae.createElement(Sf,{...t,onComplete:n})}))})}c(vf,"setupPushCommand");class kf{static{c(this,"BaseRunner")}constructor(e={}){if(this.options=e,this.fsPaths=tr(),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}function M(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}c(M,"__classPrivateFieldSet");function C(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}c(C,"__classPrivateFieldGet");let Pa=c(function(){const{crypto:s}=globalThis;if(s?.randomUUID)return Pa=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))},"uuid4");function an(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}c(an,"isAbortError");const ei=c(s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)},"castToError");class j extends Error{static{c(this,"AnthropicError")}}class re extends j{static{c(this,"APIError")}constructor(e,t,n,r){super(`${re.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r?.get("request-id"),this.error=t}static makeMessage(e,t,n){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new ms({message:n,cause:ei(t)});const i=t;return e===400?new Ma(e,i,n,r):e===401?new La(e,i,n,r):e===403?new Da(e,i,n,r):e===404?new ja(e,i,n,r):e===409?new Fa(e,i,n,r):e===422?new qa(e,i,n,r):e===429?new Ka(e,i,n,r):e>=500?new Ba(e,i,n,r):new re(e,i,n,r)}}class ve extends re{static{c(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ms extends re{static{c(this,"APIConnectionError")}constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Ra extends ms{static{c(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ma extends re{static{c(this,"BadRequestError")}}class La extends re{static{c(this,"AuthenticationError")}}class Da extends re{static{c(this,"PermissionDeniedError")}}class ja extends re{static{c(this,"NotFoundError")}}class Fa extends re{static{c(this,"ConflictError")}}class qa extends re{static{c(this,"UnprocessableEntityError")}}class Ka extends re{static{c(this,"RateLimitError")}}class Ba extends re{static{c(this,"InternalServerError")}}const Tf=/^[a-z][a-z0-9+.-]*:/i,Ef=c(s=>Tf.test(s),"isAbsoluteURL");let ti=c(s=>(ti=Array.isArray,ti(s)),"isArray"),Ua=ti;function Wa(s){return typeof s!="object"?{}:s??{}}c(Wa,"maybeObj");function _f(s){if(!s)return!0;for(const e in s)return!1;return!0}c(_f,"isEmptyObj");function If(s,e){return Object.prototype.hasOwnProperty.call(s,e)}c(If,"hasOwn");const Af=c((s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new j(`${s} must be an integer`);if(e<0)throw new j(`${s} must be a positive integer`);return e},"validatePositiveInteger"),Ja=c(s=>{try{return JSON.parse(s)}catch{return}},"safeJSON"),Of=c(s=>new Promise(e=>setTimeout(e,s)),"sleep"),Rt="0.62.0",$f=c(()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u","isRunningInBrowser");function Nf(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}c(Nf,"getDetectedPlatform");const xf=c(()=>{const s=Nf();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rt,"X-Stainless-OS":Va(Deno.build.os),"X-Stainless-Arch":Ha(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rt,"X-Stainless-OS":Va(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ha(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Pf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Pf(){if(typeof navigator>"u"||!navigator)return null;const s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,o=n[3]||0;return{browser:e,version:`${r}.${i}.${o}`}}}return null}c(Pf,"getBrowserInfo");const Ha=c(s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown","normalizeArch"),Va=c(s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),"normalizePlatform");let Ga;const Rf=c(()=>Ga??(Ga=xf()),"getPlatformHeaders");function Mf(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}c(Mf,"getDefaultFetch");function za(...s){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}c(za,"makeReadableStream");function Ya(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return za({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}c(Ya,"ReadableStreamFrom");function ni(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}c(ni,"ReadableStreamToAsyncIterable");async function Lf(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}const e=s.getReader(),t=e.cancel();e.releaseLock(),await t}c(Lf,"CancelReadableStream");const Df=c(({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");function jf(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}c(jf,"concatBytes");let Xa;function si(s){let e;return(Xa??(e=new globalThis.TextEncoder,Xa=e.encode.bind(e)))(s)}c(si,"encodeUTF8");let Qa;function Za(s){let e;return(Qa??(e=new globalThis.TextDecoder,Qa=e.decode.bind(e)))(s)}c(Za,"decodeUTF8");var he,pe;class cn{static{c(this,"LineDecoder")}constructor(){he.set(this,void 0),pe.set(this,void 0),M(this,he,new Uint8Array),M(this,pe,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?si(e):e;M(this,he,jf([C(this,he,"f"),t]));const n=[];let r;for(;(r=Ff(C(this,he,"f"),C(this,pe,"f")))!=null;){if(r.carriage&&C(this,pe,"f")==null){M(this,pe,r.index);continue}if(C(this,pe,"f")!=null&&(r.index!==C(this,pe,"f")+1||r.carriage)){n.push(Za(C(this,he,"f").subarray(0,C(this,pe,"f")-1))),M(this,he,C(this,he,"f").subarray(C(this,pe,"f"))),M(this,pe,null);continue}const i=C(this,pe,"f")!==null?r.preceding-1:r.preceding,o=Za(C(this,he,"f").subarray(0,i));n.push(o),M(this,he,C(this,he,"f").subarray(r.index)),M(this,pe,null)}return n}flush(){return C(this,he,"f").length?this.decode(`
155
+ `):[]}}he=new WeakMap,pe=new WeakMap,cn.NEWLINE_CHARS=new Set([`
156
+ `,"\r"]),cn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ff(s,e){for(let r=e??0;r<s.length;r++){if(s[r]===10)return{preceding:r,index:r+1,carriage:!1};if(s[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}c(Ff,"findNewlineIndex");function qf(s){for(let n=0;n<s.length-1;n++){if(s[n]===10&&s[n+1]===10||s[n]===13&&s[n+1]===13)return n+2;if(s[n]===13&&s[n+1]===10&&n+3<s.length&&s[n+2]===13&&s[n+3]===10)return n+4}return-1}c(qf,"findDoubleNewlineIndex");const gs={off:0,error:200,warn:300,info:400,debug:500},ec=c((s,e,t)=>{if(s){if(If(gs,s))return s;ie(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(gs))}`)}},"parseLogLevel");function ln(){}c(ln,"noop");function ys(s,e,t){return!e||gs[s]>gs[t]?ln:e[s].bind(e)}c(ys,"makeLogFn");const Kf={error:ln,warn:ln,info:ln,debug:ln};let tc=new WeakMap;function ie(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Kf;const n=tc.get(e);if(n&&n[0]===t)return n[1];const r={error:ys("error",e,t),warn:ys("warn",e,t),info:ys("info",e,t),debug:ys("debug",e,t)};return tc.set(e,[t,r]),r}c(ie,"loggerFor");const ct=c(s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s),"formatRequestDetails");var un;class Ie{static{c(this,"Stream")}constructor(e,t,n){this.iterator=e,un.set(this,void 0),this.controller=t,M(this,un,n)}static fromSSEResponse(e,t,n){let r=!1;const i=n?ie(n):console;async function*o(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of Bf(e,t)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(l.event!=="ping"&&l.event==="error")throw new re(void 0,Ja(l.data)??l.data,void 0,e.headers)}a=!0}catch(l){if(an(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ie(o,t,n)}static fromReadableStream(e,t,n){let r=!1;async function*i(){const a=new cn,l=ni(e);for await(const u of l)for(const d of a.decode(u))yield d;for(const u of a.flush())yield u}c(i,"iterLines");async function*o(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let a=!1;try{for await(const l of i())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(an(l))return;throw l}finally{a||t.abort()}}return c(o,"iterator"),new Ie(o,t,n)}[(un=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=c(i=>({next:c(()=>{if(i.length===0){const o=n.next();e.push(o),t.push(o)}return i.shift()},"next")}),"teeIterator");return[new Ie(()=>r(e),this.controller,C(this,un,"f")),new Ie(()=>r(t),this.controller,C(this,un,"f"))]}toReadableStream(){const e=this;let t;return za({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:i}=await t.next();if(i)return n.close();const o=si(JSON.stringify(r)+`
157
+ `);n.enqueue(o)}catch(r){n.error(r)}},async cancel(){await t.return?.()}})}}async function*Bf(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");const t=new Wf,n=new cn,r=ni(s.body);for await(const i of Uf(r))for(const o of n.decode(i)){const a=t.decode(o);a&&(yield a)}for(const i of n.flush()){const o=t.decode(i);o&&(yield o)}}c(Bf,"_iterSSEMessages");async function*Uf(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?si(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let i;for(;(i=qf(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}c(Uf,"iterSSEChunks");class Wf{static{c(this,"SSEDecoder")}constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
158
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=Jf(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Jf(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}c(Jf,"partition");async function nc(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:i}=e,o=await(async()=>{if(e.options.stream)return ie(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Ie.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const f=await t.json();return sc(f,t)}return await t.text()})();return ie(s).debug(`[${n}] response parsed`,ct({retryOfRequestLogID:r,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}c(nc,"defaultParseResponse");function sc(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}c(sc,"addRequestID");var dn;class Ds extends Promise{static{c(this,"APIPromise")}constructor(e,t,n=nc){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,dn.set(this,void 0),M(this,dn,e)}_thenUnwrap(e){return new Ds(C(this,dn,"f"),this.responsePromise,async(t,n)=>sc(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(C(this,dn,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}dn=new WeakMap;var ws;class Hf{static{c(this,"AbstractPage")}constructor(e,t,n,r){ws.set(this,void 0),M(this,ws,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,ws,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ws=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Vf extends Ds{static{c(this,"PagePromise")}constructor(e,t,n){super(e,t,async(r,i)=>new n(r,i.response,await nc(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class fn extends Hf{static{c(this,"Page")}constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const t=this.first_id;return t?{...this.options,query:{...Wa(this.options.query),before_id:t}}:null}const e=this.last_id;return e?{...this.options,query:{...Wa(this.options.query),after_id:e}}:null}}const rc=c(()=>{if(typeof File>"u"){const{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}},"checkFileSupport");function Mt(s,e,t){return rc(),new File(s,e??"unknown_file",t)}c(Mt,"makeFile");function bs(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}c(bs,"getName");const ic=c(s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function","isAsyncIterable"),Gf=c(async(s,e)=>({...s,body:await Yf(s.body,e)}),"multipartFormRequestOptions"),oc=new WeakMap;function zf(s){const e=typeof s=="function"?s:s.fetch,t=oc.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return oc.set(e,n),n}c(zf,"supportsFormData");const Yf=c(async(s,e)=>{if(!await zf(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>ri(t,n,r))),t},"createForm"),Xf=c(s=>s instanceof Blob&&"name"in s,"isNamedBlob"),ri=c(async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response){let n={};const r=t.headers.get("Content-Type");r&&(n={type:r}),s.append(e,Mt([await t.blob()],bs(t),n))}else if(ic(t))s.append(e,Mt([await new Response(Ya(t)).blob()],bs(t)));else if(Xf(t))s.append(e,Mt([t],bs(t),{type:t.type}));else if(Array.isArray(t))await Promise.all(t.map(n=>ri(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>ri(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},"addFormValue"),ac=c(s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function","isBlobLike"),Qf=c(s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ac(s),"isFileLike"),Zf=c(s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function","isResponseLike");async function eh(s,e,t){if(rc(),s=await s,e||(e=bs(s)),Qf(s))return s instanceof File&&e==null&&t==null?s:Mt([await s.arrayBuffer()],e??s.name,{type:s.type,lastModified:s.lastModified,...t});if(Zf(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),Mt(await ii(r),e,t)}const n=await ii(s);if(!t?.type){const r=n.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return Mt(n,e,t)}c(eh,"toFile");async function ii(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ac(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ic(s))for await(const t of s)e.push(...await ii(t));else{const t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${th(s)}`)}return e}c(ii,"getBytes");function th(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}c(th,"propsForError");class Me{static{c(this,"APIResource")}constructor(e){this._client=e}}const cc=Symbol.for("brand.privateNullableHeaders");function*nh(s){if(!s)return;if(cc in s){const{values:n,nulls:r}=s;yield*n.entries();for(const i of r)yield[i,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Ua(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=Ua(n[1])?n[1]:[n[1]];let o=!1;for(const a of i)a!==void 0&&(e&&!o&&(o=!0,yield[r,null]),yield[r,a])}}c(nh,"iterateHeaders");const G=c(s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[i,o]of nh(n)){const a=i.toLowerCase();r.has(a)||(e.delete(i),r.add(a)),o===null?(e.delete(i),t.add(a)):(e.append(i,o),t.delete(a))}}return{[cc]:!0,values:e,nulls:t}},"buildHeaders");function lc(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}c(lc,"encodeURIPath");const uc=Object.freeze(Object.create(null)),sh=c((s=lc)=>c(function(t,...n){if(t.length===1)return t[0];let r=!1;const i=[],o=t.reduce((d,f,h)=>{/[?#]/.test(f)&&(r=!0);const g=n[h];let y=(r?encodeURIComponent:s)(""+g);return h!==n.length&&(g==null||typeof g=="object"&&g.toString===Object.getPrototypeOf(Object.getPrototypeOf(g.hasOwnProperty??uc)??uc)?.toString)&&(y=g+"",i.push({start:d.length+f.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(g).slice(8,-1)} is not a valid path parameter`})),d+f+(h===n.length?"":y)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let u;for(;(u=l.exec(a))!==null;)i.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(i.sort((d,f)=>d.start-f.start),i.length>0){let d=0;const f=i.reduce((h,g)=>{const y=" ".repeat(g.start-d),p="^".repeat(g.length);return d=g.start+g.length,h+y+p},"");throw new j(`Path parameters result in path with invalid segments:
159
+ ${i.map(h=>h.error).join(`
159
160
  `)}
160
161
  ${o}
161
- ${d}`)}return o},"path2"),"createPathTagFunction"),Ce=Rd(Ya);class Qa extends Pe{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",rn,{query:r,...t,headers:G([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/files/${e}`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/files/${e}/content`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/files/${e}`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,t){const{betas:n,...r}=e;return this._client.post("/v1/files",Ed({body:r,...t,headers:G([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let Za=class extends Pe{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}?beta=true`,{...n,headers:G([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",rn,{query:r,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class xs{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new en;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");return new xs(Hr(e.body),t)}}let ec=class extends Pe{static{c(this,"Batches")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:G([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",rn,{query:r,...t,headers:G([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(Ce`/v1/messages/batches/${e}?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(Ce`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,t={},n){const r=await this.retrieve(e);if(!r.results_url)throw new j(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:G([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>xs.fromResponse(a.response,a.controller))}};const Ld=c(s=>{let e=0,t=[];for(;e<s.length;){let n=s[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=s[++e];n!=='"';){if(e===s.length){l=!0;break}if(n==="\\"){if(e++,e===s.length){l=!0;break}a+=n+s[e],n=s[++e]}else a+=n,n=s[++e]}n=s[++e],l||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=s[++e]);n&&i.test(n)||n===".";)a+=n,n=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==s.length;)a+=n,n=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},"tokenize"),$t=c(s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),$t(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),$t(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),$t(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),$t(s);break;case"delimiter":return s=s.slice(0,s.length-1),$t(s)}return s},"strip"),Dd=c(s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},"unstrip"),jd=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),tc=c(s=>JSON.parse(jd(Dd($t(Ld(s))))),"partialParse");var ge,Je,on,ps,an,cn,ms,ln,Me,un,gs,ys,Nt,ws,bs,Yr,nc,Ss,Xr,Qr,Zr,sc;const rc="__json_buf";function ic(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c(ic,"tracksToolInput$1");class Ps{static{c(this,"BetaMessageStream")}constructor(){ge.add(this),this.messages=[],this.receivedMessages=[],Je.set(this,void 0),this.controller=new AbortController,on.set(this,void 0),ps.set(this,()=>{}),an.set(this,()=>{}),cn.set(this,void 0),ms.set(this,()=>{}),ln.set(this,()=>{}),Me.set(this,{}),un.set(this,!1),gs.set(this,!1),ys.set(this,!1),Nt.set(this,!1),ws.set(this,void 0),bs.set(this,void 0),Ss.set(this,e=>{if(M(this,gs,!0),Zt(e)&&(e=new ve),e instanceof ve)return M(this,ys,!0),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){const t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))}),M(this,on,new Promise((e,t)=>{M(this,ps,e,"f"),M(this,an,t,"f")})),M(this,cn,new Promise((e,t)=>{M(this,ms,e,"f"),M(this,ln,t,"f")})),S(this,on,"f").catch(()=>{}),S(this,cn,"f").catch(()=>{})}get response(){return S(this,ws,"f")}get request_id(){return S(this,bs,"f")}async withResponse(){const e=await S(this,on,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Ps;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Ps;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,Ss,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,ge,"m",Xr).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,ge,"m",Qr).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ge,"m",Zr).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(M(this,ws,e),M(this,bs,e?.headers.get("request-id")),S(this,ps,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,un,"f")}get errored(){return S(this,gs,"f")}get aborted(){return S(this,ys,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Me,"f")[e]||(S(this,Me,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Me,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,Me,"f")[e]||(S(this,Me,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{M(this,Nt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){M(this,Nt,!0),await S(this,cn,"f")}get currentMessage(){return S(this,Je,"f")}async finalMessage(){return await this.done(),S(this,ge,"m",Yr).call(this)}async finalText(){return await this.done(),S(this,ge,"m",nc).call(this)}_emit(e,...t){if(S(this,un,"f"))return;e==="end"&&(M(this,un,!0),S(this,ms,"f").call(this));const n=S(this,Me,"f")[e];if(n&&(S(this,Me,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,Nt,"f")&&!n?.length&&Promise.reject(r),S(this,an,"f").call(this,r),S(this,ln,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,Nt,"f")&&!n?.length&&Promise.reject(r),S(this,an,"f").call(this,r),S(this,ln,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ge,"m",Yr).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,ge,"m",Xr).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ge,"m",Qr).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ge,"m",Zr).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Je=new WeakMap,on=new WeakMap,ps=new WeakMap,an=new WeakMap,cn=new WeakMap,ms=new WeakMap,ln=new WeakMap,Me=new WeakMap,un=new WeakMap,gs=new WeakMap,ys=new WeakMap,Nt=new WeakMap,ws=new WeakMap,bs=new WeakMap,Ss=new WeakMap,ge=new WeakSet,Yr=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),nc=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new j("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),Xr=c(function(){this.ended||M(this,Je,void 0)},"_BetaMessageStream_beginRequest2"),Qr=c(function(t){if(this.ended)return;const n=S(this,ge,"m",sc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{ic(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{M(this,Je,n);break}}},"_BetaMessageStream_addStreamEvent2"),Zr=c(function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=S(this,Je,"f");if(!t)throw new j("request ended without sending any chunks");return M(this,Je,void 0),t},"_BetaMessageStream_endRequest2"),sc=c(function(t){let n=S(this,Je,"f");if(t.type==="message_start"){if(n)throw new j(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new j(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&ic(r)){let i=r[rc]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,rc,{value:i,enumerable:!1,writable:!0}),i)try{o.input=tc(i)}catch(a){const l=new j(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);S(this,Ss,"f").call(this,l)}n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_BetaMessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Gh(s){}c(Gh,"checkNever$1");const oc={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192},ac={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let ei=class extends Pe{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new ec(this._client)}create(e,t){const{betas:n,...r}=e;r.model in ac&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${ac[r.model]}
162
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!r.stream&&i==null){const o=oc[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,o)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:i??6e5,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Ps.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:G([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};ei.Batches=ec;class fn extends Pe{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new Za(this._client),this.messages=new ei(this._client),this.files=new Qa(this._client)}}fn.Models=Za,fn.Messages=ei,fn.Files=Qa;class cc extends Pe{static{c(this,"Completions")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var ye,He,dn,vs,hn,pn,Cs,mn,Re,gn,ks,Ts,xt,_s,Es,ti,lc,ni,si,ri,ii,uc;const fc="__json_buf";function dc(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(dc,"tracksToolInput");class Ms{static{c(this,"MessageStream")}constructor(){ye.add(this),this.messages=[],this.receivedMessages=[],He.set(this,void 0),this.controller=new AbortController,dn.set(this,void 0),vs.set(this,()=>{}),hn.set(this,()=>{}),pn.set(this,void 0),Cs.set(this,()=>{}),mn.set(this,()=>{}),Re.set(this,{}),gn.set(this,!1),ks.set(this,!1),Ts.set(this,!1),xt.set(this,!1),_s.set(this,void 0),Es.set(this,void 0),ni.set(this,e=>{if(M(this,ks,!0),Zt(e)&&(e=new ve),e instanceof ve)return M(this,Ts,!0),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){const t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))}),M(this,dn,new Promise((e,t)=>{M(this,vs,e,"f"),M(this,hn,t,"f")})),M(this,pn,new Promise((e,t)=>{M(this,Cs,e,"f"),M(this,mn,t,"f")})),S(this,dn,"f").catch(()=>{}),S(this,pn,"f").catch(()=>{})}get response(){return S(this,_s,"f")}get request_id(){return S(this,Es,"f")}async withResponse(){const e=await S(this,dn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Ms;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Ms;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},S(this,ni,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{S(this,ye,"m",si).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)S(this,ye,"m",ri).call(this,l);if(a.controller.signal?.aborted)throw new ve;S(this,ye,"m",ii).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(M(this,_s,e),M(this,Es,e?.headers.get("request-id")),S(this,vs,"f").call(this,e),this._emit("connect"))}get ended(){return S(this,gn,"f")}get errored(){return S(this,ks,"f")}get aborted(){return S(this,Ts,"f")}abort(){this.controller.abort()}on(e,t){return(S(this,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=S(this,Re,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(S(this,Re,"f")[e]||(S(this,Re,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{M(this,xt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){M(this,xt,!0),await S(this,pn,"f")}get currentMessage(){return S(this,He,"f")}async finalMessage(){return await this.done(),S(this,ye,"m",ti).call(this)}async finalText(){return await this.done(),S(this,ye,"m",lc).call(this)}_emit(e,...t){if(S(this,gn,"f"))return;e==="end"&&(M(this,gn,!0),S(this,Cs,"f").call(this));const n=S(this,Re,"f")[e];if(n&&(S(this,Re,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!S(this,xt,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!S(this,xt,"f")&&!n?.length&&Promise.reject(r),S(this,hn,"f").call(this,r),S(this,mn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",S(this,ye,"m",ti).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{S(this,ye,"m",si).call(this),this._connected(null);const i=Ee.fromReadableStream(e,this.controller);for await(const o of i)S(this,ye,"m",ri).call(this,o);if(i.controller.signal?.aborted)throw new ve;S(this,ye,"m",ii).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(He=new WeakMap,dn=new WeakMap,vs=new WeakMap,hn=new WeakMap,pn=new WeakMap,Cs=new WeakMap,mn=new WeakMap,Re=new WeakMap,gn=new WeakMap,ks=new WeakMap,Ts=new WeakMap,xt=new WeakMap,_s=new WeakMap,Es=new WeakMap,ni=new WeakMap,ye=new WeakSet,ti=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),lc=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new j("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),si=c(function(){this.ended||M(this,He,void 0)},"_MessageStream_beginRequest2"),ri=c(function(t){if(this.ended)return;const n=S(this,ye,"m",uc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{dc(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{M(this,He,n);break}}},"_MessageStream_addStreamEvent2"),ii=c(function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=S(this,He,"f");if(!t)throw new j("request ended without sending any chunks");return M(this,He,void 0),t},"_MessageStream_endRequest2"),uc=c(function(t){let n=S(this,He,"f");if(t.type==="message_start"){if(n)throw new j(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new j(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&dc(r)){let i=r[fc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,fc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=tc(i)),n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_MessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Yh(s){}c(Yh,"checkNever");class hc extends Pe{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Ce`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",rn,{query:e,...t})}delete(e,t){return this._client.delete(Ce`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(Ce`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new j(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:G([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>xs.fromResponse(i.response,i.controller))}}class oi extends Pe{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new hc(this._client)}create(e,t){e.model in pc&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${pc[e.model]}
163
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=oc[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return Ms.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const pc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};oi.Batches=hc;class mc extends Pe{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(Ce`/v1/models/${e}`,{...n,headers:G([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",rn,{query:r,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const Os=c(s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()},"readEnv");var ai,ci,As,gc;const Fd="\\n\\nHuman:",qd="\\n\\nAssistant:";class ee{static{c(this,"BaseAnthropic")}constructor({baseURL:e=Os("ANTHROPIC_BASE_URL"),apiKey:t=Os("ANTHROPIC_API_KEY")??null,authToken:n=Os("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){ai.add(this),As.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&cd())throw new j(`It looks like you're running in a browser-like environment.
162
+ ${f}`)}return o},"path2"),"createPathTagFunction"),ke=sh(lc);class dc extends Me{static{c(this,"Files")}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/files",fn,{query:r,...t,headers:G([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(ke`/v1/files/${e}`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}download(e,t={},n){const{betas:r}=t??{};return this._client.get(ke`/v1/files/${e}/content`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}retrieveMetadata(e,t={},n){const{betas:r}=t??{};return this._client.get(ke`/v1/files/${e}`,{...n,headers:G([{"anthropic-beta":[...r??[],"files-api-2025-04-14"].toString()},n?.headers])})}upload(e,t){const{betas:n,...r}=e;return this._client.post("/v1/files",Gf({body:r,...t,headers:G([{"anthropic-beta":[...n??[],"files-api-2025-04-14"].toString()},t?.headers])},this._client))}}let fc=class extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(ke`/v1/models/${e}?beta=true`,{...n,headers:G([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models?beta=true",fn,{query:r,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}};class js{static{c(this,"JSONLDecoder")}constructor(e,t){this.iterator=e,this.controller=t}async*decoder(){const e=new cn;for await(const t of this.iterator)for(const n of e.decode(t))yield JSON.parse(n);for(const t of e.flush())yield JSON.parse(t)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");return new js(ni(e.body),t)}}let hc=class extends Me{static{c(this,"Batches")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/batches?beta=true",{body:r,...t,headers:G([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(ke`/v1/messages/batches/${e}?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/messages/batches?beta=true",fn,{query:r,...t,headers:G([{"anthropic-beta":[...n??[],"message-batches-2024-09-24"].toString()},t?.headers])})}delete(e,t={},n){const{betas:r}=t??{};return this._client.delete(ke`/v1/messages/batches/${e}?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}cancel(e,t={},n){const{betas:r}=t??{};return this._client.post(ke`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:G([{"anthropic-beta":[...r??[],"message-batches-2024-09-24"].toString()},n?.headers])})}async results(e,t={},n){const r=await this.retrieve(e);if(!r.results_url)throw new j(`No batch \`results_url\`; Has it finished processing? ${r.processing_status} - ${r.id}`);const{betas:i}=t??{};return this._client.get(r.results_url,{...n,headers:G([{"anthropic-beta":[...i??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((o,a)=>js.fromResponse(a.response,a.controller))}};const rh=c(s=>{let e=0,t=[];for(;e<s.length;){let n=s[e];if(n==="\\"){e++;continue}if(n==="{"){t.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){t.push({type:"brace",value:"}"}),e++;continue}if(n==="["){t.push({type:"paren",value:"["}),e++;continue}if(n==="]"){t.push({type:"paren",value:"]"}),e++;continue}if(n===":"){t.push({type:"separator",value:":"}),e++;continue}if(n===","){t.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",l=!1;for(n=s[++e];n!=='"';){if(e===s.length){l=!0;break}if(n==="\\"){if(e++,e===s.length){l=!0;break}a+=n+s[e],n=s[++e]}else a+=n,n=s[++e]}n=s[++e],l||t.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let i=/[0-9]/;if(n&&i.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=s[++e]);n&&i.test(n)||n===".";)a+=n,n=s[++e];t.push({type:"number",value:a});continue}let o=/[a-z]/i;if(n&&o.test(n)){let a="";for(;n&&o.test(n)&&e!==s.length;)a+=n,n=s[++e];if(a=="true"||a=="false"||a==="null")t.push({type:"name",value:a});else{e++;continue}continue}e++}return t},"tokenize"),Lt=c(s=>{if(s.length===0)return s;let e=s[s.length-1];switch(e.type){case"separator":return s=s.slice(0,s.length-1),Lt(s);case"number":let t=e.value[e.value.length-1];if(t==="."||t==="-")return s=s.slice(0,s.length-1),Lt(s);case"string":let n=s[s.length-2];if(n?.type==="delimiter")return s=s.slice(0,s.length-1),Lt(s);if(n?.type==="brace"&&n.value==="{")return s=s.slice(0,s.length-1),Lt(s);break;case"delimiter":return s=s.slice(0,s.length-1),Lt(s)}return s},"strip"),ih=c(s=>{let e=[];return s.map(t=>{t.type==="brace"&&(t.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),t.type==="paren"&&(t.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(t=>{t==="}"?s.push({type:"brace",value:"}"}):t==="]"&&s.push({type:"paren",value:"]"})}),s},"unstrip"),oh=c(s=>{let e="";return s.map(t=>{switch(t.type){case"string":e+='"'+t.value+'"';break;default:e+=t.value;break}}),e},"generate"),pc=c(s=>JSON.parse(oh(ih(Lt(rh(s))))),"partialParse");var we,Ge,hn,Ss,pn,mn,Cs,gn,Le,yn,vs,ks,Dt,Ts,Es,oi,mc,_s,ai,ci,li,gc;const yc="__json_buf";function wc(s){return s.type==="tool_use"||s.type==="server_tool_use"||s.type==="mcp_tool_use"}c(wc,"tracksToolInput$1");class Fs{static{c(this,"BetaMessageStream")}constructor(){we.add(this),this.messages=[],this.receivedMessages=[],Ge.set(this,void 0),this.controller=new AbortController,hn.set(this,void 0),Ss.set(this,()=>{}),pn.set(this,()=>{}),mn.set(this,void 0),Cs.set(this,()=>{}),gn.set(this,()=>{}),Le.set(this,{}),yn.set(this,!1),vs.set(this,!1),ks.set(this,!1),Dt.set(this,!1),Ts.set(this,void 0),Es.set(this,void 0),_s.set(this,e=>{if(M(this,vs,!0),an(e)&&(e=new ve),e instanceof ve)return M(this,ks,!0),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){const t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))}),M(this,hn,new Promise((e,t)=>{M(this,Ss,e,"f"),M(this,pn,t,"f")})),M(this,mn,new Promise((e,t)=>{M(this,Cs,e,"f"),M(this,gn,t,"f")})),C(this,hn,"f").catch(()=>{}),C(this,mn,"f").catch(()=>{})}get response(){return C(this,Ts,"f")}get request_id(){return C(this,Es,"f")}async withResponse(){const e=await C(this,hn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new Fs;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new Fs;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},C(this,_s,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{C(this,we,"m",ai).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)C(this,we,"m",ci).call(this,l);if(a.controller.signal?.aborted)throw new ve;C(this,we,"m",li).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(M(this,Ts,e),M(this,Es,e?.headers.get("request-id")),C(this,Ss,"f").call(this,e),this._emit("connect"))}get ended(){return C(this,yn,"f")}get errored(){return C(this,vs,"f")}get aborted(){return C(this,ks,"f")}abort(){this.controller.abort()}on(e,t){return(C(this,Le,"f")[e]||(C(this,Le,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=C(this,Le,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(C(this,Le,"f")[e]||(C(this,Le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{M(this,Dt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){M(this,Dt,!0),await C(this,mn,"f")}get currentMessage(){return C(this,Ge,"f")}async finalMessage(){return await this.done(),C(this,we,"m",oi).call(this)}async finalText(){return await this.done(),C(this,we,"m",mc).call(this)}_emit(e,...t){if(C(this,yn,"f"))return;e==="end"&&(M(this,yn,!0),C(this,Cs,"f").call(this));const n=C(this,Le,"f")[e];if(n&&(C(this,Le,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!C(this,Dt,"f")&&!n?.length&&Promise.reject(r),C(this,pn,"f").call(this,r),C(this,gn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!C(this,Dt,"f")&&!n?.length&&Promise.reject(r),C(this,pn,"f").call(this,r),C(this,gn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",C(this,we,"m",oi).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{C(this,we,"m",ai).call(this),this._connected(null);const i=Ie.fromReadableStream(e,this.controller);for await(const o of i)C(this,we,"m",ci).call(this,o);if(i.controller.signal?.aborted)throw new ve;C(this,we,"m",li).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(Ge=new WeakMap,hn=new WeakMap,Ss=new WeakMap,pn=new WeakMap,mn=new WeakMap,Cs=new WeakMap,gn=new WeakMap,Le=new WeakMap,yn=new WeakMap,vs=new WeakMap,ks=new WeakMap,Dt=new WeakMap,Ts=new WeakMap,Es=new WeakMap,_s=new WeakMap,we=new WeakSet,oi=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_BetaMessageStream_getFinalMessage2"),mc=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new j("stream ended without producing a content block with type=text");return t.join(" ")},"_BetaMessageStream_getFinalText2"),ai=c(function(){this.ended||M(this,Ge,void 0)},"_BetaMessageStream_beginRequest2"),ci=c(function(t){if(this.ended)return;const n=C(this,we,"m",gc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{wc(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{M(this,Ge,n);break}}},"_BetaMessageStream_addStreamEvent2"),li=c(function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=C(this,Ge,"f");if(!t)throw new j("request ended without sending any chunks");return M(this,Ge,void 0),t},"_BetaMessageStream_endRequest2"),gc=c(function(t){let n=C(this,Ge,"f");if(t.type==="message_start"){if(n)throw new j(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new j(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.container=t.delta.container,n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push(t.content_block),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&wc(r)){let i=r[yc]||"";i+=t.delta.partial_json;const o={...r};if(Object.defineProperty(o,yc,{value:i,enumerable:!1,writable:!0}),i)try{o.input=pc(i)}catch(a){const l=new j(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${a}. JSON: ${i}`);C(this,_s,"f").call(this,l)}n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_BetaMessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function wp(s){}c(wp,"checkNever$1");const bc={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192},Sc={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};let ui=class extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new hc(this._client)}create(e,t){const{betas:n,...r}=e;r.model in Sc&&console.warn(`The model '${r.model}' is deprecated and will reach end-of-life on ${Sc[r.model]}
163
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let i=this._client._options.timeout;if(!r.stream&&i==null){const o=bc[r.model]??void 0;i=this._client.calculateNonstreamingTimeout(r.max_tokens,o)}return this._client.post("/v1/messages?beta=true",{body:r,timeout:i??6e5,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}stream(e,t){return Fs.createMessage(this,e,t)}countTokens(e,t){const{betas:n,...r}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:r,...t,headers:G([{"anthropic-beta":[...n??[],"token-counting-2024-11-01"].toString()},t?.headers])})}};ui.Batches=hc;class wn extends Me{static{c(this,"Beta")}constructor(){super(...arguments),this.models=new fc(this._client),this.messages=new ui(this._client),this.files=new dc(this._client)}}wn.Models=fc,wn.Messages=ui,wn.Files=dc;class Cc extends Me{static{c(this,"Completions")}create(e,t){const{betas:n,...r}=e;return this._client.post("/v1/complete",{body:r,timeout:this._client._options.timeout??6e5,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers]),stream:e.stream??!1})}}var be,ze,bn,Is,Sn,Cn,As,vn,De,kn,Os,$s,jt,Ns,xs,di,vc,fi,hi,pi,mi,kc;const Tc="__json_buf";function Ec(s){return s.type==="tool_use"||s.type==="server_tool_use"}c(Ec,"tracksToolInput");class qs{static{c(this,"MessageStream")}constructor(){be.add(this),this.messages=[],this.receivedMessages=[],ze.set(this,void 0),this.controller=new AbortController,bn.set(this,void 0),Is.set(this,()=>{}),Sn.set(this,()=>{}),Cn.set(this,void 0),As.set(this,()=>{}),vn.set(this,()=>{}),De.set(this,{}),kn.set(this,!1),Os.set(this,!1),$s.set(this,!1),jt.set(this,!1),Ns.set(this,void 0),xs.set(this,void 0),fi.set(this,e=>{if(M(this,Os,!0),an(e)&&(e=new ve),e instanceof ve)return M(this,$s,!0),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){const t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))}),M(this,bn,new Promise((e,t)=>{M(this,Is,e,"f"),M(this,Sn,t,"f")})),M(this,Cn,new Promise((e,t)=>{M(this,As,e,"f"),M(this,vn,t,"f")})),C(this,bn,"f").catch(()=>{}),C(this,Cn,"f").catch(()=>{})}get response(){return C(this,Ns,"f")}get request_id(){return C(this,xs,"f")}async withResponse(){const e=await C(this,bn,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){const t=new qs;return t._run(()=>t._fromReadableStream(e)),t}static createMessage(e,t,n){const r=new qs;for(const i of t.messages)r._addMessageParam(i);return r._run(()=>r._createMessage(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),r}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},C(this,fi,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,t=!0){this.receivedMessages.push(e),t&&this._emit("message",e)}async _createMessage(e,t,n){const r=n?.signal;let i;r&&(r.aborted&&this.controller.abort(),i=this.controller.abort.bind(this.controller),r.addEventListener("abort",i));try{C(this,be,"m",hi).call(this);const{response:o,data:a}=await e.create({...t,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(o);for await(const l of a)C(this,be,"m",pi).call(this,l);if(a.controller.signal?.aborted)throw new ve;C(this,be,"m",mi).call(this)}finally{r&&i&&r.removeEventListener("abort",i)}}_connected(e){this.ended||(M(this,Ns,e),M(this,xs,e?.headers.get("request-id")),C(this,Is,"f").call(this,e),this._emit("connect"))}get ended(){return C(this,kn,"f")}get errored(){return C(this,Os,"f")}get aborted(){return C(this,$s,"f")}abort(){this.controller.abort()}on(e,t){return(C(this,De,"f")[e]||(C(this,De,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=C(this,De,"f")[e];if(!n)return this;const r=n.findIndex(i=>i.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(C(this,De,"f")[e]||(C(this,De,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{M(this,jt,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){M(this,jt,!0),await C(this,Cn,"f")}get currentMessage(){return C(this,ze,"f")}async finalMessage(){return await this.done(),C(this,be,"m",di).call(this)}async finalText(){return await this.done(),C(this,be,"m",vc).call(this)}_emit(e,...t){if(C(this,kn,"f"))return;e==="end"&&(M(this,kn,!0),C(this,As,"f").call(this));const n=C(this,De,"f")[e];if(n&&(C(this,De,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!C(this,jt,"f")&&!n?.length&&Promise.reject(r),C(this,Sn,"f").call(this,r),C(this,vn,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!C(this,jt,"f")&&!n?.length&&Promise.reject(r),C(this,Sn,"f").call(this,r),C(this,vn,"f").call(this,r),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",C(this,be,"m",di).call(this))}async _fromReadableStream(e,t){const n=t?.signal;let r;n&&(n.aborted&&this.controller.abort(),r=this.controller.abort.bind(this.controller),n.addEventListener("abort",r));try{C(this,be,"m",hi).call(this),this._connected(null);const i=Ie.fromReadableStream(e,this.controller);for await(const o of i)C(this,be,"m",pi).call(this,o);if(i.controller.signal?.aborted)throw new ve;C(this,be,"m",mi).call(this)}finally{n&&r&&n.removeEventListener("abort",r)}}[(ze=new WeakMap,bn=new WeakMap,Is=new WeakMap,Sn=new WeakMap,Cn=new WeakMap,As=new WeakMap,vn=new WeakMap,De=new WeakMap,kn=new WeakMap,Os=new WeakMap,$s=new WeakMap,jt=new WeakMap,Ns=new WeakMap,xs=new WeakMap,fi=new WeakMap,be=new WeakSet,di=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},"_MessageStream_getFinalMessage2"),vc=c(function(){if(this.receivedMessages.length===0)throw new j("stream ended without producing a Message with role=assistant");const t=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(t.length===0)throw new j("stream ended without producing a content block with type=text");return t.join(" ")},"_MessageStream_getFinalText2"),hi=c(function(){this.ended||M(this,ze,void 0)},"_MessageStream_beginRequest2"),pi=c(function(t){if(this.ended)return;const n=C(this,be,"m",kc).call(this,t);switch(this._emit("streamEvent",t,n),t.type){case"content_block_delta":{const r=n.content.at(-1);switch(t.delta.type){case"text_delta":{r.type==="text"&&this._emit("text",t.delta.text,r.text||"");break}case"citations_delta":{r.type==="text"&&this._emit("citation",t.delta.citation,r.citations??[]);break}case"input_json_delta":{Ec(r)&&r.input&&this._emit("inputJson",t.delta.partial_json,r.input);break}case"thinking_delta":{r.type==="thinking"&&this._emit("thinking",t.delta.thinking,r.thinking);break}case"signature_delta":{r.type==="thinking"&&this._emit("signature",r.signature);break}default:t.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{M(this,ze,n);break}}},"_MessageStream_addStreamEvent2"),mi=c(function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=C(this,ze,"f");if(!t)throw new j("request ended without sending any chunks");return M(this,ze,void 0),t},"_MessageStream_endRequest2"),kc=c(function(t){let n=C(this,ze,"f");if(t.type==="message_start"){if(n)throw new j(`Unexpected event order, got ${t.type} before receiving "message_stop"`);return t.message}if(!n)throw new j(`Unexpected event order, got ${t.type} before "message_start"`);switch(t.type){case"message_stop":return n;case"message_delta":return n.stop_reason=t.delta.stop_reason,n.stop_sequence=t.delta.stop_sequence,n.usage.output_tokens=t.usage.output_tokens,t.usage.input_tokens!=null&&(n.usage.input_tokens=t.usage.input_tokens),t.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=t.usage.cache_creation_input_tokens),t.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=t.usage.cache_read_input_tokens),t.usage.server_tool_use!=null&&(n.usage.server_tool_use=t.usage.server_tool_use),n;case"content_block_start":return n.content.push({...t.content_block}),n;case"content_block_delta":{const r=n.content.at(t.index);switch(t.delta.type){case"text_delta":{r?.type==="text"&&(n.content[t.index]={...r,text:(r.text||"")+t.delta.text});break}case"citations_delta":{r?.type==="text"&&(n.content[t.index]={...r,citations:[...r.citations??[],t.delta.citation]});break}case"input_json_delta":{if(r&&Ec(r)){let i=r[Tc]||"";i+=t.delta.partial_json;const o={...r};Object.defineProperty(o,Tc,{value:i,enumerable:!1,writable:!0}),i&&(o.input=pc(i)),n.content[t.index]=o}break}case"thinking_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,thinking:r.thinking+t.delta.thinking});break}case"signature_delta":{r?.type==="thinking"&&(n.content[t.index]={...r,signature:t.delta.signature});break}default:t.delta}return n}case"content_block_stop":return n}},"_MessageStream_accumulateMessage2"),Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("streamEvent",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const i of t)i.reject(r);t.length=0}),{next:c(async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),"next"),return:c(async()=>(this.abort(),{value:void 0,done:!0}),"return")}}toReadableStream(){return new Ie(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Sp(s){}c(Sp,"checkNever");class _c extends Me{static{c(this,"Batches")}create(e,t){return this._client.post("/v1/messages/batches",{body:e,...t})}retrieve(e,t){return this._client.get(ke`/v1/messages/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/v1/messages/batches",fn,{query:e,...t})}delete(e,t){return this._client.delete(ke`/v1/messages/batches/${e}`,t)}cancel(e,t){return this._client.post(ke`/v1/messages/batches/${e}/cancel`,t)}async results(e,t){const n=await this.retrieve(e);if(!n.results_url)throw new j(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...t,headers:G([{Accept:"application/binary"},t?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((r,i)=>js.fromResponse(i.response,i.controller))}}class gi extends Me{static{c(this,"Messages")}constructor(){super(...arguments),this.batches=new _c(this._client)}create(e,t){e.model in Ic&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Ic[e.model]}
164
+ Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){const r=bc[e.model]??void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,r)}return this._client.post("/v1/messages",{body:e,timeout:n??6e5,...t,stream:e.stream??!1})}stream(e,t){return qs.createMessage(this,e,t)}countTokens(e,t){return this._client.post("/v1/messages/count_tokens",{body:e,...t})}}const Ic={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-5-sonnet-20241022":"October 22, 2025","claude-3-5-sonnet-20240620":"October 22, 2025"};gi.Batches=_c;class Ac extends Me{static{c(this,"Models")}retrieve(e,t={},n){const{betas:r}=t??{};return this._client.get(ke`/v1/models/${e}`,{...n,headers:G([{...r?.toString()!=null?{"anthropic-beta":r?.toString()}:void 0},n?.headers])})}list(e={},t){const{betas:n,...r}=e??{};return this._client.getAPIList("/v1/models",fn,{query:r,...t,headers:G([{...n?.toString()!=null?{"anthropic-beta":n?.toString()}:void 0},t?.headers])})}}const Ps=c(s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()},"readEnv");var yi,wi,Rs,Oc;const ah="\\n\\nHuman:",ch="\\n\\nAssistant:";class ee{static{c(this,"BaseAnthropic")}constructor({baseURL:e=Ps("ANTHROPIC_BASE_URL"),apiKey:t=Ps("ANTHROPIC_API_KEY")??null,authToken:n=Ps("ANTHROPIC_AUTH_TOKEN")??null,...r}={}){yi.add(this),Rs.set(this,void 0);const i={apiKey:t,authToken:n,...r,baseURL:e||"https://api.anthropic.com"};if(!i.dangerouslyAllowBrowser&&$f())throw new j(`It looks like you're running in a browser-like environment.
164
165
 
165
166
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
166
167
  If you understand the risks and have appropriate mitigations in place,
167
168
  you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
168
169
 
169
170
  new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
170
- `);this.baseURL=i.baseURL,this.timeout=i.timeout??ci.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=Ka(i.logLevel,"ClientOptions.logLevel",this)??Ka(Os("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??hd(),M(this,As,md),this._options=i,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return G([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return G([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return G([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new j(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${At}`}defaultIdempotencyKey(){return`stainless-node-retry-${Sa()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!S(this,ai,"m",gc).call(this)&&n||this.baseURL,i=sd(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return rd(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Ns(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:o,url:a,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(o,{url:a,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=n===void 0?"":`, retryOf: ${n}`,d=Date.now();if(ie(this).debug(`[${u}] sending request`,nt({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ve;const p=new AbortController,m=await this.fetchWithTimeout(a,o,l,p).catch(Wr),y=Date.now();if(m instanceof globalThis.Error){const k=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ve;const _=Zt(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - ${k}`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (${k})`,nt({retryOfRequestLogID:n,url:a,durationMs:y-d,message:m.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${_?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${_?"timed out":"failed"} (error; no more retries left)`,nt({retryOfRequestLogID:n,url:a,durationMs:y-d,message:m.message})),_?new va:new ls({cause:m})}const h=[...m.headers.entries()].filter(([k])=>k==="request-id").map(([k,_])=>", "+k+": "+JSON.stringify(_)).join(""),w=`[${u}${f}${h}] ${o.method} ${a} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${y-d}ms`;if(!m.ok){const k=await this.shouldRetry(m);if(t&&k){const D=`retrying, ${t} attempts remaining`;return await pd(m.body),ie(this).info(`${w} - ${D}`),ie(this).debug(`[${u}] response error (${D})`,nt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-d})),this.retryRequest(r,t,n??u,m.headers)}const _=k?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${_}`);const I=await m.text().catch(D=>Wr(D).message),E=xa(I),$=E?void 0:I;throw ie(this).debug(`[${u}] response error (${_})`,nt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,message:$,durationMs:Date.now()-d})),this.makeStatusError(m.status,E,$,m.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,nt({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:y-d})),{response:m,options:r,controller:p,requestLogID:u,retryOfRequestLogID:n,startTime:d}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new _d(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:i,method:o,...a}=t||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(f.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i;const o=r?.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const a=r?.get("retry-after");if(a&&!i){const l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await ad(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:i,query:o,defaultBaseURL:a}=n,l=this.buildURL(i,o,a);"timeout"in n&&od("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:f}=this.buildBody({options:n}),d=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:d,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const o=G([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...dd(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=G([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Da(e)}:S(this,As,"f").call(this,{body:e,headers:n})}}ci=ee,As=new WeakMap,ai=new WeakSet,gc=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),ee.Anthropic=ci,ee.HUMAN_PROMPT=Fd,ee.AI_PROMPT=qd,ee.DEFAULT_TIMEOUT=6e5,ee.AnthropicError=j,ee.APIError=re,ee.APIConnectionError=ls,ee.APIConnectionTimeoutError=va,ee.APIUserAbortError=ve,ee.NotFoundError=_a,ee.ConflictError=Ea,ee.RateLimitError=Aa,ee.BadRequestError=Ca,ee.AuthenticationError=ka,ee.InternalServerError=Ia,ee.PermissionDeniedError=Ta,ee.UnprocessableEntityError=Oa,ee.toFile=xd;class yn extends ee{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new cc(this),this.messages=new oi(this),this.models=new mc(this),this.beta=new fn(this)}}yn.Completions=cc,yn.Messages=oi,yn.Models=mc,yn.Beta=fn;const Kd="claude-sonnet-4-20250514";class hi{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=Cn();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 bi({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new yn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const f=await o.messages.create({model:Kd,max_tokens:u,messages:[{role:"user",content:l}]});return f.content[0].type==="text"?f.content[0].text:""},"complete")};return new hi({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(),Js(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId,e);return Xs(t)}async writeYaml(e,t){const n=B.join(this.testsDir,this.testBasePath,this.connectionId,e);F.mkdirSync(B.dirname(n),{recursive:!0}),F.writeFileSync(n,Dt.dump(t,{noRefs:!0}))}writeResults(e){const t=B.join(this.testsDir,this.testBasePath,this.connectionId);F.mkdirSync(t,{recursive:!0});const n=B.join(t,"test-results.yaml");F.writeFileSync(n,Dt.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 Ks.sign(n,e.workspaceSecret,r)}}sl.interpolate=/{{([\s\S]+?)}}/g;function li(s,e){if(typeof s=="string"){const t=nl(s),n={state:e,random:{number:c(()=>jt.number.int(),"number"),alphaNumeric:c(i=>jt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>jt.company.name(),"name"),catchPhrase:c(()=>jt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>jt.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=>li(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,li(n,e)])):s}c(li,"processNode");function Bd(s,e){return li(s,e)}c(Bd,"handleTemplate");class Ud{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(`${T.bold.cyan("[start]")} ${T.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(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=Bd(i,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,r=e.getResult(),js(this.result,e.path,r)}catch(l){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}js(this.result,e.path,{error:ke(l)}),t=!0,r={error:ke(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Js(this.result,e.getResult())}}class Ve{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(T.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const 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:ke(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function ui(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)||!fi(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=ui(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}fi(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(ui,"getNotMatchingSubFields");function fi(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(fi,"softCompare");class Wd extends Ve{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=Fs(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=Si(n),a=Sn(e.input.fields,o,{skipUnknownFields:!0}),l=Sn(i.record.fields,o),u=ui(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=Nc(n??{});if(r.length>0){const i={};r.forEach(a=>{const l=xc(e.input.fields,a);typeof l<"u"&&js(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=Fs(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=ke(t),r=Fs(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:
171
+ `);this.baseURL=i.baseURL,this.timeout=i.timeout??wi.DEFAULT_TIMEOUT,this.logger=i.logger??console;const o="warn";this.logLevel=o,this.logLevel=ec(i.logLevel,"ClientOptions.logLevel",this)??ec(Ps("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??o,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??Mf(),M(this,Rs,Df),this._options=i,this.apiKey=t,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(this.apiKey&&e.get("x-api-key"))&&!t.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!t.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(e){return G([await this.apiKeyAuth(e),await this.bearerAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return G([{"X-Api-Key":this.apiKey}])}async bearerAuth(e){if(this.authToken!=null)return G([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new j(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Rt}`}defaultIdempotencyKey(){return`stainless-node-retry-${Pa()}`}makeStatusError(e,t,n,r){return re.generate(e,t,n,r)}buildURL(e,t,n){const r=!C(this,yi,"m",Oc).call(this)&&n||this.baseURL,i=Ef(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return _f(o)||(t={...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Ds(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:o,url:a,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(o,{url:a,options:r});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(ie(this).debug(`[${u}] sending request`,ct({retryOfRequestLogID:n,method:r.method,url:a,options:r,headers:o.headers})),r.signal?.aborted)throw new ve;const h=new AbortController,g=await this.fetchWithTimeout(a,o,l,h).catch(ei),y=Date.now();if(g instanceof globalThis.Error){const k=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ve;const E=an(g)||/timed? ?out/i.test(String(g)+("cause"in g?String(g.cause):""));if(t)return ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - ${k}`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (${k})`,ct({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),this.retryRequest(r,t,n??u);throw ie(this).info(`[${u}] connection ${E?"timed out":"failed"} - error; no more retries left`),ie(this).debug(`[${u}] connection ${E?"timed out":"failed"} (error; no more retries left)`,ct({retryOfRequestLogID:n,url:a,durationMs:y-f,message:g.message})),E?new Ra:new ms({cause:g})}const p=[...g.headers.entries()].filter(([k])=>k==="request-id").map(([k,E])=>", "+k+": "+JSON.stringify(E)).join(""),w=`[${u}${d}${p}] ${o.method} ${a} ${g.ok?"succeeded":"failed"} with status ${g.status} in ${y-f}ms`;if(!g.ok){const k=await this.shouldRetry(g);if(t&&k){const D=`retrying, ${t} attempts remaining`;return await Lf(g.body),ie(this).info(`${w} - ${D}`),ie(this).debug(`[${u}] response error (${D})`,ct({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),this.retryRequest(r,t,n??u,g.headers)}const E=k?"error; no more retries left":"error; not retryable";ie(this).info(`${w} - ${E}`);const O=await g.text().catch(D=>ei(D).message),I=Ja(O),$=I?void 0:O;throw ie(this).debug(`[${u}] response error (${E})`,ct({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,message:$,durationMs:Date.now()-f})),this.makeStatusError(g.status,I,$,g.headers)}return ie(this).info(w),ie(this).debug(`[${u}] response start`,ct({retryOfRequestLogID:n,url:g.url,status:g.status,headers:g.headers,durationMs:y-f})),{response:g,options:r,controller:h,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Vf(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:i,method:o,...a}=t||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),n),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:r.signal,...u?{duplex:"half"}:{},method:"GET",...a};o&&(d.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i;const o=r?.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const a=r?.get("retry-after");if(a&&!i){const l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Of(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}calculateNonstreamingTimeout(e,t){if(36e5*e/128e3>6e5||t!=null&&e>t)throw new j("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:i,query:o,defaultBaseURL:a}=n,l=this.buildURL(i,o,a);"timeout"in n&&Af("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:u,body:d}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:r,bodyHeaders:u,retryCount:t});return{req:{method:r,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const o=G([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Rf(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=G([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Ya(e)}:C(this,Rs,"f").call(this,{body:e,headers:n})}}wi=ee,Rs=new WeakMap,yi=new WeakSet,Oc=c(function(){return this.baseURL!=="https://api.anthropic.com"},"_BaseAnthropic_baseURLOverridden2"),ee.Anthropic=wi,ee.HUMAN_PROMPT=ah,ee.AI_PROMPT=ch,ee.DEFAULT_TIMEOUT=6e5,ee.AnthropicError=j,ee.APIError=re,ee.APIConnectionError=ms,ee.APIConnectionTimeoutError=Ra,ee.APIUserAbortError=ve,ee.NotFoundError=ja,ee.ConflictError=Fa,ee.RateLimitError=Ka,ee.BadRequestError=Ma,ee.AuthenticationError=La,ee.InternalServerError=Ba,ee.PermissionDeniedError=Da,ee.UnprocessableEntityError=qa,ee.toFile=eh;class Tn extends ee{static{c(this,"Anthropic")}constructor(){super(...arguments),this.completions=new Cc(this),this.messages=new gi(this),this.models=new Ac(this),this.beta=new wn(this)}}Tn.Completions=Cc,Tn.Messages=gi,Tn.Models=Ac,Tn.Beta=wn;const lh="claude-sonnet-4-20250514";class ki{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=On();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 Ii({token:await this.createMembraneToken(r),apiUri:r.apiUri}),o=new Tn({apiKey:r.anthropicApiKey}),a={complete:c(async({prompt:l,maxTokens:u})=>{const d=await o.messages.create({model:lh,max_tokens:u,messages:[{role:"user",content:l}]});return d.content[0].type==="text"?d.content[0].text:""},"complete")};return new ki({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(),Zs(t,n.getResult());this.writeResults(t)}async readYaml(e){const t=U.join(this.testsDir,this.testBasePath,this.connectionId,e);return ir(t)}async writeYaml(e,t){const n=U.join(this.testsDir,this.testBasePath,this.connectionId,e);F.mkdirSync(U.dirname(n),{recursive:!0}),F.writeFileSync(n,Wt.dump(t,{noRefs:!0}))}writeResults(e){const t=U.join(this.testsDir,this.testBasePath,this.connectionId);F.mkdirSync(t,{recursive:!0});const n=U.join(t,"test-results.yaml");F.writeFileSync(n,Wt.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 zs.sign(n,e.workspaceSecret,r)}}wl.interpolate=/{{([\s\S]+?)}}/g;function bi(s,e){if(typeof s=="string"){const t=yl(s),n={state:e,random:{number:c(()=>Jt.number.int(),"number"),alphaNumeric:c(i=>Jt.string.alphanumeric(i),"alphaNumeric")},faker:{company:{name:c(()=>Jt.company.name(),"name"),catchPhrase:c(()=>Jt.company.catchPhrase(),"catchPhrase")},internet:{email:c(()=>Jt.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=>bi(t,e)):typeof s=="object"&&s!==null?Object.fromEntries(Object.entries(s).map(([t,n])=>[t,bi(n,e)])):s}c(bi,"processNode");function uh(s,e){return bi(s,e)}c(uh,"handleTemplate");class dh{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(`${T.bold.cyan("[start]")} ${T.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(`${T.bold.yellow("[initialized]")} ${T.yellow(e.path)}`)),o=uh(i,this.environment.state),await e.run(o),console.debug(`${T.bold.green("[success]")} ${T.yellow(e.path)}`),t=!0,r=e.getResult(),Hs(this.result,e.path,r)}catch(l){if(console.error(`${T.bold.red("[error]")} ${T.yellow(e.path)}: ${l}`),this.environment.options.fix&&!n){n=!0;try{await e.fix(l);continue}catch(u){console.error(`${T.bold.red("[fix fail]")} ${T.yellow(e.path)}: ${u}`)}}Hs(this.result,e.path,{error:Te(l)}),t=!0,r={error:Te(l)}}const a={...o,result:r};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),Zs(this.result,e.getResult())}}class Ye{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(T.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),n)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,n){try{const 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:Te(r)}),this.logMsg(`\u274C ${t}: ${r.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function Si(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)||!Ci(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=Si(r,i);o!==null&&(t[n]=o)}else t[n]=i;continue}Ci(r,i)||(t[n]=i)}return Object.keys(t).length===0?null:t}c(Si,"getNotMatchingSubFields");function Ci(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(Ci,"softCompare");class fh extends Ye{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=Vs(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=Ai(n),a=In(e.input.fields,o,{skipUnknownFields:!0}),l=In(i.record.fields,o),u=Si(l,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:l})}const r=Hc(n??{});if(r.length>0){const i={};r.forEach(a=>{const l=Vc(e.input.fields,a);typeof l<"u"&&Hs(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=Vs(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const n=Te(t),r=Vs(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:
171
172
 
172
173
  ${JSON.stringify(r,null,2)}
173
174
 
@@ -207,7 +208,7 @@ ${JSON.stringify(r,null,2)}`).join(`
207
208
 
208
209
  `)}.
209
210
 
210
- 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 vi(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=Ci(r);n[i]=await this.fetchExampleRecords(r)}return n}}class Jd extends Ve{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=ke(t),r=`I'm trying to delete a record from a data collection.
211
+ 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 Oi(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=$i(r);n[i]=await this.fetchExampleRecords(r)}return n}}class hh extends Ye{static{c(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(n){throw n}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(n){if(n?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw n}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=Te(t),r=`I'm trying to delete a record from a data collection.
211
212
 
212
213
  I tried to delete a record with this ID:
213
214
 
@@ -227,7 +228,7 @@ Format your response as a JSON object with two fields:
227
228
  "id": "fixed id"
228
229
  }.
229
230
 
230
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Hd extends Ve{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=ke(t),r=`I'm trying to find a record by ID in a data collection.
231
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class ph extends Ye{static{c(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:n}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=n}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const n=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!n.record,"Record is returned from findById"),await this.assert(()=>n.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const n=Te(t),r=`I'm trying to find a record by ID in a data collection.
231
232
 
232
233
  I tried to find a record with this ID:
233
234
 
@@ -247,7 +248,7 @@ Format your response as a JSON object with two fields:
247
248
  "id": "fixed id"
248
249
  }.
249
250
 
250
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Vd extends Ve{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=ke(t),r=`I'm trying to list records from a data collection.
251
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class mh extends Ye{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=Te(t),r=`I'm trying to list records from a data collection.
251
252
 
252
253
  I tried to list records with these parameters:
253
254
 
@@ -267,7 +268,7 @@ Format your response as a JSON object with two fields:
267
268
  "input": { ... fixed parameters ... }
268
269
  }.
269
270
 
270
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Gd extends Ve{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(()=>fi(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=ke(t),r=`I'm trying to match a record in a data collection.
271
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class gh extends Ye{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(()=>Ci(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=Te(t),r=`I'm trying to match a record in a data collection.
271
272
 
272
273
  I tried to match a record with this query:
273
274
 
@@ -287,12 +288,12 @@ Format your response as a JSON object with two fields:
287
288
  "query": { ... fixed query ... }
288
289
  }.
289
290
 
290
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class zd extends Ve{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(T.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields||{});if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
291
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class yh extends Ye{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(T.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>n,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],n=await this.getSearchQueryWithLLM(t.fields||{});if(!n)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:n},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
291
292
 
292
293
  Record fields:
293
294
  ${JSON.stringify(e,null,2)}
294
295
 
295
- Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const n=ke(t),r=`I'm trying to search records in a data collection.
296
+ Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const n=Te(t),r=`I'm trying to search records in a data collection.
296
297
 
297
298
  I tried to search records with these parameters:
298
299
 
@@ -312,7 +313,7 @@ Format your response as a JSON object with two fields:
312
313
  "input": { ... fixed parameters ... }
313
314
  }.
314
315
 
315
- 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Yd extends Ve{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 Xd extends Ve{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=qs(this.dataCollection),o=Si(i),a=Sn(e.input.fields,o,{skipUnknownFields:!0}),l=Sn(r.record.fields,o),u=ui(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=qs(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=ke(t),r=qs(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:
316
+ 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(T.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class wh extends Ye{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 bh extends Ye{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=Gs(this.dataCollection),o=Ai(i),a=In(e.input.fields,o,{skipUnknownFields:!0}),l=In(r.record.fields,o),u=Si(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=Gs(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const n=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:n}}}async fixTestCase({config:e,error:t}){const n=Te(t),r=Gs(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:
316
317
 
317
318
  ${JSON.stringify(r,null,2)}
318
319
 
@@ -352,9 +353,9 @@ ${JSON.stringify(r,null,2)}`).join(`
352
353
 
353
354
  `)}.
354
355
 
355
- 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 vi(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=Ci(r);n[i]=await this.fetchExampleRecords(r)}return n}}const di={spec:{testerClass:Yd},create:{testerClass:Wd,operationKey:"create"},"find-by-id":{testerClass:Hd,operationKey:"findById"},list:{testerClass:Vd,operationKey:"list"},match:{testerClass:Gd,operationKey:"match"},search:{testerClass:zd,operationKey:"search"},update:{testerClass:Xd,operationKey:"update"},delete:{testerClass:Jd,operationKey:"delete"}};class Qd extends Ud{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);Z.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=di[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(di).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(di).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){Z.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Zd extends td{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){Z.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(Z.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(Z.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),Z.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,f=[...a,...t?t.split("/"):[]].join("/"),d=await hi.create({connectionId:l,testBasePath:u,options:{fix:n}}),m=await d.client.get(`connections/${l}/data`),y=[],h=f?f.split("/"):[];if(h.length===0||h[0]==="data"){h[0]==="data"&&h.shift();let k,_;h.length>=1&&(_=h[0],h.length>=2&&h[1].trim()!==""&&(k=h[1]));for(const I of m){if(_&&_!==I.key)continue;const E=new Qd({environment:d,dataCollectionKey:I.key,testMethod:k});y.push(E)}}y.length===0&&(Z.error(`No test suites found for path: ${e}${f?"/"+f:""}`),process.exit(1));const w={};for(const k of y){await k.run();const _=k.getResult();Z.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Js(w,_)}console.debug("[TestRunner] All results collected:",Object.keys(w)),d.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Is=c(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
356
- `),"createExperimentalWarning");function eh(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",Is()).action(async()=>{console.warn(Is()),Z.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",Is()].join(`
357
- `)).action(async(t,n)=>{try{console.warn(Is()),t||(Z.error("Test path is required"),process.exit(1)),Z.header(`Testing: ${t}`);const r=new Zd({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),Z.success("Tests completed")}catch(r){r instanceof Error&&(Z.error(r.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(eh,"setupTestCommand");const th=c(()=>{try{const s=Xc(import.meta.url),e=vc(s),t=Ls(e,"..","package.json");return JSON.parse(Rc(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),yc=th();function nh(){const s=new Qc().name("membrane").description("Command-line interface for Membrane Agent").version(yc,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>T.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${T.cyan(n.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${T.gray("\u25B8")} ${T.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>T.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>T.gray(n.description),"optionDescription"),commandDescription:c(n=>T.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
358
- ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${yc}`)}
356
+ 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 Oi(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=$i(r);n[i]=await this.fetchExampleRecords(r)}return n}}const vi={spec:{testerClass:wh},create:{testerClass:fh,operationKey:"create"},"find-by-id":{testerClass:ph,operationKey:"findById"},list:{testerClass:mh,operationKey:"list"},match:{testerClass:gh,operationKey:"match"},search:{testerClass:yh,operationKey:"search"},update:{testerClass:bh,operationKey:"update"},delete:{testerClass:hh,operationKey:"delete"}};class Sh extends dh{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);Z.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=vi[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(vi).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(vi).filter(([,t])=>{const n="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,n)}).map(([t])=>t)}displayTestSummary(e){Z.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Ch extends kf{static{c(this,"TestRunner")}constructor(e){super(e)}async initialize(){Z.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:n}=this.options,r=e.split("/");r.length<2&&(Z.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[i,o,...a]=r;i!=="connectors"&&(Z.error(`Test type "${i}" is not yet fully implemented. Currently only "connectors" is fully supported.`),Z.error("Supported test types: connectors"),process.exit(1));const l=o,u=i,d=[...a,...t?t.split("/"):[]].join("/"),f=await ki.create({connectionId:l,testBasePath:u,options:{fix:n}}),g=await f.client.get(`connections/${l}/data`),y=[],p=d?d.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 O of g){if(E&&E!==O.key)continue;const I=new Sh({environment:f,dataCollectionKey:O.key,testMethod:k});y.push(I)}}y.length===0&&(Z.error(`No test suites found for path: ${e}${d?"/"+d:""}`),process.exit(1));const w={};for(const k of y){await k.run();const E=k.getResult();Z.debug(`Suite ${k.constructor.name} result:`,{prefix:"TestRunner"}),Zs(w,E)}console.debug("[TestRunner] All results collected:",Object.keys(w)),f.writeResults(w)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Ms=c(()=>[T.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),T.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),T.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),T.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),T.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),T.yellow("\u2502 Use in production environments is not recommended. \u2502"),T.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
357
+ `),"createExperimentalWarning");function vh(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",Ms()).action(async()=>{console.warn(Ms()),Z.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",T.bold("Examples:"),` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${T.gray("\u25B8")} ${T.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",T.gray("For more information, visit:"),T.blue(" https://docs.integration.app/cli"),"",Ms()].join(`
358
+ `)).action(async(t,n)=>{try{console.warn(Ms()),t||(Z.error("Test path is required"),process.exit(1)),Z.header(`Testing: ${t}`);const r=new Ch({testPath:t,path:n.path,fix:n.fix});await r.initialize(),await r.run(),Z.success("Tests completed")}catch(r){r instanceof Error&&(Z.error(r.message),process.exit(1)),Z.error("An unknown error occurred"),process.exit(1)}})}c(vh,"setupTestCommand");const kh=c(()=>{try{const s=fl(import.meta.url),e=Rc(s),t=Ks(e,"..","package.json");return JSON.parse(Yc(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),$c=kh();function Th(){const s=new hl().name("membrane").description("Command-line interface for Membrane Agent").version($c,"-v, --version","Output the version number").option("--verbose","Enable verbose logging (shows debug messages)");s.configureHelp({sortSubcommands:!0,subcommandTerm:c(n=>T.cyan(n.name()),"subcommandTerm"),commandUsage:c(n=>n.name()==="membrane"?`${T.cyan(n.name())} ${T.gray("[options]")} ${T.cyan("[command]")}`:n.usage(),"commandUsage"),optionTerm:c(n=>{const r=n.flags;return`${T.gray("\u25B8")} ${T.cyan(r)}`},"optionTerm"),subcommandDescription:c(n=>T.gray(n.description()),"subcommandDescription"),optionDescription:c(n=>T.gray(n.description),"optionDescription"),commandDescription:c(n=>T.gray(n.description()),"commandDescription")}),s.addHelpText("beforeAll",`
359
+ ${T.bold.cyan("Membrane Agent CLI")} ${T.gray(`v${$c}`)}
359
360
 
360
- `);const e=new ua(Yt.Cli,process.cwd());Xf(s,e),ed(s,e),Kf(s,e),Ff(s,e),Gf(s),eh(s),Jf(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(nh,"runCLI");const wc=["--cwd","--verbose"];function sh(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&wc.includes(s[t-1])?!1:!wc.includes(e))}c(sh,"hasCLIArguments"),sh()?nh():Nf();
361
+ `);const e=new Ca(nn.Cli,process.cwd());bf(s,e),vf(s,e),af(s,e),Xd(s,e),of(s,e),gf(s),vh(s),hf(s),process.argv.length===2&&(s.outputHelp(),process.exit(0)),s.parse(),s.opts().verbose&&b.setVerboseMode(!0)}c(Th,"runCLI");const Nc=["--cwd","--verbose"];function Eh(){const s=process.argv.slice(2);return s.some((e,t)=>t>0&&Nc.includes(s[t-1])?!1:!Nc.includes(e))}c(Eh,"hasCLIArguments"),Eh()?Th():Wd();