@membranehq/cli 0.1.3 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +156 -153
- package/package.json +5 -2
package/dist/index.js
CHANGED
|
@@ -1,150 +1,153 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var ca=Object.defineProperty;var c=(s,e)=>ca(s,"name",{value:e,configurable:!0});import{jsx as S,jsxs as J}from"react/jsx-runtime";import*as we from"node:path";import{resolve as la,dirname as ua,join as da}from"node:path";import{Box as F,Text as M,useInput as $n,render as fa}from"ink";import ha from"minimist";import{SWRConfig as pa}from"swr";import{exec as ma}from"node:child_process";import{createContext as In,useContext as Ln,useState as ne,useEffect as Ps,useCallback as Rs}from"react";import{TextInput as ya,Select as ga}from"@inkjs/ui";import jn from"ink-spinner";import Ds from"swr/immutable";import*as gt from"node:fs";import{readFileSync as wa}from"node:fs";import fe from"js-yaml";import ba from"ink-text-input";import va from"os";import B from"path";import ka from"conf";import{WorkspaceElementSpecs as he,WorkspaceElementType as $,IntegrationAppClient as Kt,setValueAtLocator as Pn,extractIntegrationAppErrorData as pe,getDataCollectionCreateFields as Rn,excludeWriteOnlyFieldsFromSchema as Ks,valueToSchema as Mt,getRequiredFieldsFromSchema as _a,getValueAtLocator as Sa,walkSchema as Ms,makeDataLocationPath as Bs,getDataCollectionUpdateFields as Dn}from"@integration-app/sdk";import Bt from"jsonwebtoken";import*as Ca from"node:crypto";import{EventEmitter as Oa}from"node:events";import Ta from"chokidar";import v from"chalk";import{fileURLToPath as Aa}from"node:url";import{Command as Ea}from"commander";import R from"fs";import xa from"archiver";import Na from"form-data";import $a from"unzipper";import Kn from"lodash/merge.js";import Ia from"@anthropic-ai/sdk";import{faker as wt}from"@faker-js/faker";import La from"lodash/template.js";import ja from"lodash/templateSettings.js";const Pa=c(()=>{const s=Math.min(100,process.stdout.columns||100);return S(F,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:s,children:S(F,{marginTop:-1,marginBottom:1,children:J(M,{bold:!0,children:["\u{1F916} Membrane Code Agent \u2014 ",S(M,{color:"green",children:"active"})]})})})},"AgentStatus");var U;(function(s){s.assertEqual=r=>{};function e(r){}c(e,"assertIs"),s.assertIs=e;function t(r){throw new Error}c(t,"assertNever"),s.assertNever=t,s.arrayToEnum=r=>{const i={};for(const a of r)i[a]=a;return i},s.getValidEnumValues=r=>{const i=s.objectKeys(r).filter(o=>typeof r[r[o]]!="number"),a={};for(const o of i)a[o]=r[o];return s.objectValues(a)},s.objectValues=r=>s.objectKeys(r).map(function(i){return r[i]}),s.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const i=[];for(const a in r)Object.prototype.hasOwnProperty.call(r,a)&&i.push(a);return i},s.find=(r,i)=>{for(const a of r)if(i(a))return a},s.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function n(r,i=" | "){return r.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}c(n,"joinValues"),s.joinValues=n,s.jsonStringifyReplacer=(r,i)=>typeof i=="bigint"?i.toString():i})(U||(U={}));var Fs;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Fs||(Fs={}));const O=U.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Se=c(s=>{switch(typeof s){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(s)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(s)?O.array:s===null?O.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?O.promise:typeof Map<"u"&&s instanceof Map?O.map:typeof Set<"u"&&s instanceof Set?O.set:typeof Date<"u"&&s instanceof Date?O.date:O.object;default:return O.unknown}},"getParsedType"),g=U.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class ke extends Error{static{c(this,"ZodError")}get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(i){return i.message},n={_errors:[]},r=c(i=>{for(const a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(r);else if(a.code==="invalid_return_type")r(a.returnTypeError);else if(a.code==="invalid_arguments")r(a.argumentsError);else if(a.path.length===0)n._errors.push(t(a));else{let o=n,l=0;for(;l<a.path.length;){const u=a.path[l];l===a.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(a))):o[u]=o[u]||{_errors:[]},o=o[u],l++}}},"processError");return r(this),n}static assert(e){if(!(e instanceof ke))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,U.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},n=[];for(const r of this.issues)if(r.path.length>0){const i=r.path[0];t[i]=t[i]||[],t[i].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}}ke.create=s=>new ke(s);const Mn=c((s,e)=>{let t;switch(s.code){case g.invalid_type:s.received===O.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case g.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,U.jsonStringifyReplacer)}`;break;case g.unrecognized_keys:t=`Unrecognized key(s) in object: ${U.joinValues(s.keys,", ")}`;break;case g.invalid_union:t="Invalid input";break;case g.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${U.joinValues(s.options)}`;break;case g.invalid_enum_value:t=`Invalid enum value. Expected ${U.joinValues(s.options)}, received '${s.received}'`;break;case g.invalid_arguments:t="Invalid function arguments";break;case g.invalid_return_type:t="Invalid function return type";break;case g.invalid_date:t="Invalid date";break;case g.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:U.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case g.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case g.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case g.custom:t="Invalid input";break;case g.invalid_intersection_types:t="Intersection results could not be merged";break;case g.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case g.not_finite:t="Number must be finite";break;default:t=e.defaultError,U.assertNever(s)}return{message:t}},"errorMap");let Ra=Mn;function Da(){return Ra}c(Da,"getErrorMap");const Ka=c(s=>{const{data:e,path:t,errorMaps:n,issueData:r}=s,i=[...t,...r.path||[]],a={...r,path:i};if(r.message!==void 0)return{...r,path:i,message:r.message};let o="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)o=u(a,{data:e,defaultError:o}).message;return{...r,path:i,message:o}},"makeIssue");function k(s,e){const t=Da(),n=Ka({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Mn?void 0:Mn].filter(r=>!!r)});s.common.issues.push(n)}c(k,"addIssueToContext");class ie{static{c(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const n=[];for(const r of t){if(r.status==="aborted")return L;r.status==="dirty"&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){const n=[];for(const r of t){const i=await r.key,a=await r.value;n.push({key:i,value:a})}return ie.mergeObjectSync(e,n)}static mergeObjectSync(e,t){const n={};for(const r of t){const{key:i,value:a}=r;if(i.status==="aborted"||a.status==="aborted")return L;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||r.alwaysSet)&&(n[i.value]=a.value)}return{status:e.value,value:n}}}const L=Object.freeze({status:"aborted"}),bt=c(s=>({status:"dirty",value:s}),"DIRTY"),ae=c(s=>({status:"valid",value:s}),"OK"),qs=c(s=>s.status==="aborted","isAborted"),Us=c(s=>s.status==="dirty","isDirty"),qe=c(s=>s.status==="valid","isValid"),Ft=c(s=>typeof Promise<"u"&&s instanceof Promise,"isAsync");var T;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(T||(T={}));class Ce{static{c(this,"ParseInputLazyPath")}constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Vs=c((s,e)=>{if(qe(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new ke(s.common.issues);return this._error=t,this._error}}},"handleResult");function D(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:n,description:r}=s;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:c((a,o)=>{const{message:l}=s;return a.code==="invalid_enum_value"?{message:l??o.defaultError}:typeof o.data>"u"?{message:l??n??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:l??t??o.defaultError}},"customMap"),description:r}}c(D,"processCreateParams");class q{static{c(this,"ZodType")}get description(){return this._def.description}_getType(e){return Se(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ie,ctx:{common:e.parent.common,data:e.data,parsedType:Se(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Ft(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){const n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Vs(n,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:t});return qe(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>qe(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){const n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){const n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Se(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(Ft(r)?r:Promise.resolve(r));return Vs(n,i)}refine(e,t){const n=c(r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t,"getIssueProperties");return this._refinement((r,i)=>{const a=e(r),o=c(()=>i.addIssue({code:g.custom,...n(r)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t=="function"?t(n,r):t),!1))}_refinement(e){return new Ve({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:c(t=>this["~validate"](t),"validate")}}optional(){return Te.create(this,this._def)}nullable(){return Ze.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ge.create(this)}promise(){return Vt.create(this,this._def)}or(e){return qt.create([this,e],this._def)}and(e){return Ut.create(this,e,this._def)}transform(e){return new Ve({...D(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new qn({...D(this._def),innerType:this,defaultValue:t,typeName:j.ZodDefault})}brand(){return new oo({typeName:j.ZodBranded,type:this,...D(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Un({...D(this._def),innerType:this,catchValue:t,typeName:j.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Is.create(this,e)}readonly(){return Vn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ma=/^c[^\s-]{8,}$/i,Ba=/^[0-9a-z]+$/,Fa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qa=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ua=/^[a-z0-9_-]{21}$/i,Va=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Za=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ja=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,za="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Bn;const Wa=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ga=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Ha=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Ya=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Qa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Xa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Zs="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",eo=new RegExp(`^${Zs}$`);function Js(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}c(Js,"timeRegexSource");function to(s){return new RegExp(`^${Js(s)}$`)}c(to,"timeRegex");function no(s){let e=`${Zs}T${Js(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}c(no,"datetimeRegex");function so(s,e){return!!((e==="v4"||!e)&&Wa.test(s)||(e==="v6"||!e)&&Ha.test(s))}c(so,"isValidIP");function ro(s,e){if(!Va.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(n));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}c(ro,"isValidJWT");function io(s,e){return!!((e==="v4"||!e)&&Ga.test(s)||(e==="v6"||!e)&&Ya.test(s))}c(io,"isValidCidr");class Ie extends q{static{c(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){const i=this._getOrReturnCtx(e);return k(i,{code:g.invalid_type,expected:O.string,received:i.parsedType}),L}const n=new ie;let r;for(const i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(r=this._getOrReturnCtx(e,r),k(r,{code:g.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="max")e.data.length>i.value&&(r=this._getOrReturnCtx(e,r),k(r,{code:g.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),n.dirty());else if(i.kind==="length"){const a=e.data.length>i.value,o=e.data.length<i.value;(a||o)&&(r=this._getOrReturnCtx(e,r),a?k(r,{code:g.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):o&&k(r,{code:g.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),n.dirty())}else if(i.kind==="email")Ja.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"email",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="emoji")Bn||(Bn=new RegExp(za,"u")),Bn.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"emoji",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="uuid")qa.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"uuid",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="nanoid")Ua.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"nanoid",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid")Ma.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"cuid",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="cuid2")Ba.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"cuid2",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="ulid")Fa.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"ulid",code:g.invalid_string,message:i.message}),n.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),k(r,{validation:"url",code:g.invalid_string,message:i.message}),n.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"regex",code:g.invalid_string,message:i.message}),n.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),n.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:{startsWith:i.value},message:i.message}),n.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:{endsWith:i.value},message:i.message}),n.dirty()):i.kind==="datetime"?no(i).test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:"datetime",message:i.message}),n.dirty()):i.kind==="date"?eo.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:"date",message:i.message}),n.dirty()):i.kind==="time"?to(i).test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{code:g.invalid_string,validation:"time",message:i.message}),n.dirty()):i.kind==="duration"?Za.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"duration",code:g.invalid_string,message:i.message}),n.dirty()):i.kind==="ip"?so(e.data,i.version)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"ip",code:g.invalid_string,message:i.message}),n.dirty()):i.kind==="jwt"?ro(e.data,i.alg)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"jwt",code:g.invalid_string,message:i.message}),n.dirty()):i.kind==="cidr"?io(e.data,i.version)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"cidr",code:g.invalid_string,message:i.message}),n.dirty()):i.kind==="base64"?Qa.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"base64",code:g.invalid_string,message:i.message}),n.dirty()):i.kind==="base64url"?Xa.test(e.data)||(r=this._getOrReturnCtx(e,r),k(r,{validation:"base64url",code:g.invalid_string,message:i.message}),n.dirty()):U.assertNever(i);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(r=>e.test(r),{validation:t,code:g.invalid_string,...T.errToObj(n)})}_addCheck(e){return new Ie({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...T.errToObj(e)})}url(e){return this._addCheck({kind:"url",...T.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...T.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...T.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...T.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...T.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...T.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...T.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...T.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...T.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...T.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...T.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...T.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...T.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...T.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...T.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...T.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...T.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...T.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...T.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...T.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...T.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...T.errToObj(t)})}nonempty(e){return this.min(1,T.errToObj(e))}trim(){return new Ie({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Ie({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Ie({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Ie.create=s=>new Ie({checks:[],typeName:j.ZodString,coerce:s?.coerce??!1,...D(s)});function ao(s,e){const t=(s.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,r=t>n?t:n,i=Number.parseInt(s.toFixed(r).replace(".","")),a=Number.parseInt(e.toFixed(r).replace(".",""));return i%a/10**r}c(ao,"floatSafeRemainder");class Pt extends q{static{c(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==O.number){const i=this._getOrReturnCtx(e);return k(i,{code:g.invalid_type,expected:O.number,received:i.parsedType}),L}let n;const r=new ie;for(const i of this._def.checks)i.kind==="int"?U.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),k(n,{code:g.invalid_type,expected:"integer",received:"float",message:i.message}),r.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),r.dirty()):i.kind==="multipleOf"?ao(e.data,i.value)!==0&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),k(n,{code:g.not_finite,message:i.message}),r.dirty()):U.assertNever(i);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,n,r){return new Pt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:T.toString(r)}]})}_addCheck(e){return new Pt({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:T.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:T.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&U.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Pt.create=s=>new Pt({checks:[],typeName:j.ZodNumber,coerce:s?.coerce||!1,...D(s)});class Rt extends q{static{c(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==O.bigint)return this._getInvalidInput(e);let n;const r=new ie;for(const i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),r.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),k(n,{code:g.not_multiple_of,multipleOf:i.value,message:i.message}),r.dirty()):U.assertNever(i);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return k(t,{code:g.invalid_type,expected:O.bigint,received:t.parsedType}),L}gte(e,t){return this.setLimit("min",e,!0,T.toString(t))}gt(e,t){return this.setLimit("min",e,!1,T.toString(t))}lte(e,t){return this.setLimit("max",e,!0,T.toString(t))}lt(e,t){return this.setLimit("max",e,!1,T.toString(t))}setLimit(e,t,n,r){return new Rt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:T.toString(r)}]})}_addCheck(e){return new Rt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:T.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Rt.create=s=>new Rt({checks:[],typeName:j.ZodBigInt,coerce:s?.coerce??!1,...D(s)});class zs extends q{static{c(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.boolean,received:n.parsedType}),L}return ae(e.data)}}zs.create=s=>new zs({typeName:j.ZodBoolean,coerce:s?.coerce||!1,...D(s)});class xn extends q{static{c(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){const i=this._getOrReturnCtx(e);return k(i,{code:g.invalid_type,expected:O.date,received:i.parsedType}),L}if(Number.isNaN(e.data.getTime())){const i=this._getOrReturnCtx(e);return k(i,{code:g.invalid_date}),L}const n=new ie;let r;for(const i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(r=this._getOrReturnCtx(e,r),k(r,{code:g.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),n.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(r=this._getOrReturnCtx(e,r),k(r,{code:g.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),n.dirty()):U.assertNever(i);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new xn({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:T.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:T.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}xn.create=s=>new xn({checks:[],coerce:s?.coerce||!1,typeName:j.ZodDate,...D(s)});class Ws extends q{static{c(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==O.symbol){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.symbol,received:n.parsedType}),L}return ae(e.data)}}Ws.create=s=>new Ws({typeName:j.ZodSymbol,...D(s)});class Gs extends q{static{c(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.undefined,received:n.parsedType}),L}return ae(e.data)}}Gs.create=s=>new Gs({typeName:j.ZodUndefined,...D(s)});class Hs extends q{static{c(this,"ZodNull")}_parse(e){if(this._getType(e)!==O.null){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.null,received:n.parsedType}),L}return ae(e.data)}}Hs.create=s=>new Hs({typeName:j.ZodNull,...D(s)});class Ys extends q{static{c(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return ae(e.data)}}Ys.create=s=>new Ys({typeName:j.ZodAny,...D(s)});class Qs extends q{static{c(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return ae(e.data)}}Qs.create=s=>new Qs({typeName:j.ZodUnknown,...D(s)});class Oe extends q{static{c(this,"ZodNever")}_parse(e){const t=this._getOrReturnCtx(e);return k(t,{code:g.invalid_type,expected:O.never,received:t.parsedType}),L}}Oe.create=s=>new Oe({typeName:j.ZodNever,...D(s)});class Xs extends q{static{c(this,"ZodVoid")}_parse(e){if(this._getType(e)!==O.undefined){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.void,received:n.parsedType}),L}return ae(e.data)}}Xs.create=s=>new Xs({typeName:j.ZodVoid,...D(s)});class ge extends q{static{c(this,"ZodArray")}_parse(e){const{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==O.array)return k(t,{code:g.invalid_type,expected:O.array,received:t.parsedType}),L;if(r.exactLength!==null){const a=t.data.length>r.exactLength.value,o=t.data.length<r.exactLength.value;(a||o)&&(k(t,{code:a?g.too_big:g.too_small,minimum:o?r.exactLength.value:void 0,maximum:a?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(k(t,{code:g.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(k(t,{code:g.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>r.type._parseAsync(new Ce(t,a,t.path,o)))).then(a=>ie.mergeArray(n,a));const i=[...t.data].map((a,o)=>r.type._parseSync(new Ce(t,a,t.path,o)));return ie.mergeArray(n,i)}get element(){return this._def.type}min(e,t){return new ge({...this._def,minLength:{value:e,message:T.toString(t)}})}max(e,t){return new ge({...this._def,maxLength:{value:e,message:T.toString(t)}})}length(e,t){return new ge({...this._def,exactLength:{value:e,message:T.toString(t)}})}nonempty(e){return this.min(1,e)}}ge.create=(s,e)=>new ge({type:s,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...D(e)});function Ue(s){if(s instanceof H){const e={};for(const t in s.shape){const n=s.shape[t];e[t]=Te.create(Ue(n))}return new H({...s._def,shape:c(()=>e,"shape")})}else return s instanceof ge?new ge({...s._def,type:Ue(s.element)}):s instanceof Te?Te.create(Ue(s.unwrap())):s instanceof Ze?Ze.create(Ue(s.unwrap())):s instanceof Be?Be.create(s.items.map(e=>Ue(e))):s}c(Ue,"deepPartialify");class H extends q{static{c(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=U.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==O.object){const u=this._getOrReturnCtx(e);return k(u,{code:g.invalid_type,expected:O.object,received:u.parsedType}),L}const{status:n,ctx:r}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Oe&&this._def.unknownKeys==="strip"))for(const u in r.data)a.includes(u)||o.push(u);const l=[];for(const u of a){const d=i[u],f=r.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Ce(r,f,r.path,u)),alwaysSet:u in r.data})}if(this._def.catchall instanceof Oe){const u=this._def.unknownKeys;if(u==="passthrough")for(const d of o)l.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(u==="strict")o.length>0&&(k(r,{code:g.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const d of o){const f=r.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Ce(r,f,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const u=[];for(const d of l){const f=await d.key,h=await d.value;u.push({key:f,value:h,alwaysSet:d.alwaysSet})}return u}).then(u=>ie.mergeObjectSync(n,u)):ie.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return T.errToObj,new H({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:c((t,n)=>{const r=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:T.errToObj(e).message??r}:{message:r}},"errorMap")}:{}})}strip(){return new H({...this._def,unknownKeys:"strip"})}passthrough(){return new H({...this._def,unknownKeys:"passthrough"})}extend(e){return new H({...this._def,shape:c(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new H({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:c(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:j.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new H({...this._def,catchall:e})}pick(e){const t={};for(const n of U.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new H({...this._def,shape:c(()=>t,"shape")})}omit(e){const t={};for(const n of U.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new H({...this._def,shape:c(()=>t,"shape")})}deepPartial(){return Ue(this)}partial(e){const t={};for(const n of U.objectKeys(this.shape)){const r=this.shape[n];e&&!e[n]?t[n]=r:t[n]=r.optional()}return new H({...this._def,shape:c(()=>t,"shape")})}required(e){const t={};for(const n of U.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let i=this.shape[n];for(;i instanceof Te;)i=i._def.innerType;t[n]=i}return new H({...this._def,shape:c(()=>t,"shape")})}keyof(){return sr(U.objectKeys(this.shape))}}H.create=(s,e)=>new H({shape:c(()=>s,"shape"),unknownKeys:"strip",catchall:Oe.create(),typeName:j.ZodObject,...D(e)}),H.strictCreate=(s,e)=>new H({shape:c(()=>s,"shape"),unknownKeys:"strict",catchall:Oe.create(),typeName:j.ZodObject,...D(e)}),H.lazycreate=(s,e)=>new H({shape:s,unknownKeys:"strip",catchall:Oe.create(),typeName:j.ZodObject,...D(e)});class qt extends q{static{c(this,"ZodUnion")}_parse(e){const{ctx:t}=this._processInputParams(e),n=this._def.options;function r(i){for(const o of i)if(o.result.status==="valid")return o.result;for(const o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=i.map(o=>new ke(o.ctx.common.issues));return k(t,{code:g.invalid_union,unionErrors:a}),L}if(c(r,"handleResults"),t.common.async)return Promise.all(n.map(async i=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(r);{let i;const a=[];for(const l of n){const u={...t,common:{...t.common,issues:[]},parent:null},d=l._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;const o=a.map(l=>new ke(l));return k(t,{code:g.invalid_union,unionErrors:o}),L}}get options(){return this._def.options}}qt.create=(s,e)=>new qt({options:s,typeName:j.ZodUnion,...D(e)});function Fn(s,e){const t=Se(s),n=Se(e);if(s===e)return{valid:!0,data:s};if(t===O.object&&n===O.object){const r=U.objectKeys(e),i=U.objectKeys(s).filter(o=>r.indexOf(o)!==-1),a={...s,...e};for(const o of i){const l=Fn(s[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===O.array&&n===O.array){if(s.length!==e.length)return{valid:!1};const r=[];for(let i=0;i<s.length;i++){const a=s[i],o=e[i],l=Fn(a,o);if(!l.valid)return{valid:!1};r.push(l.data)}return{valid:!0,data:r}}else return t===O.date&&n===O.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}c(Fn,"mergeValues");class Ut extends q{static{c(this,"ZodIntersection")}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=c((i,a)=>{if(qs(i)||qs(a))return L;const o=Fn(i.value,a.value);return o.valid?((Us(i)||Us(a))&&t.dirty(),{status:t.value,value:o.data}):(k(n,{code:g.invalid_intersection_types}),L)},"handleParsed");return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([i,a])=>r(i,a)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}Ut.create=(s,e,t)=>new Ut({left:s,right:e,typeName:j.ZodIntersection,...D(t)});class Be extends q{static{c(this,"ZodTuple")}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return k(n,{code:g.invalid_type,expected:O.array,received:n.parsedType}),L;if(n.data.length<this._def.items.length)return k(n,{code:g.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),L;!this._def.rest&&n.data.length>this._def.items.length&&(k(n,{code:g.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const i=[...n.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new Ce(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(i).then(a=>ie.mergeArray(t,a)):ie.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Be({...this._def,rest:e})}}Be.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Be({items:s,typeName:j.ZodTuple,rest:null,...D(e)})};class er extends q{static{c(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.map)return k(n,{code:g.invalid_type,expected:O.map,received:n.parsedType}),L;const r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([o,l],u)=>({key:r._parse(new Ce(n,o,n.path,[u,"key"])),value:i._parse(new Ce(n,l,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return L;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const l of a){const u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return L;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}}}}er.create=(s,e,t)=>new er({valueType:e,keyType:s,typeName:j.ZodMap,...D(t)});class Dt extends q{static{c(this,"ZodSet")}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return k(n,{code:g.invalid_type,expected:O.set,received:n.parsedType}),L;const r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(k(n,{code:g.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(k(n,{code:g.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const i=this._def.valueType;function a(l){const u=new Set;for(const d of l){if(d.status==="aborted")return L;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}c(a,"finalizeSet");const o=[...n.data.values()].map((l,u)=>i._parse(new Ce(n,l,n.path,u)));return n.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new Dt({...this._def,minSize:{value:e,message:T.toString(t)}})}max(e,t){return new Dt({...this._def,maxSize:{value:e,message:T.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Dt.create=(s,e)=>new Dt({valueType:s,minSize:null,maxSize:null,typeName:j.ZodSet,...D(e)});class tr extends q{static{c(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}tr.create=(s,e)=>new tr({getter:s,typeName:j.ZodLazy,...D(e)});class nr extends q{static{c(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return k(t,{received:t.data,code:g.invalid_literal,expected:this._def.value}),L}return{status:"valid",value:e.data}}get value(){return this._def.value}}nr.create=(s,e)=>new nr({value:s,typeName:j.ZodLiteral,...D(e)});function sr(s,e){return new yt({values:s,typeName:j.ZodEnum,...D(e)})}c(sr,"createZodEnum");class yt extends q{static{c(this,"ZodEnum")}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),n=this._def.values;return k(t,{expected:U.joinValues(n),received:t.parsedType,code:g.invalid_type}),L}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),n=this._def.values;return k(t,{received:t.data,code:g.invalid_enum_value,options:n}),L}return ae(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return yt.create(e,{...this._def,...t})}exclude(e,t=this._def){return yt.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}}yt.create=sr;class rr extends q{static{c(this,"ZodNativeEnum")}_parse(e){const t=U.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){const r=U.objectValues(t);return k(n,{expected:U.joinValues(r),received:n.parsedType,code:g.invalid_type}),L}if(this._cache||(this._cache=new Set(U.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=U.objectValues(t);return k(n,{received:n.data,code:g.invalid_enum_value,options:r}),L}return ae(e.data)}get enum(){return this._def.values}}rr.create=(s,e)=>new rr({values:s,typeName:j.ZodNativeEnum,...D(e)});class Vt extends q{static{c(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==O.promise&&t.common.async===!1)return k(t,{code:g.invalid_type,expected:O.promise,received:t.parsedType}),L;const n=t.parsedType===O.promise?t.data:Promise.resolve(t.data);return ae(n.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Vt.create=(s,e)=>new Vt({type:s,typeName:j.ZodPromise,...D(e)});class Ve extends q{static{c(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:c(a=>{k(n,a),a.fatal?t.abort():t.dirty()},"addIssue"),get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type==="preprocess"){const a=r.transform(n.data,i);if(n.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return L;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?L:l.status==="dirty"||t.value==="dirty"?bt(l.value):l});{if(t.value==="aborted")return L;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?L:o.status==="dirty"||t.value==="dirty"?bt(o.value):o}}if(r.type==="refinement"){const a=c(o=>{const l=r.refinement(o,i);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o},"executeRefinement");if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?L:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?L:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(r.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!qe(a))return L;const o=r.transform(a.value,i);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>qe(a)?Promise.resolve(r.transform(a.value,i)).then(o=>({status:t.value,value:o})):L);U.assertNever(r)}}Ve.create=(s,e,t)=>new Ve({schema:s,typeName:j.ZodEffects,effect:e,...D(t)}),Ve.createWithPreprocess=(s,e,t)=>new Ve({schema:e,effect:{type:"preprocess",transform:s},typeName:j.ZodEffects,...D(t)});class Te extends q{static{c(this,"ZodOptional")}_parse(e){return this._getType(e)===O.undefined?ae(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Te.create=(s,e)=>new Te({innerType:s,typeName:j.ZodOptional,...D(e)});class Ze extends q{static{c(this,"ZodNullable")}_parse(e){return this._getType(e)===O.null?ae(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Ze.create=(s,e)=>new Ze({innerType:s,typeName:j.ZodNullable,...D(e)});class qn extends q{static{c(this,"ZodDefault")}_parse(e){const{ctx:t}=this._processInputParams(e);let n=t.data;return t.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}qn.create=(s,e)=>new qn({innerType:s,typeName:j.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...D(e)});class Un extends q{static{c(this,"ZodCatch")}_parse(e){const{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ft(r)?r.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new ke(n.common.issues)},input:n.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ke(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}Un.create=(s,e)=>new Un({innerType:s,typeName:j.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...D(e)});class ir extends q{static{c(this,"ZodNaN")}_parse(e){if(this._getType(e)!==O.nan){const n=this._getOrReturnCtx(e);return k(n,{code:g.invalid_type,expected:O.nan,received:n.parsedType}),L}return{status:"valid",value:e.data}}}ir.create=s=>new ir({typeName:j.ZodNaN,...D(s)});class oo extends q{static{c(this,"ZodBranded")}_parse(e){const{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}}class Is extends q{static{c(this,"ZodPipeline")}_parse(e){const{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return c(async()=>{const i=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?L:i.status==="dirty"?(t.dirty(),bt(i.value)):this._def.out._parseAsync({data:i.value,path:n.path,parent:n})},"handleAsync")();{const r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return r.status==="aborted"?L:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new Is({in:e,out:t,typeName:j.ZodPipeline})}}class Vn extends q{static{c(this,"ZodReadonly")}_parse(e){const t=this._def.innerType._parse(e),n=c(r=>(qe(r)&&(r.value=Object.freeze(r.value)),r),"freeze");return Ft(t)?t.then(r=>n(r)):n(t)}unwrap(){return this._def.innerType}}Vn.create=(s,e)=>new Vn({innerType:s,typeName:j.ZodReadonly,...D(e)});var j;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(j||(j={}));const vt=Ie.create;Oe.create,ge.create;const co=H.create;qt.create,Ut.create,Be.create;const lo=yt.create;Vt.create,Te.create,Ze.create;const ar=In(process.cwd());function uo({cwd:s,children:e}){return S(ar.Provider,{value:s,children:e})}c(uo,"CwdProvider");function Zn(){return Ln(ar)}c(Zn,"useCwd");const fo="membrane.config.yml";function Le(s){const e=we.join(s??process.cwd(),fo);try{const t=gt.readFileSync(e,"utf8"),n=fe.load(t),r=or.safeParse(n);return r.success?r.data:null}catch{return null}}c(Le,"readProjectConfig");const ho="membrane.config.yml",or=co({workspaceKey:vt().optional(),workspaceSecret:vt().optional(),apiUri:vt().optional(),testCustomerId:vt().optional(),anthropicApiKey:vt().optional()});lo(["pull"]);const cr=In(void 0);function po({children:s}){const e=Zn(),[t,n]=ne(null),[r,i]=ne(!0);Ps(()=>{const u=Le(e);n(u),i(!1)},[e]);const a=Rs(u=>{const d=we.join(e,ho),h={...Le(e)??{},...u},y=or.safeParse(h);return y.success?(gt.writeFileSync(d,fe.dump(y.data)),n(y.data),!0):!1},[e]),o=Rs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),l={config:t,isLoading:r,updateConfig:a,validateConfig:o};return S(cr.Provider,{value:l,children:s})}c(po,"ProjectConfigProvider");function Jn(){const s=Ln(cr);if(s===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return s}c(Jn,"useProjectConfig");const lr=c(({onExit:s,showEscOption:e=!0})=>{const[t,n]=ne(""),{data:r,error:i,isLoading:a}=Ds("/account"),{updateConfig:o,isLoading:l}=Jn(),u=r?.workspaces,d=a||l;if($n((m,b)=>{b.escape&&s?.()}),d)return J(F,{children:[S(jn,{}),S(M,{children:" Fetching workspaces..."})]});if(i)return J(F,{flexDirection:"column",children:[J(M,{color:"red",children:["Error: ",i.message]}),S(F,{marginTop:1,children:S(M,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(m=>m.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(m=>({label:m.name,value:m.id})),y=h.length,w=u?.length??0,p=c(async m=>{const b=f.find(E=>E.id===m);if(!b)return;const{key:_,secret:C}=b;!_||!C||(await o({workspaceKey:_,workspaceSecret:C}),s?.())},"handleSelect");return J(F,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[S(F,{marginTop:-1,children:S(M,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),J(F,{marginTop:1,children:[S(M,{children:"Search: "}),S(ya,{placeholder:"Enter a search query...",onChange:n})]}),w>5&&J(M,{children:["Showing ",y," of ",w," workspaces."]}),S(F,{marginTop:1,children:S(ga,{options:h,onChange:c(m=>{m&&p(m)},"onChange")})}),e&&S(F,{marginTop:1,children:S(M,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),mo=c(({currentPat:s,onSubmit:e})=>{const[t,n]=ne(""),[r,i]=ne(!1),[a,o]=ne(null);return J(F,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[S(F,{marginTop:-1,marginBottom:1,children:S(M,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),S(M,{children:"Please provide your Personal Access Token. You can find it here:"}),S(F,{marginTop:1,marginBottom:1,children:S(M,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),s&&S(M,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),S(ba,{mask:"*",placeholder:`${s?"******":"Enter your token here..."}`,value:t,onChange:n,onSubmit:c(async u=>{o(null),i(!0);try{await e(u),n("")}catch{o("Invalid token. Please try again.")}finally{i(!1)}},"handleSubmit")}),r&&S(F,{marginTop:1,children:J(M,{children:[S(jn,{type:"dots"})," Validating token..."]})}),a&&S(M,{color:"red",children:a})]})},"PersonalAccessTokenInput"),yo={pat:{type:"string"},workspace:{type:"object"}},zn=new ka({schema:yo,configName:"config",cwd:B.join(va.homedir(),".membrane")}),go=c(s=>{zn.set("pat",s)},"setPat"),ur=c(()=>zn.get("pat"),"getPat"),wo=c(()=>!!zn.get("pat"),"hasPat"),dr="https://api.integration.app";class fr{static{c(this,"AccountApiClient")}constructor(e=dr){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 a=ur();if(!a)throw new Error("Personal Access Token not found.");n.set("Authorization",`Bearer ${a}`)}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 a=await r.text();throw new Error(`API request failed: ${r.status} ${r.statusText} - ${a}`)}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 bo=c(s=>{const e=new fr(dr);return t=>e.get(t)},"createAccountApiFetcher");var kt=(s=>(s[s.Authenticate=0]="Authenticate",s[s.ConnectWorkspace=1]="ConnectWorkspace",s))(kt||{});const vo={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},hr=c(()=>{const{config:s}=Jn(),e=wo(),t=!!(s?.workspaceKey&&s?.workspaceSecret);return{isAuthenticated:e,workspaceIsConfigured:t,isSetupComplete:e&&t}},"useSetup"),ko=c(({status:s,label:e})=>J(F,{children:[J(F,{width:2,children:[s==="current"&&S(jn,{type:"dots"}),s==="done"&&S(M,{children:"\u2705"})]}),S(M,{dimColor:s!=="current",children:e})]}),"StepDisplay"),Wn=[kt.Authenticate,kt.ConnectWorkspace],_o=c(({onComplete:s})=>{const[e,t]=ne(!1),[n,r]=ne(0),[i,a]=ne(!1),[o,l]=ne(null),[u,d]=ne(""),{isSetupComplete:f}=hr(),h=Wn[n],y=n+1,w=Wn.length,p=Wn.map((C,E)=>{let x="pending";return E<n?x="done":E===n&&(x="current"),{id:C,label:vo[C],status:x}}),m=ur();m&&"*".repeat(m.length);const b=c(async C=>{l(null),a(!0);const E=m&&C===""?m:C,x=new fr;try{await x.request("/account",{headers:{Authorization:`Bearer ${E}`}}),go(E),r(I=>I+1),d("")}catch(I){console.log(I),l("Invalid token. Please try again.")}finally{a(!1)}},"handlePatSubmit"),_=c(()=>{t(!0),s&&s()},"handleWorkspaceSelected");return $n((C,E)=>{f&&E.escape&&s&&s()}),e?S(F,{children:S(M,{children:"\u2705 Setup complete. You are ready to go!"})}):J(F,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[J(F,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[S(F,{marginTop:-1,marginBottom:1,children:J(M,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",J(M,{color:"cyan",children:["Step ",y," of ",w]}),f&&S(M,{color:"grey",children:" [esc: go back]"})]})}),S(F,{flexDirection:"column",paddingLeft:2,children:p.map(C=>S(ko,{status:C.status,label:C.label},C.id))})]}),h===kt.Authenticate&&S(mo,{currentPat:m,onSubmit:b}),h===kt.ConnectWorkspace&&S(lr,{onExit:_,showEscOption:!1})]})},"Setup");function pr(s){if(!Oo(s)&&Co(s))return So(s)}c(pr,"getTypeAndKeyFromPath");function So(s){const e=Object.values(he).map(a=>a.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),n=s.match(t);if(n&&n.groups){const{elementTypePlural:a,elementKey:o}=n.groups,l=mr(a);if(l)return{key:o,type:l}}const r=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),i=s.match(r);if(i&&i.groups){const{elementTypePlural:a,elementKey:o}=i.groups,l=mr(a);if(l)return{key:o,type:l}}}c(So,"extractWorkspaceElementKeyReference");function Co(s){return s.endsWith(".yml")||s.endsWith(".yaml")}c(Co,"isWorkspaceElementFile");function Oo(s){const[e]=s.split(we.sep);return e===he[$.Connector].apiPath}c(Oo,"isConnectorFile");function mr(s){return Object.values($).find(e=>To(e)===s)}c(mr,"getWorkspaceElementTypeFromFolderName");function To(s){return he[s].apiPath}c(To,"getWorkspaceElementTypeFolderName");const yr=In(null);function Ao({children:s,fileWatcher:e}){const[t,n]=ne([]);Ps(()=>{const i=c(u=>d=>{const f=pr(d.relativePath);if(!f)return;const h={...d,elementType:f.type,elementKey:f.key,type:u,timestamp:Date.now()};n(y=>[h,...y.slice(0,2)])},"handleFileChange"),a=i("added"),o=i("changed"),l=i("deleted");return e.on("added",a),e.on("changed",o),e.on("deleted",l),()=>{e.off("added",a),e.off("changed",o),e.off("deleted",l)}},[e]);const r={fileWatcher:e,recentChanges:t};return S(yr.Provider,{value:r,children:s})}c(Ao,"FileWatcherProvider");function Eo(){const s=Ln(yr);if(!s)throw new Error("useFileWatcher must be used within a FileWatcherProvider");return s}c(Eo,"useFileWatcher");const xo=c(s=>{switch(s){case"added":return{symbol:"+",color:"green"};case"changed":return{symbol:"*",color:"yellow"};case"deleted":return{symbol:"-",color:"red"};default:return{symbol:"?",color:"gray"}}},"getSymbolAndColor"),No=c(s=>{switch(s){case"added":return"ADD";case"changed":return"UPD";case"deleted":return"DEL";default:return"UNKNOWN"}},"getActionText");function $o(){const{recentChanges:s}=Eo(),e=[...s].sort((t,n)=>t.timestamp-n.timestamp);return e.length===0?S(F,{paddingTop:1,children:S(M,{color:"gray",children:"No recent changes"})}):J(F,{flexDirection:"column",paddingTop:1,children:[S(M,{color:"gray",children:"Recent Changes:"}),e.map((t,n)=>{const{symbol:r,color:i}=xo(t.type),a=No(t.type);return J(F,{marginLeft:1,children:[J(M,{color:i,children:[r," ",a,":"," "]}),J(M,{children:["[",t.elementType,"] ",S(M,{bold:!0,children:t.elementKey})," (",t.relativePath,")"]})]},`${t.filePath}-${t.timestamp}`)})]})}c($o,"RecentChanges");const gr=c(()=>{const{isSetupComplete:s}=hr(),{config:e}=Jn(),t=Zn();return{isSetupComplete:s,workspaceKey:e?.workspaceKey,config:e,cwd:t}},"useStatus");function Io(s,e=30){return s.length<=e?s:s.slice(0,e-3)+"..."}c(Io,"truncateWorkspaceName");const Lo=c(()=>{const{workspaceKey:s,cwd:e}=gr(),t=Math.min(100,process.stdout.columns||100),{data:n}=Ds("/account"),a=n?.workspaces?.find(l=>l.key===s)?.name,o=a?Io(a):s;return J(F,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[S(F,{marginTop:-1,marginBottom:1,children:J(M,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",S(M,{color:"green",children:"in sync"})]})}),J(F,{children:[S(F,{width:12,children:S(M,{color:"grey",children:"Local:"})}),S(M,{color:"grey",children:e})]}),J(F,{children:[S(F,{width:12,children:S(M,{color:"grey",children:"Remote:"})}),s?J(M,{color:"grey",children:[o," [o: open in console] [w: change]"]}):J(M,{children:[S(M,{color:"yellow",children:"not selected"})," [w: select]"]})]}),S($o,{})]})},"WorkspaceSync");class jo{static{c(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return Bt.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=Le(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 Kt({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const n=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,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}getCurrentConfigInfo(){return this.currentConfig}}const wr=new jo;async function br(s){const e=await wr.getClient(s);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}c(br,"getWorkspaceId");const Po=c(()=>{const{isSetupComplete:s,workspaceKey:e,config:t}=gr(),[n,r]=ne(!1),[i,a]=ne(!1),o=Zn();return $n(l=>{!n&&!i&&(l==="w"&&r(!0),l==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const d=`https://console.integration.app/w/${await br(o)}`,f=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";ma(`${f} "${d}"`)}catch(u){console.error("Failed to open workspace:",u)}})(),l==="s"&&a(!0))}),n?S(lr,{onExit:c(()=>r(!1),"onExit")}):i||!s?S(_o,{onComplete:c(()=>a(!1),"onComplete")},Date.now()):J(F,{flexDirection:"column",children:[S(F,{flexGrow:1,children:S(Pa,{})}),S(Lo,{}),S(F,{paddingLeft:2,children:S(M,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),Gn=Symbol.for("yaml.alias"),Hn=Symbol.for("yaml.document"),Ae=Symbol.for("yaml.map"),vr=Symbol.for("yaml.pair"),me=Symbol.for("yaml.scalar"),Je=Symbol.for("yaml.seq"),oe=Symbol.for("yaml.node.type"),Ee=c(s=>!!s&&typeof s=="object"&&s[oe]===Gn,"isAlias"),je=c(s=>!!s&&typeof s=="object"&&s[oe]===Hn,"isDocument"),ze=c(s=>!!s&&typeof s=="object"&&s[oe]===Ae,"isMap"),z=c(s=>!!s&&typeof s=="object"&&s[oe]===vr,"isPair"),V=c(s=>!!s&&typeof s=="object"&&s[oe]===me,"isScalar$1"),We=c(s=>!!s&&typeof s=="object"&&s[oe]===Je,"isSeq");function W(s){if(s&&typeof s=="object")switch(s[oe]){case Ae:case Je:return!0}return!1}c(W,"isCollection$1");function G(s){if(s&&typeof s=="object")switch(s[oe]){case Gn:case Ae:case me:case Je:return!0}return!1}c(G,"isNode");const kr=c(s=>(V(s)||W(s))&&!!s.anchor,"hasAnchor"),se=Symbol("break visit"),_r=Symbol("skip children"),ye=Symbol("remove node");function Pe(s,e){const t=Sr(e);je(s)?Ge(null,s.contents,t,Object.freeze([s]))===ye&&(s.contents=null):Ge(null,s,t,Object.freeze([]))}c(Pe,"visit$1"),Pe.BREAK=se,Pe.SKIP=_r,Pe.REMOVE=ye;function Ge(s,e,t,n){const r=Cr(s,e,t,n);if(G(r)||z(r))return Or(s,n,r),Ge(s,r,t,n);if(typeof r!="symbol"){if(W(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const a=Ge(i,e.items[i],t,n);if(typeof a=="number")i=a-1;else{if(a===se)return se;a===ye&&(e.items.splice(i,1),i-=1)}}}else if(z(e)){n=Object.freeze(n.concat(e));const i=Ge("key",e.key,t,n);if(i===se)return se;i===ye&&(e.key=null);const a=Ge("value",e.value,t,n);if(a===se)return se;a===ye&&(e.value=null)}}return r}c(Ge,"visit_");async function Zt(s,e){const t=Sr(e);je(s)?await He(null,s.contents,t,Object.freeze([s]))===ye&&(s.contents=null):await He(null,s,t,Object.freeze([]))}c(Zt,"visitAsync"),Zt.BREAK=se,Zt.SKIP=_r,Zt.REMOVE=ye;async function He(s,e,t,n){const r=await Cr(s,e,t,n);if(G(r)||z(r))return Or(s,n,r),He(s,r,t,n);if(typeof r!="symbol"){if(W(e)){n=Object.freeze(n.concat(e));for(let i=0;i<e.items.length;++i){const a=await He(i,e.items[i],t,n);if(typeof a=="number")i=a-1;else{if(a===se)return se;a===ye&&(e.items.splice(i,1),i-=1)}}}else if(z(e)){n=Object.freeze(n.concat(e));const i=await He("key",e.key,t,n);if(i===se)return se;i===ye&&(e.key=null);const a=await He("value",e.value,t,n);if(a===se)return se;a===ye&&(e.value=null)}}return r}c(He,"visitAsync_");function Sr(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(Sr,"initVisitor");function Cr(s,e,t,n){if(typeof t=="function")return t(s,e,n);if(ze(e))return t.Map?.(s,e,n);if(We(e))return t.Seq?.(s,e,n);if(z(e))return t.Pair?.(s,e,n);if(V(e))return t.Scalar?.(s,e,n);if(Ee(e))return t.Alias?.(s,e,n)}c(Cr,"callVisitor");function Or(s,e,t){const n=e[e.length-1];if(W(n))n.items[s]=t;else if(z(n))s==="key"?n.key=t:n.value=t;else if(je(n))n.contents=t;else{const r=Ee(n)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}c(Or,"replaceNode");const Ro={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Do=c(s=>s.replace(/[!,[\]{}]/g,e=>Ro[e]),"escapeTagName");class te{static{c(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},te.defaultYaml,e),this.tags=Object.assign({},te.defaultTags,t)}clone(){const e=new te(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new te(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:te.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},te.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:te.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},te.defaultTags),this.atNextDocument=!1);const n=e.trim().split(/[ \t]+/),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,a]=n;return this.tags[i]=a,!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 a=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,a),!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 a=e.slice(2,-1);return a==="!"||a==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),a)}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(a){return t(String(a)),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+Do(e.substring(n.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],n=Object.entries(this.tags);let r;if(e&&n.length>0&&G(e.contents)){const i={};Pe(e.contents,(a,o)=>{G(o)&&o.tag&&(i[o.tag]=!0)}),r=Object.keys(i)}else r=[];for(const[i,a]of n)i==="!!"&&a==="tag:yaml.org,2002:"||(!e||r.some(o=>o.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
|
|
3
|
-
`)}}
|
|
4
|
-
`)?
|
|
2
|
+
var pr=Object.defineProperty;var l=(n,e)=>pr(n,"name",{value:e,configurable:!0});import{jsxs as L,jsx as g}from"react/jsx-runtime";import*as H from"node:path";import{resolve as mr,dirname as yr,join as gr}from"node:path";import{useInput as ht,Box as O,Text as v,Newline as wr,render as br}from"ink";import Sr from"minimist";import{SWRConfig as kr}from"swr";import{exec as Cr}from"node:child_process";import{useState as B,useEffect as tn,createContext as nn,useContext as sn,useCallback as rs}from"react";import*as M from"node:fs";import{readFileSync as vr}from"node:fs";import*as Ar from"node:crypto";import{createHash as Tr}from"node:crypto";import*as Or from"node:os";import{TextInput as Er,Select as $r}from"@inkjs/ui";import rn from"ink-spinner";import os from"swr/immutable";import se from"js-yaml";import{z as F}from"zod";import Ir from"ink-text-input";import Nr from"os";import j from"path";import Lr from"conf";import{WorkspaceElementSpecs as ie,WorkspaceElementType as I,IntegrationAppClient as pt,setValueAtLocator as on,extractIntegrationAppErrorData as re,getDataCollectionCreateFields as an,excludeWriteOnlyFieldsFromSchema as as,valueToSchema as mt,getRequiredFieldsFromSchema as _r,getValueAtLocator as Pr,walkSchema as cs,makeDataLocationPath as ls,getDataCollectionUpdateFields as cn}from"@integration-app/sdk";import Ye from"jsonwebtoken";import{EventEmitter as xr}from"node:events";import jr from"chokidar";import k from"chalk";import{fileURLToPath as Kr}from"node:url";import{Command as Dr}from"commander";import ln from"axios";import{FastMCP as Mr}from"fastmcp";import P from"fs";import Rr from"archiver";import Br from"form-data";import Fr from"unzipper";import un from"lodash/merge.js";import qr from"@anthropic-ai/sdk";import{faker as Ze}from"@faker-js/faker";import Ur from"lodash/template.js";import Jr from"lodash/templateSettings.js";const fn=[{id:"claude-code",name:"Claude Code",description:"Anthropic Claude Code agent",actionDescription:"Adding membrane MCP to .mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".mcp.json"),e={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Claude Code"}}}};let t={};if(M.existsSync(n))try{t=JSON.parse(M.readFileSync(n,"utf8"))}catch{t={}}const s={...t,mcpServers:{...t.mcpServers,...e.mcpServers}};return M.writeFileSync(n,JSON.stringify(s,null,2)),`MCP server configuration added to ${n}`},"addConfig")},{id:"cursor",name:"Cursor",description:"Cursor AI editor",actionDescription:"Adding membrane MCP to .cursor/mcp.json in the current directory",addConfig:l(()=>{const n=H.join(process.cwd(),".cursor"),e=H.join(n,"mcp.json");M.existsSync(n)||M.mkdirSync(n);const t={mcpServers:{membrane:{command:"membrane",args:["mcp"],env:{AGENT_NAME:"Cursor"}}}};let s={};if(M.existsSync(e))try{s=JSON.parse(M.readFileSync(e,"utf8"))}catch{s={}}const i={...s,mcpServers:{...s.mcpServers,...t.mcpServers}};return M.writeFileSync(e,JSON.stringify(i,null,2)),`MCP server configuration added to ${e}`},"addConfig")}],Vr=l(({onExit:n,onComplete:e})=>{const[t,s]=B(0),[i,r]=B(!1),[o,a]=B(null),[c,u]=B(""),[d,f]=B("");ht((w,p)=>{if(c||d){(p.escape||w==="q"||p.return)&&e();return}if(i)p.return||w===" "?h(o):p.escape&&(r(!1),a(null));else if(p.escape)n();else if(p.upArrow||w==="k")s(Math.max(0,t-1));else if(p.downArrow||w==="j")s(Math.min(fn.length-1,t+1));else if(p.return||w===" "){const y=fn[t];a(y),r(!0)}});const h=l(w=>{try{const p=w.addConfig();u(p)}catch(p){f(`Failed to write configuration: ${p.message||p}`)}},"addMcpConfiguration"),m=Math.min(80,process.stdout.columns||80);return c?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"green",children:"Success"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"green",children:c}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"The agent will now be able to use Membrane's integration capabilities."})})]}),g(O,{marginTop:1,paddingLeft:2,children:g(v,{color:"white",children:"[esc/q/enter: exit]"})})]}):d?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"red",children:"Error"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:g(v,{color:"red",children:d})}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[esc/q/enter: exit]"})})]}):i&&o?L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Confirmation"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[L(v,{children:["Connect ",g(v,{bold:!0,children:o.name})," to Membrane via MCP?"]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,children:g(v,{color:"yellow",bold:!0,children:o.actionDescription})}),g(O,{marginTop:2,marginBottom:1,children:L(v,{children:[g(v,{color:"white",bold:!0,children:"[Enter] Confirm"})," ",g(v,{color:"gray",children:"[Esc] Cancel"})]})})]})]}):L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:m,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F517} Connect Agent \u2014 ",g(v,{color:"cyan",children:"Select Agent"})]})}),L(O,{flexDirection:"column",paddingLeft:2,children:[g(v,{color:"grey",children:"Choose an agent to connect to Membrane via MCP:"}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"This will add an MCP server configuration that allows the agent to use Membrane's integration capabilities."})}),g(O,{marginTop:1,flexDirection:"column",children:fn.map((w,p)=>L(O,{children:[L(v,{color:t===p?"cyan":"white",children:[t===p?"\u25B6 ":" ",w.name]}),L(v,{color:"grey",children:[" \u2014 ",w.description]})]},w.id))})]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[\u2191\u2193: select] [enter: choose] [esc: exit]"})})]})},"AddMcpServerScreen"),fe=H.join(Or.tmpdir(),"membrane-mcp-status"),us=3e4;function dn(n){return Tr("md5").update(n).digest("hex").slice(0,8)}l(dn,"getCwdHash");function hn(n,e){const t=dn(e);return H.join(fe,`mcp-${t}-${n}.json`)}l(hn,"getStatusFilePath");function Te(n,e){try{const t=e||process.cwd();if(!n){const i=yt(t);return i.length===0?null:i[0]}const s=hn(n,t);if(M.existsSync(s)){const i=M.statSync(s),r=new Date;if(r.getTime()-i.mtime.getTime()>us)return Qe(n,t),null;const a=M.readFileSync(s,"utf8"),c=JSON.parse(a);if(c.isRunning){const u=new Date(c.lastActivity).getTime();if(r.getTime()-u>us)return Qe(n,t),null}return c}}catch{n&&e&&Qe(n,e)}return null}l(Te,"getMcpStatus");function yt(n){try{const e=n||process.cwd(),t=dn(e);if(!M.existsSync(fe))return[];const s=M.readdirSync(fe),i=[];for(const r of s){const o=r.match(new RegExp(`^mcp-${t}-(\\d+)\\.json$`));if(o){const a=parseInt(o[1],10),c=Te(a,e);c&&i.push(c)}}return i.sort((r,o)=>new Date(o.startTime).getTime()-new Date(r.startTime).getTime())}catch{return[]}}l(yt,"getAllMcpStatusFiles");function pn(n){try{const t={...Te(n.processId,n.cwd)||{isRunning:!1,startTime:new Date().toISOString(),lastActivity:new Date().toISOString(),toolsCount:0,totalRequests:0,processId:n.processId,cwd:n.cwd,agentName:process.env.AGENT_NAME||"Unnamed Agent"},...n};M.existsSync(fe)||M.mkdirSync(fe,{recursive:!0});const s=hn(n.processId,n.cwd);M.writeFileSync(s,JSON.stringify(t,null,2))}catch{}}l(pn,"updateMcpStatus");function Qe(n,e){try{const t=e||process.cwd();if(n){const s=hn(n,t);M.existsSync(s)&&M.unlinkSync(s)}else{const s=dn(t);if(M.existsSync(fe)){const i=M.readdirSync(fe);for(const r of i)r.match(new RegExp(`^mcp-${s}-\\d+\\.json$`))&&M.unlinkSync(H.join(fe,r))}}}catch{}}l(Qe,"clearMcpStatus");function Wr(n,e){const t=Te(n,e);t&&pn({processId:n,cwd:e,totalRequests:t.totalRequests+1,lastRequestTime:new Date().toISOString(),lastActivity:new Date().toISOString()})}l(Wr,"trackToolExecution");function zr(){const[n,e]=B(Te()),[t,s]=B(yt()),[i,r]=B(null);return tn(()=>{try{const a=process.cwd();e(Te(void 0,a)),s(yt(a)),r(null)}catch(a){r("Failed to read MCP status:"+a),e(null),s([])}const o=setInterval(()=>{try{const a=process.cwd(),c=Te(void 0,a),u=yt(a);e(c),s(u),r(null)}catch(a){r("Failed to read MCP status: "+a),e(null),s([])}},2e3);return()=>clearInterval(o)},[]),{mcpStatus:n,allMcpServers:t,error:i,isRunning:n?.isRunning||!1,toolsCount:n?.toolsCount||0,totalRequests:n?.totalRequests||0,lastActivity:n?.lastActivity,processId:n?.processId,serverCount:t.length}}l(zr,"useMcpStatus");const Hr=l(()=>{const n=Math.min(100,process.stdout.columns||100),{error:e,serverCount:t,allMcpServers:s}=zr();return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:n,children:[g(O,{marginTop:-1,marginBottom:0,flexDirection:"column",children:L(v,{bold:!0,children:["\u{1F916} Connected AI Agents:"," ",e?g(v,{color:"red",children:"error reading status"}):t===0?g(v,{color:"yellow",children:"none"}):g(v,{color:"green",children:t})]})}),!e&&t===0&&g(O,{marginTop:1,children:L(v,{color:"grey",children:["Connect your AI agents to Membrane.",g(wr,{}),"It will give them tools and context to build integrations."]})}),s.length>0&&g(O,{flexDirection:"column",paddingLeft:2,marginTop:1,children:s.map((i,r)=>g(O,{children:L(v,{color:"grey",children:["#",r+1," ",i.agentName,": ",i.totalRequests," calls"]})},i.processId))}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"[a: connect an agent]"})})]})},"AgentStatus"),fs=nn(process.cwd());function Gr({cwd:n,children:e}){return g(fs.Provider,{value:n,children:e})}l(Gr,"CwdProvider");function mn(){return sn(fs)}l(mn,"useCwd");const Yr="membrane.config.yml";function de(n){const e=H.join(n??process.cwd(),Yr);try{const t=M.readFileSync(e,"utf8"),s=se.load(t),i=ds.safeParse(s);return i.success?i.data:null}catch{return null}}l(de,"readProjectConfig");const Zr="membrane.config.yml",ds=F.object({workspaceKey:F.string().optional(),workspaceSecret:F.string().optional(),apiUri:F.string().optional(),testCustomerId:F.string().optional(),anthropicApiKey:F.string().optional()});F.enum(["pull"]);const hs=nn(void 0);function Qr({children:n}){const e=mn(),[t,s]=B(null),[i,r]=B(!0);tn(()=>{const u=de(e);s(u),r(!1)},[e]);const o=rs(u=>{const d=H.join(e,Zr),h={...de(e)??{},...u},m=ds.safeParse(h);return m.success?(M.writeFileSync(d,se.dump(m.data)),s(m.data),!0):!1},[e]),a=rs(()=>!!(t?.workspaceKey&&t?.workspaceSecret),[t]),c={config:t,isLoading:i,updateConfig:o,validateConfig:a};return g(hs.Provider,{value:c,children:n})}l(Qr,"ProjectConfigProvider");function yn(){const n=sn(hs);if(n===void 0)throw new Error("useProjectConfig must be used within a ProjectConfigProvider");return n}l(yn,"useProjectConfig");const ps=l(({onExit:n,showEscOption:e=!0})=>{const[t,s]=B(""),{data:i,error:r,isLoading:o}=os("/account"),{updateConfig:a,isLoading:c}=yn(),u=i?.workspaces,d=o||c;if(ht((y,S)=>{S.escape&&n?.()}),d)return L(O,{children:[g(rn,{}),g(v,{children:" Fetching workspaces..."})]});if(r)return L(O,{flexDirection:"column",children:[L(v,{color:"red",children:["Error: ",r.message]}),g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]});const f=u?.filter(y=>y.name.toLowerCase().includes(t.toLowerCase()))??[],h=f.map(y=>({label:y.name,value:y.id})),m=h.length,w=u?.length??0,p=l(async y=>{const S=f.find(A=>A.id===y);if(!S)return;const{key:b,secret:C}=S;!b||!C||(await a({workspaceKey:b,workspaceSecret:C}),n?.())},"handleSelect");return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,children:g(v,{bold:!0,children:"\u{1F4C1} Select your workspace"})}),L(O,{marginTop:1,children:[g(v,{children:"Search: "}),g(Er,{placeholder:"Enter a search query...",onChange:s})]}),w>5&&L(v,{children:["Showing ",m," of ",w," workspaces."]}),g(O,{marginTop:1,children:g($r,{options:h,onChange:l(y=>{y&&p(y)},"onChange")})}),e&&g(O,{marginTop:1,children:g(v,{color:"grey",children:"Press ESC to go back"})})]})},"SelectWorkspace"),Xr=l(({currentPat:n,onSubmit:e})=>{const[t,s]=B(""),[i,r]=B(!1),[o,a]=B(null);return L(O,{flexDirection:"column",borderStyle:"round",borderTop:!0,width:70,paddingX:1,children:[g(O,{marginTop:-1,marginBottom:1,children:g(v,{bold:!0,children:"\u{1F511} Enter your Personal Access Token"})}),g(v,{children:"Please provide your Personal Access Token. You can find it here:"}),g(O,{marginTop:1,marginBottom:1,children:g(v,{color:"yellow",children:"https://console.integration.app/w/0/manage-account/api-token"})}),n&&g(v,{dimColor:!0,children:"Press Enter to keep your current token or type a new one."}),g(Ir,{mask:"*",placeholder:`${n?"******":"Enter your token here..."}`,value:t,onChange:s,onSubmit:l(async u=>{a(null),r(!0);try{await e(u),s("")}catch{a("Invalid token. Please try again.")}finally{r(!1)}},"handleSubmit")}),i&&g(O,{marginTop:1,children:L(v,{children:[g(rn,{type:"dots"})," Validating token..."]})}),o&&g(v,{color:"red",children:o})]})},"PersonalAccessTokenInput"),eo="membrane",to="membrane.config.yml",gn="https://api.integration.app";function Xe(){const n=process.cwd(),e=H.join(n,eo),t=H.join(n,to),s=e,i=H.join(s,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:s,workspaceDataFilePath:i}}l(Xe,"getPaths");const no={pat:{type:"string"},workspace:{type:"object"}},wn=new Lr({schema:no,configName:"config",cwd:j.join(Nr.homedir(),".membrane")}),so=l(n=>{wn.set("pat",n)},"setPat"),ms=l(()=>wn.get("pat"),"getPat"),io=l(()=>!!wn.get("pat"),"hasPat");class ys{static{l(this,"AccountApiClient")}constructor(e=gn){this.apiBaseUrl=e}async request(e,t={}){const s=t.headers?t.headers instanceof Headers?new Headers(t.headers):new Headers(t.headers):new Headers;if(!s.has("Authorization")){const o=ms();if(!o)throw new Error("Personal Access Token not found.");s.set("Authorization",`Bearer ${o}`)}t.body&&!s.has("Content-Type")&&s.set("Content-Type","application/json");const i=await fetch(`${this.apiBaseUrl}${e}`,{...t,headers:s});if(!i.ok){const o=await i.text();throw new Error(`API request failed: ${i.status} ${i.statusText} - ${o}`)}if(i.status===204)return{};const r=await i.text();return JSON.parse(r)}get(e){return this.request(e,{method:"GET"})}post(e,t){return this.request(e,{method:"POST",body:JSON.stringify(t)})}put(e,t){return this.request(e,{method:"PUT",body:JSON.stringify(t)})}patch(e,t){return this.request(e,{method:"PATCH",body:JSON.stringify(t)})}delete(e){return this.request(e,{method:"DELETE"})}}const ro=l(n=>{const e=new ys(gn);return t=>e.get(t)},"createAccountApiFetcher");var et=(n=>(n[n.Authenticate=0]="Authenticate",n[n.ConnectWorkspace=1]="ConnectWorkspace",n))(et||{});const oo={0:"Authenticate in Membrane",1:"Connect a Membrane Workspace"},gs=l(()=>{const{config:n}=yn(),e=io(),t=!!(n?.workspaceKey&&n?.workspaceSecret);return{isAuthenticated:e,workspaceIsConfigured:t,isSetupComplete:e&&t}},"useSetup"),ao=l(({status:n,label:e})=>L(O,{children:[L(O,{width:2,children:[n==="current"&&g(rn,{type:"dots"}),n==="done"&&g(v,{children:"\u2705"})]}),g(v,{dimColor:n!=="current",children:e})]}),"StepDisplay"),bn=[et.Authenticate,et.ConnectWorkspace],co=l(({onComplete:n})=>{const[e,t]=B(!1),[s,i]=B(0),[r,o]=B(!1),[a,c]=B(null),[u,d]=B(""),{isSetupComplete:f}=gs(),h=bn[s],m=s+1,w=bn.length,p=bn.map((C,A)=>{let $="pending";return A<s?$="done":A===s&&($="current"),{id:C,label:oo[C],status:$}}),y=ms();y&&"*".repeat(y.length);const S=l(async C=>{c(null),o(!0);const A=y&&C===""?y:C,$=new ys;try{await $.request("/account",{headers:{Authorization:`Bearer ${A}`}}),so(A),i(N=>N+1),d("")}catch(N){console.log(N),c("Invalid token. Please try again.")}finally{o(!1)}},"handlePatSubmit"),b=l(()=>{t(!0),n&&n()},"handleWorkspaceSelected");return ht((C,A)=>{f&&A.escape&&n&&n()}),e?g(O,{children:g(v,{children:"\u2705 Setup complete. You are ready to go!"})}):L(O,{flexDirection:"column",alignSelf:"flex-start",gap:1,children:[L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:70,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F6E0}\uFE0F Setup \u2014"," ",L(v,{color:"cyan",children:["Step ",m," of ",w]}),f&&g(v,{color:"grey",children:" [esc: go back]"})]})}),g(O,{flexDirection:"column",paddingLeft:2,children:p.map(C=>g(ao,{status:C.status,label:C.label},C.id))})]}),h===et.Authenticate&&g(Xr,{currentPat:y,onSubmit:S}),h===et.ConnectWorkspace&&g(ps,{onExit:b,showEscOption:!1})]})},"Setup");function ws(n){if(!fo(n)&&uo(n))return lo(n)}l(ws,"getTypeAndKeyFromPath");function lo(n){const e=Object.values(ie).map(o=>o.apiPath),t=new RegExp(`^(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),s=n.match(t);if(s&&s.groups){const{elementTypePlural:o,elementKey:a}=s.groups,c=bs(o);if(c)return{key:a,type:c}}const i=new RegExp(`^integrations/(?<integrationKey>[^/]+)/(?<elementTypePlural>${e.join("|")})/(?<elementKey>[^/]+)/spec.y[a]*ml$`),r=n.match(i);if(r&&r.groups){const{elementTypePlural:o,elementKey:a}=r.groups,c=bs(o);if(c)return{key:a,type:c}}}l(lo,"extractWorkspaceElementKeyReference");function uo(n){return n.endsWith(".yml")||n.endsWith(".yaml")}l(uo,"isWorkspaceElementFile");function fo(n){const[e]=n.split(H.sep);return e===ie[I.Connector].apiPath}l(fo,"isConnectorFile");function bs(n){return Object.values(I).find(e=>ho(e)===n)}l(bs,"getWorkspaceElementTypeFromFolderName");function ho(n){return ie[n].apiPath}l(ho,"getWorkspaceElementTypeFolderName");const Ss=nn(null);function po({children:n,fileWatcher:e}){const[t,s]=B([]);tn(()=>{const r=l(u=>d=>{const f=ws(d.relativePath);if(!f)return;const h={...d,elementType:f.type,elementKey:f.key,type:u,timestamp:Date.now()};s(m=>[h,...m.slice(0,2)])},"handleFileChange"),o=r("added"),a=r("changed"),c=r("deleted");return e.on("added",o),e.on("changed",a),e.on("deleted",c),()=>{e.off("added",o),e.off("changed",a),e.off("deleted",c)}},[e]);const i={fileWatcher:e,recentChanges:t};return g(Ss.Provider,{value:i,children:n})}l(po,"FileWatcherProvider");function mo(){const n=sn(Ss);if(!n)throw new Error("useFileWatcher must be used within a FileWatcherProvider");return n}l(mo,"useFileWatcher");const yo=l(n=>{switch(n){case"added":return{symbol:"+",color:"green"};case"changed":return{symbol:"*",color:"yellow"};case"deleted":return{symbol:"-",color:"red"};default:return{symbol:"?",color:"gray"}}},"getSymbolAndColor"),go=l(n=>{switch(n){case"added":return"ADD";case"changed":return"UPD";case"deleted":return"DEL";default:return"UNKNOWN"}},"getActionText");function wo(){const{recentChanges:n}=mo(),e=[...n].sort((t,s)=>t.timestamp-s.timestamp);return e.length===0?g(O,{paddingTop:1,children:g(v,{color:"gray",children:"No recent changes"})}):L(O,{flexDirection:"column",paddingTop:1,children:[g(v,{color:"gray",children:"Recent Changes:"}),e.map((t,s)=>{const{symbol:i,color:r}=yo(t.type),o=go(t.type);return L(O,{marginLeft:1,children:[L(v,{color:r,children:[i," ",o,":"," "]}),L(v,{children:["[",t.elementType,"] ",g(v,{bold:!0,children:t.elementKey})," (",t.relativePath,")"]})]},`${t.filePath}-${t.timestamp}`)})]})}l(wo,"RecentChanges");const ks=l(()=>{const{isSetupComplete:n}=gs(),{config:e}=yn(),t=mn();return{isSetupComplete:n,workspaceKey:e?.workspaceKey,config:e,cwd:t}},"useStatus");function bo(n,e=30){return n.length<=e?n:n.slice(0,e-3)+"..."}l(bo,"truncateWorkspaceName");const So=l(()=>{const{workspaceKey:n,cwd:e}=ks(),t=Math.min(100,process.stdout.columns||100),{data:s}=os("/account"),o=s?.workspaces?.find(c=>c.key===n)?.name,a=o?bo(o):n;return L(O,{flexDirection:"column",paddingX:1,borderStyle:"round",borderTop:!0,width:t,children:[g(O,{marginTop:-1,marginBottom:1,children:L(v,{bold:!0,children:["\u{1F504} Workspaces \u2014 ",g(v,{color:"green",children:"in sync"})]})}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Local:"})}),g(v,{color:"grey",children:e})]}),L(O,{children:[g(O,{width:12,children:g(v,{color:"grey",children:"Remote:"})}),n?L(v,{color:"grey",children:[a," [o: open in console] [w: change]"]}):L(v,{children:[g(v,{color:"yellow",children:"not selected"})," [w: select]"]})]}),g(wo,{})]})},"WorkspaceSync");class ko{static{l(this,"MembraneClient")}client=null;currentConfig=null;tokenExpiry=0;async generateAccessToken(e,t){return Ye.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=de(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 pt({token:t,apiUri:e.apiUri})}async getClient(e){const t=this.getCurrentConfig(e);if(!t)throw new Error("Unable to create IntegrationAppClient: No workspace configuration found.");const s=!this.currentConfig||this.currentConfig.workspaceKey!==t.workspaceKey||this.currentConfig.workspaceSecret!==t.workspaceSecret||this.currentConfig.apiUri!==t.apiUri,i=!this.isTokenValid()||this.tokenExpiry-Date.now()<3e5;return(!this.client||s||i)&&(this.client=await this.createClient(t)),this.client}clearClient(){this.client=null,this.currentConfig=null,this.tokenExpiry=0}getCurrentConfigInfo(){return this.currentConfig}}const Cs=new ko;async function vs(n){const e=await Cs.getClient(n);if(!e)throw new Error("No workspace configuration found");return(await e.get("org-workspace-id")).id}l(vs,"getWorkspaceId");const Co=l(()=>{const{isSetupComplete:n,workspaceKey:e,config:t}=ks(),[s,i]=B(!1),[r,o]=B(!1),[a,c]=B(!1),u=mn();return ht(d=>{!s&&!r&&!a&&(d==="w"&&i(!0),d==="a"&&c(!0),d==="o"&&e&&t?.workspaceSecret&&(async()=>{try{const h=`https://console.integration.app/w/${await vs(u)}`,m=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";Cr(`${m} "${h}"`)}catch(f){console.error("Failed to open workspace:",f)}})(),d==="s"&&o(!0))}),s?g(ps,{onExit:l(()=>i(!1),"onExit")}):a?g(Vr,{onExit:l(()=>c(!1),"onExit"),onComplete:l(()=>c(!1),"onComplete")}):r||!n?g(co,{onComplete:l(()=>o(!1),"onComplete")},Date.now()):L(O,{flexDirection:"column",children:[g(O,{flexGrow:1,children:g(Hr,{})}),g(So,{}),g(O,{paddingLeft:2,children:g(v,{color:"grey",children:"[s: (re-)setup]"})})]})},"Main"),Sn=Symbol.for("yaml.alias"),kn=Symbol.for("yaml.document"),he=Symbol.for("yaml.map"),As=Symbol.for("yaml.pair"),oe=Symbol.for("yaml.scalar"),Oe=Symbol.for("yaml.seq"),Q=Symbol.for("yaml.node.type"),pe=l(n=>!!n&&typeof n=="object"&&n[Q]===Sn,"isAlias"),we=l(n=>!!n&&typeof n=="object"&&n[Q]===kn,"isDocument"),Ee=l(n=>!!n&&typeof n=="object"&&n[Q]===he,"isMap"),R=l(n=>!!n&&typeof n=="object"&&n[Q]===As,"isPair"),K=l(n=>!!n&&typeof n=="object"&&n[Q]===oe,"isScalar$1"),$e=l(n=>!!n&&typeof n=="object"&&n[Q]===Oe,"isSeq");function q(n){if(n&&typeof n=="object")switch(n[Q]){case he:case Oe:return!0}return!1}l(q,"isCollection$1");function U(n){if(n&&typeof n=="object")switch(n[Q]){case Sn:case he:case oe:case Oe:return!0}return!1}l(U,"isNode");const Ts=l(n=>(K(n)||q(n))&&!!n.anchor,"hasAnchor"),Y=Symbol("break visit"),Os=Symbol("skip children"),ae=Symbol("remove node");function be(n,e){const t=Es(e);we(n)?Ie(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):Ie(null,n,t,Object.freeze([]))}l(be,"visit$1"),be.BREAK=Y,be.SKIP=Os,be.REMOVE=ae;function Ie(n,e,t,s){const i=$s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ie(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=Ie(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=Ie("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=Ie("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ie,"visit_");async function gt(n,e){const t=Es(e);we(n)?await Ne(null,n.contents,t,Object.freeze([n]))===ae&&(n.contents=null):await Ne(null,n,t,Object.freeze([]))}l(gt,"visitAsync"),gt.BREAK=Y,gt.SKIP=Os,gt.REMOVE=ae;async function Ne(n,e,t,s){const i=await $s(n,e,t,s);if(U(i)||R(i))return Is(n,s,i),Ne(n,i,t,s);if(typeof i!="symbol"){if(q(e)){s=Object.freeze(s.concat(e));for(let r=0;r<e.items.length;++r){const o=await Ne(r,e.items[r],t,s);if(typeof o=="number")r=o-1;else{if(o===Y)return Y;o===ae&&(e.items.splice(r,1),r-=1)}}}else if(R(e)){s=Object.freeze(s.concat(e));const r=await Ne("key",e.key,t,s);if(r===Y)return Y;r===ae&&(e.key=null);const o=await Ne("value",e.value,t,s);if(o===Y)return Y;o===ae&&(e.value=null)}}return i}l(Ne,"visitAsync_");function Es(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}l(Es,"initVisitor");function $s(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(Ee(e))return t.Map?.(n,e,s);if($e(e))return t.Seq?.(n,e,s);if(R(e))return t.Pair?.(n,e,s);if(K(e))return t.Scalar?.(n,e,s);if(pe(e))return t.Alias?.(n,e,s)}l($s,"callVisitor");function Is(n,e,t){const s=e[e.length-1];if(q(s))s.items[n]=t;else if(R(s))n==="key"?s.key=t:s.value=t;else if(we(s))s.contents=t;else{const i=pe(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${i} parent`)}}l(Is,"replaceNode");const vo={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Ao=l(n=>n.replace(/[!,[\]{}]/g,e=>vo[e]),"escapeTagName");class G{static{l(this,"Directives")}constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},G.defaultYaml,e),this.tags=Object.assign({},G.defaultTags,t)}clone(){const e=new G(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){const e=new G(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:G.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},G.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:G.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},G.defaultTags),this.atNextDocument=!1);const s=e.trim().split(/[ \t]+/),i=s.shift();switch(i){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;const[r,o]=s;return this.tags[r]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;const[r]=s;if(r==="1.1"||r==="1.2")return this.yaml.version=r,!0;{const o=/^\d+\.\d+$/.test(r);return t(6,`Unsupported YAML version ${r}`,o),!1}}default:return t(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){const o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}const[,s,i]=e.match(/^(.*!)([^!]*)$/s);i||t(`The ${e} tag has no suffix`);const r=this.tags[s];if(r)try{return r+decodeURIComponent(i)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(const[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Ao(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){const t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags);let i;if(e&&s.length>0&&U(e.contents)){const r={};be(e.contents,(o,a)=>{U(a)&&a.tag&&(r[a.tag]=!0)}),i=Object.keys(r)}else i=[];for(const[r,o]of s)r==="!!"&&o==="tag:yaml.org,2002:"||(!e||i.some(a=>a.startsWith(o)))&&t.push(`%TAG ${r} ${o}`);return t.join(`
|
|
3
|
+
`)}}G.defaultYaml={explicit:!1,version:"1.2"},G.defaultTags={"!!":"tag:yaml.org,2002:"};function Ns(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){const t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}l(Ns,"anchorIsValid");function Ls(n){const e=new Set;return be(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}l(Ls,"anchorNames");function _s(n,e){for(let t=1;;++t){const s=`${n}${t}`;if(!e.has(s))return s}}l(_s,"findNewAnchor");function To(n,e){const t=[],s=new Map;let i=null;return{onAnchor:l(r=>{t.push(r),i??(i=Ls(n));const o=_s(e,i);return i.add(o),o},"onAnchor"),setAnchors:l(()=>{for(const r of t){const o=s.get(r);if(typeof o=="object"&&o.anchor&&(K(o.node)||q(o.node)))o.node.anchor=o.anchor;else{const a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=r,a}}},"setAnchors"),sourceObjects:s}}l(To,"createNodeAnchors");function Le(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let i=0,r=s.length;i<r;++i){const o=s[i],a=Le(n,s,String(i),o);a===void 0?delete s[i]:a!==o&&(s[i]=a)}else if(s instanceof Map)for(const i of Array.from(s.keys())){const r=s.get(i),o=Le(n,s,i,r);o===void 0?s.delete(i):o!==r&&s.set(i,o)}else if(s instanceof Set)for(const i of Array.from(s)){const r=Le(n,s,i,i);r===void 0?s.delete(i):r!==i&&(s.delete(i),s.add(r))}else for(const[i,r]of Object.entries(s)){const o=Le(n,s,i,r);o===void 0?delete s[i]:o!==r&&(s[i]=o)}return n.call(e,t,s)}l(Le,"applyReviver");function X(n,e,t){if(Array.isArray(n))return n.map((s,i)=>X(s,String(i),t));if(n&&typeof n.toJSON=="function"){if(!t||!Ts(n))return n.toJSON(e,t);const s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=r=>{s.res=r,delete t.onCreate};const i=n.toJSON(e,t);return t.onCreate&&t.onCreate(i),i}return typeof n=="bigint"&&!t?.keep?Number(n):n}l(X,"toJS");class Cn{static{l(this,"NodeBase")}constructor(e){Object.defineProperty(this,Q,{value:e})}clone(){const e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:s,onAnchor:i,reviver:r}={}){if(!we(e))throw new TypeError("A document argument is required");const o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=X(this,"",o);if(typeof i=="function")for(const{count:c,res:u}of o.anchors.values())i(u,c);return typeof r=="function"?Le(r,{"":a},"",a):a}}class wt extends Cn{static{l(this,"Alias")}constructor(e){super(Sn),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],be(e,{Node:l((r,o)=>{(pe(o)||Ts(o))&&s.push(o)},"Node")}),t&&(t.aliasResolveCache=s));let i;for(const r of s){if(r===this)break;r.anchor===this.source&&(i=r)}return i}toJSON(e,t){if(!t)return{source:this.source};const{anchors:s,doc:i,maxAliasCount:r}=t,o=this.resolve(i,t);if(!o){const c=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(c)}let a=s.get(o);if(a||(X(o,null,t),a=s.get(o)),!a||a.res===void 0){const c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(r>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=bt(i,o,s)),a.count*a.aliasCount>r)){const c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}return a.res}toString(e,t,s){const i=`*${this.source}`;if(e){if(Ns(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){const r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(r)}if(e.implicitKey)return`${i} `}return i}}function bt(n,e,t){if(pe(e)){const s=e.resolve(n),i=t&&s&&t.get(s);return i?i.count*i.aliasCount:0}else if(q(e)){let s=0;for(const i of e.items){const r=bt(n,i,t);r>s&&(s=r)}return s}else if(R(e)){const s=bt(n,e.key,t),i=bt(n,e.value,t);return Math.max(s,i)}return 1}l(bt,"getAliasCount");const Ps=l(n=>!n||typeof n!="function"&&typeof n!="object","isScalarValue");class _ extends Cn{static{l(this,"Scalar")}constructor(e){super(oe),this.value=e}toJSON(e,t){return t?.keep?this.value:X(this.value,e,t)}toString(){return String(this.value)}}_.BLOCK_FOLDED="BLOCK_FOLDED",_.BLOCK_LITERAL="BLOCK_LITERAL",_.PLAIN="PLAIN",_.QUOTE_DOUBLE="QUOTE_DOUBLE",_.QUOTE_SINGLE="QUOTE_SINGLE";const Oo="tag:yaml.org,2002:";function Eo(n,e,t){if(e){const s=t.filter(r=>r.tag===e),i=s.find(r=>!r.format)??s[0];if(!i)throw new Error(`Tag ${e} not found`);return i}return t.find(s=>s.identify?.(n)&&!s.format)}l(Eo,"findTagObject");function tt(n,e,t){if(we(n)&&(n=n.contents),U(n))return n;if(R(n)){const f=t.schema[he].createNode?.(t.schema,null,t);return f.items.push(n),f}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());const{aliasDuplicateObjects:s,onAnchor:i,onTagObj:r,schema:o,sourceObjects:a}=t;let c;if(s&&n&&typeof n=="object"){if(c=a.get(n),c)return c.anchor??(c.anchor=i(n)),new wt(c.anchor);c={anchor:null,node:null},a.set(n,c)}e?.startsWith("!!")&&(e=Oo+e.slice(2));let u=Eo(n,e,o.tags);if(!u){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){const f=new _(n);return c&&(c.node=f),f}u=n instanceof Map?o[he]:Symbol.iterator in Object(n)?o[Oe]:o[he]}r&&(r(u),delete t.onTagObj);const d=u?.createNode?u.createNode(t.schema,n,t):typeof u?.nodeClass?.from=="function"?u.nodeClass.from(t.schema,n,t):new _(n);return e?d.tag=e:u.default||(d.tag=u.tag),c&&(c.node=d),d}l(tt,"createNode");function St(n,e,t){let s=t;for(let i=e.length-1;i>=0;--i){const r=e[i];if(typeof r=="number"&&Number.isInteger(r)&&r>=0){const o=[];o[r]=s,s=o}else s=new Map([[r,s]])}return tt(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:l(()=>{throw new Error("This should not happen, please report a bug.")},"onAnchor"),schema:n,sourceObjects:new Map})}l(St,"collectionFromPath");const nt=l(n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,"isEmptyPath");class xs extends Cn{static{l(this,"Collection")}constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){const t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(s=>U(s)||R(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(nt(e))this.add(t);else{const[s,...i]=e,r=this.get(s,!0);if(q(r))r.addIn(i,t);else if(r===void 0&&this.schema)this.set(s,St(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}deleteIn(e){const[t,...s]=e;if(s.length===0)return this.delete(t);const i=this.get(t,!0);if(q(i))return i.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){const[s,...i]=e,r=this.get(s,!0);return i.length===0?!t&&K(r)?r.value:r:q(r)?r.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!R(t))return!1;const s=t.value;return s==null||e&&K(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){const[t,...s]=e;if(s.length===0)return this.has(t);const i=this.get(t,!0);return q(i)?i.hasIn(s):!1}setIn(e,t){const[s,...i]=e;if(i.length===0)this.set(s,t);else{const r=this.get(s,!0);if(q(r))r.setIn(i,t);else if(r===void 0&&this.schema)this.set(s,St(this.schema,i,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${i}`)}}}const $o=l(n=>n.replace(/^(?!$)(?: $)?/gm,"#"),"stringifyComment");function ce(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}l(ce,"indentComment");const Se=l((n,e,t)=>n.endsWith(`
|
|
4
|
+
`)?ce(t,e):t.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
`+
|
|
7
|
-
`)t===
|
|
8
|
-
`&&
|
|
9
|
-
`&&
|
|
10
|
-
${e}${
|
|
11
|
-
${e}${
|
|
12
|
-
`);
|
|
13
|
-
`){if(
|
|
14
|
-
|
|
15
|
-
`;t[
|
|
16
|
-
`,
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
18
|
-
${t}`)+"'";return e.implicitKey?
|
|
6
|
+
`+ce(t,e):(n.endsWith(" ")?"":" ")+t,"lineComment"),js="flow",vn="block",kt="quoted";function Ct(n,e,t="flow",{indentAtStart:s,lineWidth:i=80,minContentWidth:r=20,onFold:o,onOverflow:a}={}){if(!i||i<0)return n;i<r&&(r=0);const c=Math.max(1+r,1+i-e.length);if(n.length<=c)return n;const u=[],d={};let f=i-e.length;typeof s=="number"&&(s>i-Math.max(2,r)?u.push(0):f=i-s);let h,m,w=!1,p=-1,y=-1,S=-1;t===vn&&(p=Ks(n,p,e.length),p!==-1&&(f=p+c));for(let C;C=n[p+=1];){if(t===kt&&C==="\\"){switch(y=p,n[p+1]){case"x":p+=3;break;case"u":p+=5;break;case"U":p+=9;break;default:p+=1}S=p}if(C===`
|
|
7
|
+
`)t===vn&&(p=Ks(n,p,e.length)),f=p+e.length+c,h=void 0;else{if(C===" "&&m&&m!==" "&&m!==`
|
|
8
|
+
`&&m!==" "){const A=n[p+1];A&&A!==" "&&A!==`
|
|
9
|
+
`&&A!==" "&&(h=p)}if(p>=f)if(h)u.push(h),f=h+c,h=void 0;else if(t===kt){for(;m===" "||m===" ";)m=C,C=n[p+=1],w=!0;const A=p>S+1?p-2:y-1;if(d[A])return n;u.push(A),d[A]=!0,f=A+c,h=void 0}else w=!0}m=C}if(w&&a&&a(),u.length===0)return n;o&&o();let b=n.slice(0,u[0]);for(let C=0;C<u.length;++C){const A=u[C],$=u[C+1]||n.length;A===0?b=`
|
|
10
|
+
${e}${n.slice(0,$)}`:(t===kt&&d[A]&&(b+=`${n[A]}\\`),b+=`
|
|
11
|
+
${e}${n.slice(A+1,$)}`)}return b}l(Ct,"foldFlowLines");function Ks(n,e,t){let s=e,i=e+1,r=n[i];for(;r===" "||r===" ";)if(e<i+t)r=n[++e];else{do r=n[++e];while(r&&r!==`
|
|
12
|
+
`);s=e,i=e+1,r=n[i]}return s}l(Ks,"consumeMoreIndentedLines");const vt=l((n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),"getFoldOptions"),At=l(n=>/^(%|---|\.\.\.)/m.test(n),"containsDocumentMarker");function Io(n,e,t){if(!e||e<0)return!1;const s=e-t,i=n.length;if(i<=s)return!1;for(let r=0,o=0;r<i;++r)if(n[r]===`
|
|
13
|
+
`){if(r-o>s)return!0;if(o=r+1,i-o<=s)return!1}return!0}l(Io,"lineLengthOverLimit");function st(n,e){const t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;const{implicitKey:s}=e,i=e.options.doubleQuotedMinMultiLineLength,r=e.indent||(At(n)?" ":"");let o="",a=0;for(let c=0,u=t[c];u;u=t[++c])if(u===" "&&t[c+1]==="\\"&&t[c+2]==="n"&&(o+=t.slice(a,c)+"\\ ",c+=1,a=c,u="\\"),u==="\\")switch(t[c+1]){case"u":{o+=t.slice(a,c);const d=t.substr(c+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(c,6)}c+=5,a=c+1}break;case"n":if(s||t[c+2]==='"'||t.length<i)c+=1;else{for(o+=t.slice(a,c)+`
|
|
14
|
+
|
|
15
|
+
`;t[c+2]==="\\"&&t[c+3]==="n"&&t[c+4]!=='"';)o+=`
|
|
16
|
+
`,c+=2;o+=r,t[c+2]===" "&&(o+="\\"),c+=1,a=c+1}break;default:c+=1}return o=a?o+t.slice(a):t,s?o:Ct(o,r,kt,vt(e,!1))}l(st,"doubleQuotedString");function An(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test(n))return st(n,e);const t=e.indent||(At(n)?" ":""),s="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${t}`)+"'";return e.implicitKey?s:Ct(s,t,js,vt(e,!1))}l(An,"singleQuotedString");function _e(n,e){const{singleQuote:t}=e.options;let s;if(t===!1)s=st;else{const i=n.includes('"'),r=n.includes("'");i&&!r?s=An:r&&!i?s=st:s=t?An:st}return s(n,e)}l(_e,"quotedString");let Tn;try{Tn=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{Tn=/\n+(?!\n|$)/g}function Tt({comment:n,type:e,value:t},s,i,r){const{blockQuote:o,commentString:a,lineWidth:c}=s.options;if(!o||/\n[\t ]+$/.test(t)||/^\s*$/.test(t))return _e(t,s);const u=s.indent||(s.forceBlockIndent||At(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===_.BLOCK_FOLDED?!1:e===_.BLOCK_LITERAL?!0:!Io(t,c,u.length);if(!t)return d?`|
|
|
22
22
|
`:`>
|
|
23
|
-
`;let f,h;for(h=t.length;h>0;--h){const
|
|
24
|
-
|
|
25
|
-
`);w===-1?f="-":t===
|
|
26
|
-
`&&(
|
|
27
|
-
`)
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let
|
|
29
|
-
${u}${
|
|
30
|
-
${u}${
|
|
31
|
-
`)||d&&/[[\]{},]/.test(
|
|
32
|
-
`)?
|
|
33
|
-
`))return
|
|
34
|
-
${
|
|
35
|
-
${e.indent}${
|
|
36
|
-
${
|
|
37
|
-
`:"",
|
|
38
|
-
${
|
|
39
|
-
`&&(
|
|
40
|
-
|
|
41
|
-
`):
|
|
42
|
-
${t.indent}`}else if(!
|
|
43
|
-
`),
|
|
44
|
-
${t.indent}`)}}else(
|
|
45
|
-
`)&&(
|
|
46
|
-
${
|
|
47
|
-
`}}return
|
|
48
|
-
`+
|
|
49
|
-
`))&&(u=!0),f.push(
|
|
50
|
-
${
|
|
23
|
+
`;let f,h;for(h=t.length;h>0;--h){const $=t[h-1];if($!==`
|
|
24
|
+
`&&$!==" "&&$!==" ")break}let m=t.substring(h);const w=m.indexOf(`
|
|
25
|
+
`);w===-1?f="-":t===m||w!==m.length-1?(f="+",r&&r()):f="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
|
|
26
|
+
`&&(m=m.slice(0,-1)),m=m.replace(Tn,`$&${u}`));let p=!1,y,S=-1;for(y=0;y<t.length;++y){const $=t[y];if($===" ")p=!0;else if($===`
|
|
27
|
+
`)S=y;else break}let b=t.substring(0,S<y?S+1:y);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${u}`));let A=(p?u?"2":"1":"")+f;if(n&&(A+=" "+a(n.replace(/ ?[\r\n]+/g," ")),i&&i()),!d){const $=t.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${u}`);let N=!1;const D=vt(s,!0);o!=="folded"&&e!==_.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});const T=Ct(`${b}${$}${m}`,u,vn,D);if(!N)return`>${A}
|
|
29
|
+
${u}${T}`}return t=t.replace(/\n+/g,`$&${u}`),`|${A}
|
|
30
|
+
${u}${b}${t}${m}`}l(Tt,"blockString");function No(n,e,t,s){const{type:i,value:r}=n,{actualString:o,implicitKey:a,indent:c,indentStep:u,inFlow:d}=e;if(a&&r.includes(`
|
|
31
|
+
`)||d&&/[[\]{},]/.test(r))return _e(r,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(r))return a||d||!r.includes(`
|
|
32
|
+
`)?_e(r,e):Tt(n,e,t,s);if(!a&&!d&&i!==_.PLAIN&&r.includes(`
|
|
33
|
+
`))return Tt(n,e,t,s);if(At(r)){if(c==="")return e.forceBlockIndent=!0,Tt(n,e,t,s);if(a&&c===u)return _e(r,e)}const f=r.replace(/\n+/g,`$&
|
|
34
|
+
${c}`);if(o){const h=l(p=>p.default&&p.tag!=="tag:yaml.org,2002:str"&&p.test?.test(f),"test"),{compat:m,tags:w}=e.doc.schema;if(w.some(h)||m?.some(h))return _e(r,e)}return a?f:Ct(f,c,js,vt(e,!1))}l(No,"plainString");function it(n,e,t,s){const{implicitKey:i,inFlow:r}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)});let{type:a}=n;a!==_.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=_.QUOTE_DOUBLE);const c=l(d=>{switch(d){case _.BLOCK_FOLDED:case _.BLOCK_LITERAL:return i||r?_e(o.value,e):Tt(o,e,t,s);case _.QUOTE_DOUBLE:return st(o.value,e);case _.QUOTE_SINGLE:return An(o.value,e);case _.PLAIN:return No(o,e,t,s);default:return null}},"_stringify");let u=c(a);if(u===null){const{defaultKeyType:d,defaultStringType:f}=e.options,h=i&&d||f;if(u=c(h),u===null)throw new Error(`Unsupported default string type ${h}`)}return u}l(it,"stringifyString");function Ds(n,e){const t=Object.assign({blockQuote:!0,commentString:$o,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e);let s;switch(t.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}l(Ds,"createStringifyContext");function Lo(n,e){if(e.tag){const i=n.filter(r=>r.tag===e.tag);if(i.length>0)return i.find(r=>r.format===e.format)??i[0]}let t,s;if(K(e)){s=e.value;let i=n.filter(r=>r.identify?.(s));if(i.length>1){const r=i.filter(o=>o.test);r.length>0&&(i=r)}t=i.find(r=>r.format===e.format)??i.find(r=>!r.format)}else s=e,t=n.find(i=>i.nodeClass&&s instanceof i.nodeClass);if(!t){const i=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${i} value`)}return t}l(Lo,"getTagObject");function _o(n,e,{anchors:t,doc:s}){if(!s.directives)return"";const i=[],r=(K(n)||q(n))&&n.anchor;r&&Ns(r)&&(t.add(r),i.push(`&${r}`));const o=n.tag??(e.default?null:e.tag);return o&&i.push(s.directives.tagString(o)),i.join(" ")}l(_o,"stringifyProps");function Pe(n,e,t,s){if(R(n))return n.toString(e,t,s);if(pe(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let i;const r=U(n)?n:e.doc.createNode(n,{onTagObj:l(c=>i=c,"onTagObj")});i??(i=Lo(e.doc.schema.tags,r));const o=_o(r,i,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);const a=typeof i.stringify=="function"?i.stringify(r,e,t,s):K(r)?it(r,e,t,s):r.toString(e,t,s);return o?K(r)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
|
|
35
|
+
${e.indent}${a}`:a}l(Pe,"stringify$2");function Po({key:n,value:e},t,s,i){const{allNullValues:r,doc:o,indent:a,indentStep:c,options:{commentString:u,indentSeq:d,simpleKeys:f}}=t;let h=U(n)&&n.comment||null;if(f){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(q(n)||!U(n)&&typeof n=="object"){const D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let m=!f&&(!n||h&&e==null&&!t.inFlow||q(n)||(K(n)?n.type===_.BLOCK_FOLDED||n.type===_.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(f||!r),indent:a+c});let w=!1,p=!1,y=Pe(n,t,()=>w=!0,()=>p=!0);if(!m&&!t.inFlow&&y.length>1024){if(f)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(r||e==null)return w&&s&&s(),y===""?"?":m?`? ${y}`:y}else if(r&&!f||e==null&&m)return y=`? ${y}`,h&&!w?y+=Se(y,t.indent,u(h)):p&&i&&i(),y;w&&(h=null),m?(h&&(y+=Se(y,t.indent,u(h))),y=`? ${y}
|
|
36
|
+
${a}:`):(y=`${y}:`,h&&(y+=Se(y,t.indent,u(h))));let S,b,C;U(e)?(S=!!e.spaceBefore,b=e.commentBefore,C=e.comment):(S=!1,b=null,C=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!m&&!h&&K(e)&&(t.indentAtStart=y.length+1),p=!1,!d&&c.length>=2&&!t.inFlow&&!m&&$e(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let A=!1;const $=Pe(e,t,()=>A=!0,()=>p=!0);let N=" ";if(h||S||b){if(N=S?`
|
|
37
|
+
`:"",b){const D=u(b);N+=`
|
|
38
|
+
${ce(D,t.indent)}`}$===""&&!t.inFlow?N===`
|
|
39
|
+
`&&(N=`
|
|
40
|
+
|
|
41
|
+
`):N+=`
|
|
42
|
+
${t.indent}`}else if(!m&&q(e)){const D=$[0],T=$.indexOf(`
|
|
43
|
+
`),J=T!==-1,ue=t.inFlow??e.flow??e.items.length===0;if(J||!ue){let Ae=!1;if(J&&(D==="&"||D==="!")){let V=$.indexOf(" ");D==="&"&&V!==-1&&V<T&&$[V+1]==="!"&&(V=$.indexOf(" ",V+1)),(V===-1||T<V)&&(Ae=!0)}Ae||(N=`
|
|
44
|
+
${t.indent}`)}}else($===""||$[0]===`
|
|
45
|
+
`)&&(N="");return y+=N+$,t.inFlow?A&&s&&s():C&&!A?y+=Se(y,t.indent,u(C)):p&&i&&i(),y}l(Po,"stringifyPair");function Ms(n,e){(n==="debug"||n==="warn")&&console.warn(e)}l(Ms,"warn");const Ot="<<",le={identify:l(n=>n===Ot||typeof n=="symbol"&&n.description===Ot,"identify"),default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:l(()=>Object.assign(new _(Symbol(Ot)),{addToJSMap:Rs}),"resolve"),stringify:l(()=>Ot,"stringify")},xo=l((n,e)=>(le.identify(e)||K(e)&&(!e.type||e.type===_.PLAIN)&&le.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===le.tag&&t.default),"isMergeKey");function Rs(n,e,t){if(t=n&&pe(t)?t.resolve(n.doc):t,$e(t))for(const s of t.items)On(n,e,s);else if(Array.isArray(t))for(const s of t)On(n,e,s);else On(n,e,t)}l(Rs,"addMergeToJSMap");function On(n,e,t){const s=n&&pe(t)?t.resolve(n.doc):t;if(!Ee(s))throw new Error("Merge sources must be maps or map aliases");const i=s.toJSON(null,n,Map);for(const[r,o]of i)e instanceof Map?e.has(r)||e.set(r,o):e instanceof Set?e.add(r):Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}l(On,"mergeValue");function Bs(n,e,{key:t,value:s}){if(U(t)&&t.addToJSMap)t.addToJSMap(n,e,s);else if(xo(n,t))Rs(n,e,s);else{const i=X(t,"",n);if(e instanceof Map)e.set(i,X(s,i,n));else if(e instanceof Set)e.add(i);else{const r=jo(t,i,n),o=X(s,r,n);r in e?Object.defineProperty(e,r,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[r]=o}}return e}l(Bs,"addPairToJSMap");function jo(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(U(n)&&t?.doc){const s=Ds(t.doc,{});s.anchors=new Set;for(const r of t.anchors.keys())s.anchors.add(r.anchor);s.inFlow=!0,s.inStringifyKey=!0;const i=n.toString(s);if(!t.mapKeyWarned){let r=JSON.stringify(i);r.length>40&&(r=r.substring(0,36)+'..."'),Ms(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${r}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return i}return JSON.stringify(e)}l(jo,"stringifyKey");function En(n,e,t){const s=tt(n,void 0,t),i=tt(e,void 0,t);return new z(s,i)}l(En,"createPair");class z{static{l(this,"Pair")}constructor(e,t=null){Object.defineProperty(this,Q,{value:As}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return U(t)&&(t=t.clone(e)),U(s)&&(s=s.clone(e)),new z(t,s)}toJSON(e,t){const s=t?.mapAsMap?new Map:{};return Bs(t,s,this)}toString(e,t,s){return e?.doc?Po(this,e,t,s):JSON.stringify(this)}}function Fs(n,e,t){return(e.inFlow??n.flow?Do:Ko)(n,e,t)}l(Fs,"stringifyCollection");function Ko({comment:n,items:e},t,{blockItemPrefix:s,flowChars:i,itemIndent:r,onChompKeep:o,onComment:a}){const{indent:c,options:{commentString:u}}=t,d=Object.assign({},t,{indent:r,type:null});let f=!1;const h=[];for(let w=0;w<e.length;++w){const p=e[w];let y=null;if(U(p))!f&&p.spaceBefore&&h.push(""),Et(t,h,p.commentBefore,f),p.comment&&(y=p.comment);else if(R(p)){const b=U(p.key)?p.key:null;b&&(!f&&b.spaceBefore&&h.push(""),Et(t,h,b.commentBefore,f))}f=!1;let S=Pe(p,d,()=>y=null,()=>f=!0);y&&(S+=Se(S,r,u(y))),f&&y&&(f=!1),h.push(s+S)}let m;if(h.length===0)m=i.start+i.end;else{m=h[0];for(let w=1;w<h.length;++w){const p=h[w];m+=p?`
|
|
46
|
+
${c}${p}`:`
|
|
47
|
+
`}}return n?(m+=`
|
|
48
|
+
`+ce(u(n),c),a&&a()):f&&o&&o(),m}l(Ko,"stringifyBlockCollection");function Do({items:n},e,{flowChars:t,itemIndent:s}){const{indent:i,indentStep:r,flowCollectionPadding:o,options:{commentString:a}}=e;s+=r;const c=Object.assign({},e,{indent:s,inFlow:!0,type:null});let u=!1,d=0;const f=[];for(let w=0;w<n.length;++w){const p=n[w];let y=null;if(U(p))p.spaceBefore&&f.push(""),Et(e,f,p.commentBefore,!1),p.comment&&(y=p.comment);else if(R(p)){const b=U(p.key)?p.key:null;b&&(b.spaceBefore&&f.push(""),Et(e,f,b.commentBefore,!1),b.comment&&(u=!0));const C=U(p.value)?p.value:null;C?(C.comment&&(y=C.comment),C.commentBefore&&(u=!0)):p.value==null&&b?.comment&&(y=b.comment)}y&&(u=!0);let S=Pe(p,c,()=>y=null);w<n.length-1&&(S+=","),y&&(S+=Se(S,s,a(y))),!u&&(f.length>d||S.includes(`
|
|
49
|
+
`))&&(u=!0),f.push(S),d=f.length}const{start:h,end:m}=t;if(f.length===0)return h+m;if(!u){const w=f.reduce((p,y)=>p+y.length+2,2);u=e.options.lineWidth>0&&w>e.options.lineWidth}if(u){let w=h;for(const p of f)w+=p?`
|
|
50
|
+
${r}${i}${p}`:`
|
|
51
51
|
`;return`${w}
|
|
52
|
-
${
|
|
53
|
-
`:" ")}return
|
|
54
|
-
${
|
|
55
|
-
${i.comment}`:n.comment}n=r}s.items[t]=z(n)?n:new ee(n)}}else e("Expected a sequence for this tag");return s}c(Jr,"resolvePairs");function zr(s,e,t){const{replacer:n}=t,r=new xe(s);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let a of e){typeof n=="function"&&(a=n.call(e,String(i++),a));let o,l;if(Array.isArray(a))if(a.length===2)o=a[0],l=a[1];else throw new TypeError(`Expected [key, value] tuple: ${a}`);else if(a&&a instanceof Object){const u=Object.keys(a);if(u.length===1)o=u[0],l=a[o];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else o=a;r.items.push(ns(o,l,t))}return r}c(zr,"createPairs");const as={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Jr,createNode:zr};class ht extends xe{static{c(this,"YAMLOMap")}constructor(){super(),this.add=re.prototype.add.bind(this),this.delete=re.prototype.delete.bind(this),this.get=re.prototype.get.bind(this),this.has=re.prototype.has.bind(this),this.set=re.prototype.set.bind(this),this.tag=ht.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,a;if(z(r)?(i=ce(r.key,"",t),a=ce(r.value,i,t)):i=ce(r,"",t),n.has(i))throw new Error("Ordered maps must not include duplicate keys");n.set(i,a)}return n}static from(e,t,n){const r=zr(e,t,n),i=new this;return i.items=r.items,i}}ht.tag="tag:yaml.org,2002:omap";const os={collection:"seq",identify:c(s=>s instanceof Map,"identify"),nodeClass:ht,default:!1,tag:"tag:yaml.org,2002:omap",resolve(s,e){const t=Jr(s,e),n=[];for(const{key:r}of t.items)V(r)&&(n.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):n.push(r.value));return Object.assign(new ht,t)},createNode:c((s,e,t)=>ht.from(s,e,t),"createNode")};function Wr({value:s,source:e},t){return e&&(s?Gr:Hr).test.test(e)?e:s?t.options.trueStr:t.options.falseStr}c(Wr,"boolStringify");const Gr={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:Wr},Hr={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:Wr},tc={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:c(s=>s.slice(-3).toLowerCase()==="nan"?NaN:s[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:ue},nc={identify:c(s=>typeof s=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:c(s=>parseFloat(s.replace(/_/g,"")),"resolve"),stringify(s){const e=Number(s.value);return isFinite(e)?e.toExponential():ue(s)}},sc={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:ue},Tt=c(s=>typeof s=="bigint"||Number.isInteger(s),"intIdentify");function cn(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 a=BigInt(s);return r==="-"?BigInt(-1)*a:a}const i=parseInt(s,t);return r==="-"?-1*i:i}c(cn,"intResolve");function cs(s,e,t){const{value:n}=s;if(Tt(n)){const r=n.toString(e);return n<0?"-"+t+r.substr(1):t+r}return ue(s)}c(cs,"intStringify");const rc={identify:Tt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:c((s,e,t)=>cn(s,2,2,t),"resolve"),stringify:c(s=>cs(s,2,"0b"),"stringify")},ic={identify:Tt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:c((s,e,t)=>cn(s,1,8,t),"resolve"),stringify:c(s=>cs(s,8,"0"),"stringify")},ac={identify:Tt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:c((s,e,t)=>cn(s,0,10,t),"resolve"),stringify:ue},oc={identify:Tt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:c((s,e,t)=>cn(s,2,16,t),"resolve"),stringify:c(s=>cs(s,16,"0x"),"stringify")};class pt extends re{static{c(this,"YAMLSet")}constructor(e){super(e),this.tag=pt.tag}add(e){let t;z(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new ee(e.key,null):t=new ee(e,null),De(this.items,t.key)||this.items.push(t)}get(e,t){const n=De(this.items,e);return!t&&z(n)?V(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const n=De(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ee(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 a of t)typeof r=="function"&&(a=r.call(t,a,a)),i.items.push(ns(a,null,n));return i}}pt.tag="tag:yaml.org,2002:set";const ls={collection:"map",identify:c(s=>s instanceof Set,"identify"),nodeClass:pt,default:!1,tag:"tag:yaml.org,2002:set",createNode:c((s,e,t)=>pt.from(s,e,t),"createNode"),resolve(s,e){if(ze(s)){if(s.hasAllNullValues(!0))return Object.assign(new pt,s);e("Set items must all have null values")}else e("Expected a mapping for this tag");return s}};function us(s,e){const t=s[0],n=t==="-"||t==="+"?s.substring(1):s,r=c(a=>e?BigInt(a):Number(a),"num"),i=n.replace(/_/g,"").split(":").reduce((a,o)=>a*r(60)+r(o),r(0));return t==="-"?r(-1)*i:i}c(us,"parseSexagesimal");function Yr(s){let{value:e}=s,t=c(a=>a,"num");if(typeof e=="bigint")t=c(a=>BigInt(a),"num");else if(isNaN(e)||!isFinite(e))return ue(s);let n="";e<0&&(n="-",e*=t(-1));const r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),n+i.map(a=>String(a).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}c(Yr,"stringifySexagesimal");const Qr={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})=>us(s,t),"resolve"),stringify:Yr},Xr={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=>us(s,!1),"resolve"),stringify:Yr},ln={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(ln.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,n,r,i,a,o]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,n-1,r,i||0,a||0,o||0,l);const d=e[8];if(d&&d!=="Z"){let f=us(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")},ei=[et,tt,sn,rn,Gr,Hr,rc,ic,ac,oc,tc,nc,sc,is,ve,os,as,ls,Qr,Xr,ln],ti=new Map([["core",Yo],["failsafe",[et,tt,sn]],["json",ec],["yaml11",ei],["yaml-1.1",ei]]),ni={binary:is,bool:ss,float:Br,floatExp:Mr,floatNaN:Kr,floatTime:Xr,int:Ur,intHex:Vr,intOct:qr,intTime:Qr,map:et,merge:ve,null:rn,omap:os,pairs:as,seq:tt,set:ls,timestamp:ln},cc={"tag:yaml.org,2002:binary":is,"tag:yaml.org,2002:merge":ve,"tag:yaml.org,2002:omap":os,"tag:yaml.org,2002:pairs":as,"tag:yaml.org,2002:set":ls,"tag:yaml.org,2002:timestamp":ln};function ds(s,e,t){const n=ti.get(e);if(n&&!s)return t&&!n.includes(ve)?n.concat(ve):n.slice();let r=n;if(!r)if(Array.isArray(s))r=[];else{const i=Array.from(ti.keys()).filter(a=>a!=="yaml11").map(a=>JSON.stringify(a)).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(ve)),r.reduce((i,a)=>{const o=typeof a=="string"?ni[a]:a;if(!o){const l=JSON.stringify(a),u=Object.keys(ni).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${u}`)}return i.includes(o)||i.push(o),i},[])}c(ds,"getTags");const lc=c((s,e)=>s.key<e.key?-1:s.key>e.key?1:0,"sortMapEntriesByKey");class Nn{static{c(this,"Schema")}constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?ds(e,"compat"):e?ds(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?cc:{},this.tags=ds(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Ae,{value:et}),Object.defineProperty(this,me,{value:sn}),Object.defineProperty(this,Je,{value:tt}),this.sortMapEntries=typeof a=="function"?a:a===!0?lc:null}clone(){const e=Object.create(Nn.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function uc(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=Lr(s,e),{commentString:i}=r.options;if(s.commentBefore){t.length!==1&&t.unshift("");const l=i(s.commentBefore);t.unshift(be(l,""))}let a=!1,o=null;if(s.contents){if(G(s.contents)){if(s.contents.spaceBefore&&n&&t.push(""),s.contents.commentBefore){const d=i(s.contents.commentBefore);t.push(be(d,""))}r.forceBlockIndent=!!s.comment,o=s.contents.comment}const l=o?void 0:()=>a=!0;let u=Xe(s.contents,r,()=>o=null,l);o&&(u+=Re(u,"",i(o))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Xe(s.contents,r));if(s.directives?.docEnd)if(s.comment){const l=i(s.comment);l.includes(`
|
|
56
|
-
`)?(t.push("..."),t.push(
|
|
52
|
+
${i}${m}`}else return`${h}${o}${f.join(" ")}${o}${m}`}l(Do,"stringifyFlowCollection");function Et({indent:n,options:{commentString:e}},t,s,i){if(s&&i&&(s=s.replace(/^\n+/,"")),s){const r=ce(e(s),n);t.push(r.trimStart())}}l(Et,"addCommentBefore");function ke(n,e){const t=K(e)?e.value:e;for(const s of n)if(R(s)&&(s.key===e||s.key===t||K(s.key)&&s.key.value===t))return s}l(ke,"findPair");class Z extends xs{static{l(this,"YAMLMap")}static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(he,e),this.items=[]}static from(e,t,s){const{keepUndefined:i,replacer:r}=s,o=new this(e),a=l((c,u)=>{if(typeof r=="function")u=r.call(t,c,u);else if(Array.isArray(r)&&!r.includes(c))return;(u!==void 0||i)&&o.items.push(En(c,u,s))},"add");if(t instanceof Map)for(const[c,u]of t)a(c,u);else if(t&&typeof t=="object")for(const c of Object.keys(t))a(c,t[c]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let s;R(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new z(e,e?.value):s=new z(e.key,e.value);const i=ke(this.items,s.key),r=this.schema?.sortMapEntries;if(i){if(!t)throw new Error(`Key ${s.key} already set`);K(i.value)&&Ps(s.value)?i.value.value=s.value:i.value=s.value}else if(r){const o=this.items.findIndex(a=>r(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){const t=ke(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){const i=ke(this.items,e)?.value;return(!t&&K(i)?i.value:i)??void 0}has(e){return!!ke(this.items,e)}set(e,t){this.add(new z(e,t),!0)}toJSON(e,t,s){const i=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(i);for(const r of this.items)Bs(t,i,r);return i}toString(e,t,s){if(!e)return JSON.stringify(this);for(const i of this.items)if(!R(i))throw new Error(`Map items must all be pairs; found ${JSON.stringify(i)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Fs(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}}const xe={collection:"map",default:!0,nodeClass:Z,tag:"tag:yaml.org,2002:map",resolve(n,e){return Ee(n)||e("Expected a mapping for this tag"),n},createNode:l((n,e,t)=>Z.from(n,e,t),"createNode")};class me extends xs{static{l(this,"YAMLSeq")}static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Oe,e),this.items=[]}add(e){this.items.push(e)}delete(e){const t=$t(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){const s=$t(e);if(typeof s!="number")return;const i=this.items[s];return!t&&K(i)?i.value:i}has(e){const t=$t(e);return typeof t=="number"&&t<this.items.length}set(e,t){const s=$t(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);const i=this.items[s];K(i)&&Ps(t)?i.value=t:this.items[s]=t}toJSON(e,t){const s=[];t?.onCreate&&t.onCreate(s);let i=0;for(const r of this.items)s.push(X(r,String(i++),t));return s}toString(e,t,s){return e?Fs(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){const{replacer:i}=s,r=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof i=="function"){const c=t instanceof Set?a:String(o++);a=i.call(t,c,a)}r.items.push(tt(a,void 0,s))}}return r}}function $t(n){let e=K(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}l($t,"asItemIndex");const je={collection:"seq",default:!0,nodeClass:me,tag:"tag:yaml.org,2002:seq",resolve(n,e){return $e(n)||e("Expected a sequence for this tag"),n},createNode:l((n,e,t)=>me.from(n,e,t),"createNode")},It={identify:l(n=>typeof n=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(n=>n,"resolve"),stringify(n,e,t,s){return e=Object.assign({actualString:!0},e),it(n,e,t,s)}},Nt={identify:l(n=>n==null,"identify"),createNode:l(()=>new _(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:l(()=>new _(null),"resolve"),stringify:l(({source:n},e)=>typeof n=="string"&&Nt.test.test(n)?n:e.options.nullStr,"stringify")},$n={identify:l(n=>typeof n=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:l(n=>new _(n[0]==="t"||n[0]==="T"),"resolve"),stringify({source:n,value:e},t){if(n&&$n.test.test(n)){const s=n[0]==="t"||n[0]==="T";if(e===s)return n}return e?t.options.trueStr:t.options.falseStr}};function te({format:n,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);const i=typeof s=="number"?s:Number(s);if(!isFinite(i))return isNaN(i)?".nan":i<0?"-.inf":".inf";let r=JSON.stringify(s);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(r)){let o=r.indexOf(".");o<0&&(o=r.length,r+=".");let a=e-(r.length-o-1);for(;a-- >0;)r+="0"}return r}l(te,"stringifyNumber");const qs={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:te},Us={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:l(n=>parseFloat(n),"resolve"),stringify(n){const e=Number(n.value);return isFinite(e)?e.toExponential():te(n)}},Js={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){const e=new _(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:te},Lt=l(n=>typeof n=="bigint"||Number.isInteger(n),"intIdentify$2"),In=l((n,e,t,{intAsBigInt:s})=>s?BigInt(n):parseInt(n.substring(e),t),"intResolve$1");function Vs(n,e,t){const{value:s}=n;return Lt(s)&&s>=0?t+s.toString(e):te(n)}l(Vs,"intStringify$1");const Ws={identify:l(n=>Lt(n)&&n>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:l((n,e,t)=>In(n,2,8,t),"resolve"),stringify:l(n=>Vs(n,8,"0o"),"stringify")},zs={identify:Lt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:l((n,e,t)=>In(n,0,10,t),"resolve"),stringify:te},Hs={identify:l(n=>Lt(n)&&n>=0,"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:l((n,e,t)=>In(n,2,16,t),"resolve"),stringify:l(n=>Vs(n,16,"0x"),"stringify")},Mo=[xe,je,It,Nt,$n,Ws,zs,Hs,qs,Us,Js];function Gs(n){return typeof n=="bigint"||Number.isInteger(n)}l(Gs,"intIdentify$1");const _t=l(({value:n})=>JSON.stringify(n),"stringifyJSON"),Ro=[{identify:l(n=>typeof n=="string","identify"),default:!0,tag:"tag:yaml.org,2002:str",resolve:l(n=>n,"resolve"),stringify:_t},{identify:l(n=>n==null,"identify"),createNode:l(()=>new _(null),"createNode"),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:l(()=>null,"resolve"),stringify:_t},{identify:l(n=>typeof n=="boolean","identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:l(n=>n==="true","resolve"),stringify:_t},{identify:Gs,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:l((n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),"resolve"),stringify:l(({value:n})=>Gs(n)?n.toString():JSON.stringify(n),"stringify")},{identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:l(n=>parseFloat(n),"resolve"),stringify:_t}],Bo={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},Fo=[xe,je].concat(Ro,Bo),Nn={identify:l(n=>n instanceof Uint8Array,"identify"),default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof atob=="function"){const t=atob(n.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let i=0;i<t.length;++i)s[i]=t.charCodeAt(i);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},s,i,r){if(!t)return"";const o=t;let a;if(typeof btoa=="function"){let c="";for(let u=0;u<o.length;++u)c+=String.fromCharCode(o[u]);a=btoa(c)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=_.BLOCK_LITERAL),e!==_.QUOTE_DOUBLE){const c=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),u=Math.ceil(a.length/c),d=new Array(u);for(let f=0,h=0;f<u;++f,h+=c)d[f]=a.substr(h,c);a=d.join(e===_.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return it({comment:n,type:e,value:a},s,i,r)}};function Ys(n,e){if($e(n))for(let t=0;t<n.items.length;++t){let s=n.items[t];if(!R(s)){if(Ee(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");const i=s.items[0]||new z(new _(null));if(s.commentBefore&&(i.key.commentBefore=i.key.commentBefore?`${s.commentBefore}
|
|
54
|
+
${i.key.commentBefore}`:s.commentBefore),s.comment){const r=i.value??i.key;r.comment=r.comment?`${s.comment}
|
|
55
|
+
${r.comment}`:s.comment}s=i}n.items[t]=R(s)?s:new z(s)}}else e("Expected a sequence for this tag");return n}l(Ys,"resolvePairs");function Zs(n,e,t){const{replacer:s}=t,i=new me(n);i.tag="tag:yaml.org,2002:pairs";let r=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(r++),o));let a,c;if(Array.isArray(o))if(o.length===2)a=o[0],c=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const u=Object.keys(o);if(u.length===1)a=u[0],c=o[a];else throw new TypeError(`Expected tuple with one key, not ${u.length} keys`)}else a=o;i.items.push(En(a,c,t))}return i}l(Zs,"createPairs");const Ln={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ys,createNode:Zs};class ze extends me{static{l(this,"YAMLOMap")}constructor(){super(),this.add=Z.prototype.add.bind(this),this.delete=Z.prototype.delete.bind(this),this.get=Z.prototype.get.bind(this),this.has=Z.prototype.has.bind(this),this.set=Z.prototype.set.bind(this),this.tag=ze.tag}toJSON(e,t){if(!t)return super.toJSON(e);const s=new Map;t?.onCreate&&t.onCreate(s);for(const i of this.items){let r,o;if(R(i)?(r=X(i.key,"",t),o=X(i.value,r,t)):r=X(i,"",t),s.has(r))throw new Error("Ordered maps must not include duplicate keys");s.set(r,o)}return s}static from(e,t,s){const i=Zs(e,t,s),r=new this;return r.items=i.items,r}}ze.tag="tag:yaml.org,2002:omap";const _n={collection:"seq",identify:l(n=>n instanceof Map,"identify"),nodeClass:ze,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){const t=Ys(n,e),s=[];for(const{key:i}of t.items)K(i)&&(s.includes(i.value)?e(`Ordered maps must not include duplicate keys: ${i.value}`):s.push(i.value));return Object.assign(new ze,t)},createNode:l((n,e,t)=>ze.from(n,e,t),"createNode")};function Qs({value:n,source:e},t){return e&&(n?Xs:ei).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}l(Qs,"boolStringify");const Xs={identify:l(n=>n===!0,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:l(()=>new _(!0),"resolve"),stringify:Qs},ei={identify:l(n=>n===!1,"identify"),default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:l(()=>new _(!1),"resolve"),stringify:Qs},qo={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:l(n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,"resolve"),stringify:te},Uo={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:l(n=>parseFloat(n.replace(/_/g,"")),"resolve"),stringify(n){const e=Number(n.value);return isFinite(e)?e.toExponential():te(n)}},Jo={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){const e=new _(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){const s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:te},rt=l(n=>typeof n=="bigint"||Number.isInteger(n),"intIdentify");function Pt(n,e,t,{intAsBigInt:s}){const i=n[0];if((i==="-"||i==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}const o=BigInt(n);return i==="-"?BigInt(-1)*o:o}const r=parseInt(n,t);return i==="-"?-1*r:r}l(Pt,"intResolve");function Pn(n,e,t){const{value:s}=n;if(rt(s)){const i=s.toString(e);return s<0?"-"+t+i.substr(1):t+i}return te(n)}l(Pn,"intStringify");const Vo={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:l((n,e,t)=>Pt(n,2,2,t),"resolve"),stringify:l(n=>Pn(n,2,"0b"),"stringify")},Wo={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:l((n,e,t)=>Pt(n,1,8,t),"resolve"),stringify:l(n=>Pn(n,8,"0"),"stringify")},zo={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:l((n,e,t)=>Pt(n,0,10,t),"resolve"),stringify:te},Ho={identify:rt,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:l((n,e,t)=>Pt(n,2,16,t),"resolve"),stringify:l(n=>Pn(n,16,"0x"),"stringify")};class He extends Z{static{l(this,"YAMLSet")}constructor(e){super(e),this.tag=He.tag}add(e){let t;R(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new z(e.key,null):t=new z(e,null),ke(this.items,t.key)||this.items.push(t)}get(e,t){const s=ke(this.items,e);return!t&&R(s)?K(s.key)?s.key.value:s.key:s}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);const s=ke(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new z(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){const{replacer:i}=s,r=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof i=="function"&&(o=i.call(t,o,o)),r.items.push(En(o,null,s));return r}}He.tag="tag:yaml.org,2002:set";const xn={collection:"map",identify:l(n=>n instanceof Set,"identify"),nodeClass:He,default:!1,tag:"tag:yaml.org,2002:set",createNode:l((n,e,t)=>He.from(n,e,t),"createNode"),resolve(n,e){if(Ee(n)){if(n.hasAllNullValues(!0))return Object.assign(new He,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};function jn(n,e){const t=n[0],s=t==="-"||t==="+"?n.substring(1):n,i=l(o=>e?BigInt(o):Number(o),"num"),r=s.replace(/_/g,"").split(":").reduce((o,a)=>o*i(60)+i(a),i(0));return t==="-"?i(-1)*r:r}l(jn,"parseSexagesimal");function ti(n){let{value:e}=n,t=l(o=>o,"num");if(typeof e=="bigint")t=l(o=>BigInt(o),"num");else if(isNaN(e)||!isFinite(e))return te(n);let s="";e<0&&(s="-",e*=t(-1));const i=t(60),r=[e%i];return e<60?r.unshift(0):(e=(e-r[0])/i,r.unshift(e%i),e>=60&&(e=(e-r[0])/i,r.unshift(e))),s+r.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}l(ti,"stringifySexagesimal");const ni={identify:l(n=>typeof n=="bigint"||Number.isInteger(n),"identify"),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:l((n,e,{intAsBigInt:t})=>jn(n,t),"resolve"),stringify:ti},si={identify:l(n=>typeof n=="number","identify"),default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:l(n=>jn(n,!1),"resolve"),stringify:ti},xt={identify:l(n=>n instanceof Date,"identify"),default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){const e=n.match(xt.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");const[,t,s,i,r,o,a]=e.map(Number),c=e[7]?Number((e[7]+"00").substr(1,3)):0;let u=Date.UTC(t,s-1,i,r||0,o||0,a||0,c);const d=e[8];if(d&&d!=="Z"){let f=jn(d,!1);Math.abs(f)<30&&(f*=60),u-=6e4*f}return new Date(u)},stringify:l(({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??"","stringify")},ii=[xe,je,It,Nt,Xs,ei,Vo,Wo,zo,Ho,qo,Uo,Jo,Nn,le,_n,Ln,xn,ni,si,xt],ri=new Map([["core",Mo],["failsafe",[xe,je,It]],["json",Fo],["yaml11",ii],["yaml-1.1",ii]]),oi={binary:Nn,bool:$n,float:Js,floatExp:Us,floatNaN:qs,floatTime:si,int:zs,intHex:Hs,intOct:Ws,intTime:ni,map:xe,merge:le,null:Nt,omap:_n,pairs:Ln,seq:je,set:xn,timestamp:xt},Go={"tag:yaml.org,2002:binary":Nn,"tag:yaml.org,2002:merge":le,"tag:yaml.org,2002:omap":_n,"tag:yaml.org,2002:pairs":Ln,"tag:yaml.org,2002:set":xn,"tag:yaml.org,2002:timestamp":xt};function Kn(n,e,t){const s=ri.get(e);if(s&&!n)return t&&!s.includes(le)?s.concat(le):s.slice();let i=s;if(!i)if(Array.isArray(n))i=[];else{const r=Array.from(ri.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${r} or define customTags array`)}if(Array.isArray(n))for(const r of n)i=i.concat(r);else typeof n=="function"&&(i=n(i.slice()));return t&&(i=i.concat(le)),i.reduce((r,o)=>{const a=typeof o=="string"?oi[o]:o;if(!a){const c=JSON.stringify(o),u=Object.keys(oi).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${c}; use one of ${u}`)}return r.includes(a)||r.push(a),r},[])}l(Kn,"getTags");const Yo=l((n,e)=>n.key<e.key?-1:n.key>e.key?1:0,"sortMapEntriesByKey");class en{static{l(this,"Schema")}constructor({compat:e,customTags:t,merge:s,resolveKnownTags:i,schema:r,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?Kn(e,"compat"):e?Kn(null,e):null,this.name=typeof r=="string"&&r||"core",this.knownTags=i?Go:{},this.tags=Kn(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,he,{value:xe}),Object.defineProperty(this,oe,{value:It}),Object.defineProperty(this,Oe,{value:je}),this.sortMapEntries=typeof o=="function"?o:o===!0?Yo:null}clone(){const e=Object.create(en.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}}function Zo(n,e){const t=[];let s=e.directives===!0;if(e.directives!==!1&&n.directives){const c=n.directives.toString(n);c?(t.push(c),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");const i=Ds(n,e),{commentString:r}=i.options;if(n.commentBefore){t.length!==1&&t.unshift("");const c=r(n.commentBefore);t.unshift(ce(c,""))}let o=!1,a=null;if(n.contents){if(U(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){const d=r(n.contents.commentBefore);t.push(ce(d,""))}i.forceBlockIndent=!!n.comment,a=n.contents.comment}const c=a?void 0:()=>o=!0;let u=Pe(n.contents,i,()=>a=null,c);a&&(u+=Se(u,"",r(a))),(u[0]==="|"||u[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${u}`:t.push(u)}else t.push(Pe(n.contents,i));if(n.directives?.docEnd)if(n.comment){const c=r(n.comment);c.includes(`
|
|
56
|
+
`)?(t.push("..."),t.push(ce(c,""))):t.push(`... ${c}`)}else t.push("...");else{let c=n.comment;c&&o&&(c=c.replace(/^\n+/,"")),c&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(ce(r(c),"")))}return t.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
59
|
-
`),a
|
|
58
|
+
`}l(Zo,"stringifyDocument");class Ge{static{l(this,"Document")}constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Q,{value:kn});let i=null;typeof t=="function"||Array.isArray(t)?i=t:s===void 0&&t&&(s=t,t=void 0);const r=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=r;let{version:o}=r;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new G({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,i,s)}clone(){const e=Object.create(Ge.prototype,{[Q]:{value:kn}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=U(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ke(this.contents)&&this.contents.add(e)}addIn(e,t){Ke(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){const s=Ls(this);e.anchor=!t||s.has(t)?_s(t||"a",s):t}return new wt(e.anchor)}createNode(e,t,s){let i;if(typeof t=="function")e=t.call({"":e},"",e),i=t;else if(Array.isArray(t)){const y=l(b=>typeof b=="number"||b instanceof String||b instanceof Number,"keyToStr"),S=t.filter(y).map(String);S.length>0&&(t=t.concat(S)),i=t}else s===void 0&&t&&(s=t,t=void 0);const{aliasDuplicateObjects:r,anchorPrefix:o,flow:a,keepUndefined:c,onTagObj:u,tag:d}=s??{},{onAnchor:f,setAnchors:h,sourceObjects:m}=To(this,o||"a"),w={aliasDuplicateObjects:r??!0,keepUndefined:c??!1,onAnchor:f,onTagObj:u,replacer:i,schema:this.schema,sourceObjects:m},p=tt(e,d,w);return a&&q(p)&&(p.flow=!0),h(),p}createPair(e,t,s={}){const i=this.createNode(e,null,s),r=this.createNode(t,null,s);return new z(i,r)}delete(e){return Ke(this.contents)?this.contents.delete(e):!1}deleteIn(e){return nt(e)?this.contents==null?!1:(this.contents=null,!0):Ke(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return q(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return nt(e)?!t&&K(this.contents)?this.contents.value:this.contents:q(this.contents)?this.contents.getIn(e,t):void 0}has(e){return q(this.contents)?this.contents.has(e):!1}hasIn(e){return nt(e)?this.contents!==void 0:q(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=St(this.schema,[e],t):Ke(this.contents)&&this.contents.set(e,t)}setIn(e,t){nt(e)?this.contents=t:this.contents==null?this.contents=St(this.schema,Array.from(e),t):Ke(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new G({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new G({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{const i=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${i}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new en(Object.assign(s,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:s,maxAliasCount:i,onAnchor:r,reviver:o}={}){const a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},c=X(this.contents,t??"",a);if(typeof r=="function")for(const{count:u,res:d}of a.anchors.values())r(d,u);return typeof o=="function"?Le(o,{"":c},"",c):c}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){const t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Zo(this,e)}}function Ke(n){if(q(n))return!0;throw new Error("Expected a YAML collection as document contents")}l(Ke,"assertCollection");class Dn extends Error{static{l(this,"YAMLError")}constructor(e,t,s,i){super(),this.name=e,this.code=s,this.message=i,this.pos=t}}class Ce extends Dn{static{l(this,"YAMLParseError")}constructor(e,t,s){super("YAMLParseError",e,t,s)}}class ai extends Dn{static{l(this,"YAMLWarning")}constructor(e,t,s){super("YAMLWarning",e,t,s)}}const jt=l((n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));const{line:s,col:i}=t.linePos[0];t.message+=` at line ${s}, column ${i}`;let r=i-1,o=n.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(r>=60&&o.length>80){const a=Math.min(r-39,o.length-79);o="\u2026"+o.substring(a),r-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(o.substring(0,r))){let a=n.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
|
|
59
|
+
`),o=a+o}if(/[^ ]/.test(o)){let a=1;const c=t.linePos[1];c&&c.line===s&&c.col>i&&(a=Math.max(1,Math.min(c.col-i,80-r)));const u=" ".repeat(r)+"^".repeat(a);t.message+=`:
|
|
60
60
|
|
|
61
|
-
${
|
|
61
|
+
${o}
|
|
62
62
|
${u}
|
|
63
|
-
`}},"prettifyError");function
|
|
64
|
-
`))return!0;if(
|
|
65
|
-
`+p.comment:
|
|
66
|
-
`+C.comment:
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`.repeat(Math.max(1,
|
|
72
|
-
`;for(let p=d;p<
|
|
73
|
-
`):
|
|
74
|
-
`:!
|
|
63
|
+
`}},"prettifyError");function De(n,{flow:e,indicator:t,next:s,offset:i,onError:r,parentIndent:o,startOnNewline:a}){let c=!1,u=a,d=a,f="",h="",m=!1,w=!1,p=null,y=null,S=null,b=null,C=null,A=null,$=null;for(const T of n)switch(w&&(T.type!=="space"&&T.type!=="newline"&&T.type!=="comma"&&r(T.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),w=!1),p&&(u&&T.type!=="comment"&&T.type!=="newline"&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),p=null),T.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&T.source.includes(" ")&&(p=T),d=!0;break;case"comment":{d||r(T,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const J=T.source.substring(1)||" ";f?f+=h+J:f=J,h="",u=!1;break}case"newline":u?f?f+=T.source:(!A||t!=="seq-item-ind")&&(c=!0):h+=T.source,u=!0,m=!0,(y||S)&&(b=T),d=!0;break;case"anchor":y&&r(T,"MULTIPLE_ANCHORS","A node can have at most one anchor"),T.source.endsWith(":")&&r(T.offset+T.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=T,$??($=T.offset),u=!1,d=!1,w=!0;break;case"tag":{S&&r(T,"MULTIPLE_TAGS","A node can have at most one tag"),S=T,$??($=T.offset),u=!1,d=!1,w=!0;break}case t:(y||S)&&r(T,"BAD_PROP_ORDER",`Anchors and tags must be after the ${T.source} indicator`),A&&r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.source} in ${e??"collection"}`),A=T,u=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){C&&r(T,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),C=T,u=!1,d=!1;break}default:r(T,"UNEXPECTED_TOKEN",`Unexpected ${T.type} token`),u=!1,d=!1}const N=n[n.length-1],D=N?N.offset+N.source.length:i;return w&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&r(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),p&&(u&&p.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&r(p,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:C,found:A,spaceBefore:c,comment:f,hasNewline:m,anchor:y,tag:S,newlineAfterProp:b,end:D,start:$??D}}l(De,"resolveProps");function ot(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
|
|
64
|
+
`))return!0;if(n.end){for(const e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(const e of n.items){for(const t of e.start)if(t.type==="newline")return!0;if(e.sep){for(const t of e.sep)if(t.type==="newline")return!0}if(ot(e.key)||ot(e.value))return!0}return!1;default:return!0}}l(ot,"containsNewline");function Mn(n,e,t){if(e?.type==="flow-collection"){const s=e.end[0];s.indent===n&&(s.source==="]"||s.source==="}")&&ot(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}l(Mn,"flowIndentCheck");function ci(n,e,t){const{uniqueKeys:s}=n.options;if(s===!1)return!1;const i=typeof s=="function"?s:(r,o)=>r===o||K(r)&&K(o)&&r.value===o.value;return e.some(r=>i(r.key,t))}l(ci,"mapIncludes");const li="All mapping items must start at the same column";function Qo({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=r?.nodeClass??Z,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let c=s.offset,u=null;for(const d of s.items){const{start:f,key:h,sep:m,value:w}=d,p=De(f,{indicator:"explicit-key-ind",next:h??m?.[0],offset:c,onError:i,parentIndent:s.indent,startOnNewline:!0}),y=!p.found;if(y){if(h&&(h.type==="block-seq"?i(c,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&i(c,"BAD_INDENT",li)),!p.anchor&&!p.tag&&!m){u=p.end,p.comment&&(a.comment?a.comment+=`
|
|
65
|
+
`+p.comment:a.comment=p.comment);continue}(p.newlineAfterProp||ot(h))&&i(h??f[f.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else p.found?.indent!==s.indent&&i(c,"BAD_INDENT",li);t.atKey=!0;const S=p.end,b=h?n(t,h,p,i):e(t,S,f,null,p,i);t.schema.compat&&Mn(s.indent,h,i),t.atKey=!1,ci(t,a.items,b)&&i(S,"DUPLICATE_KEY","Map keys must be unique");const C=De(m??[],{indicator:"map-value-ind",next:w,offset:b.range[2],onError:i,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(c=C.end,C.found){y&&(w?.type==="block-map"&&!C.hasNewline&&i(c,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&p.start<C.found.offset-1024&&i(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));const A=w?n(t,w,C,i):e(t,c,m,null,C,i);t.schema.compat&&Mn(s.indent,w,i),c=A.range[2];const $=new z(b,A);t.options.keepSourceTokens&&($.srcToken=d),a.items.push($)}else{y&&i(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),C.comment&&(b.comment?b.comment+=`
|
|
66
|
+
`+C.comment:b.comment=C.comment);const A=new z(b);t.options.keepSourceTokens&&(A.srcToken=d),a.items.push(A)}}return u&&u<c&&i(u,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,c,u??c],a}l(Qo,"resolveBlockMap");function Xo({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=r?.nodeClass??me,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let c=s.offset,u=null;for(const{start:d,value:f}of s.items){const h=De(d,{indicator:"seq-item-ind",next:f,offset:c,onError:i,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||f)f&&f.type==="block-seq"?i(h.end,"BAD_INDENT","All sequence items must start at the same column"):i(c,"MISSING_CHAR","Sequence item without - indicator");else{u=h.end,h.comment&&(a.comment=h.comment);continue}const m=f?n(t,f,h,i):e(t,h.end,d,null,h,i);t.schema.compat&&Mn(s.indent,f,i),c=m.range[2],a.items.push(m)}return a.range=[s.offset,c,u??c],a}l(Xo,"resolveBlockSeq");function at(n,e,t,s){let i="";if(n){let r=!1,o="";for(const a of n){const{source:c,type:u}=a;switch(u){case"space":r=!0;break;case"comment":{t&&!r&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");const d=c.substring(1)||" ";i?i+=o+d:i=d,o="";break}case"newline":i&&(o+=c),r=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${u} at node end`)}e+=c.length}}return{comment:i,offset:e}}l(at,"resolveEnd");const Rn="Block collections are not allowed within flow collections",Bn=l(n=>n&&(n.type==="block-map"||n.type==="block-seq"),"isBlock");function ea({composeNode:n,composeEmptyNode:e},t,s,i,r){const o=s.start.source==="{",a=o?"flow map":"flow sequence",c=r?.nodeClass??(o?Z:me),u=new c(t.schema);u.flow=!0;const d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let f=s.offset+s.start.source.length;for(let y=0;y<s.items.length;++y){const S=s.items[y],{start:b,key:C,sep:A,value:$}=S,N=De(b,{flow:a,indicator:"explicit-key-ind",next:C??A?.[0],offset:f,onError:i,parentIndent:s.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!A&&!$){y===0&&N.comma?i(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&i(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(u.comment?u.comment+=`
|
|
67
|
+
`+N.comment:u.comment=N.comment),f=N.end;continue}!o&&t.options.strict&&ot(C)&&i(C,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)N.comma&&i(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||i(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(const T of b)switch(T.type){case"comma":case"space":break;case"comment":D=T.source.substring(1);break e;default:break e}if(D){let T=u.items[u.items.length-1];R(T)&&(T=T.value??T.key),T.comment?T.comment+=`
|
|
68
|
+
`+D:T.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!A&&!N.found){const D=$?n(t,$,N,i):e(t,N.end,A,null,N,i);u.items.push(D),f=D.range[2],Bn($)&&i(D.range,"BLOCK_IN_FLOW",Rn)}else{t.atKey=!0;const D=N.end,T=C?n(t,C,N,i):e(t,D,b,null,N,i);Bn(C)&&i(T.range,"BLOCK_IN_FLOW",Rn),t.atKey=!1;const J=De(A??[],{flow:a,indicator:"map-value-ind",next:$,offset:T.range[2],onError:i,parentIndent:s.indent,startOnNewline:!1});if(J.found){if(!o&&!N.found&&t.options.strict){if(A)for(const V of A){if(V===J.found)break;if(V.type==="newline"){i(V,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<J.found.offset-1024&&i(J.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]===":"?i($,"MISSING_CHAR",`Missing space after : in ${a}`):i(J.start,"MISSING_CHAR",`Missing , or : between ${a} items`));const ue=$?n(t,$,J,i):J.found?e(t,J.end,A,null,J,i):null;ue?Bn($)&&i(ue.range,"BLOCK_IN_FLOW",Rn):J.comment&&(T.comment?T.comment+=`
|
|
69
|
+
`+J.comment:T.comment=J.comment);const Ae=new z(T,ue);if(t.options.keepSourceTokens&&(Ae.srcToken=S),o){const V=u;ci(t,V.items,T)&&i(D,"DUPLICATE_KEY","Map keys must be unique"),V.items.push(Ae)}else{const V=new Z(t.schema);V.flow=!0,V.items.push(Ae);const is=(ue??T).range;V.range=[T.range[0],is[1],is[2]],u.items.push(V)}f=ue?ue.range[2]:J.end}}const h=o?"}":"]",[m,...w]=s.end;let p=f;if(m&&m.source===h)p=m.offset+m.source.length;else{const y=a[0].toUpperCase()+a.substring(1),S=d?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;i(f,d?"MISSING_CHAR":"BAD_INDENT",S),m&&m.source.length!==1&&w.unshift(m)}if(w.length>0){const y=at(w,p,t.options.strict,i);y.comment&&(u.comment?u.comment+=`
|
|
70
|
+
`+y.comment:u.comment=y.comment),u.range=[s.offset,p,y.offset]}else u.range=[s.offset,p,p];return u}l(ea,"resolveFlowCollection");function Fn(n,e,t,s,i,r){const o=t.type==="block-map"?Qo(n,e,t,s,r):t.type==="block-seq"?Xo(n,e,t,s,r):ea(n,e,t,s,r),a=o.constructor;return i==="!"||i===a.tagName?(o.tag=a.tagName,o):(i&&(o.tag=i),o)}l(Fn,"resolveCollection");function ta(n,e,t,s,i){const r=s.tag,o=r?e.directives.tagName(r.source,h=>i(r,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){const{anchor:h,newlineAfterProp:m}=s,w=h&&r?h.offset>r.offset?h:r:h??r;w&&(!m||m.offset<w.offset)&&i(w,"MISSING_CHAR","Missing newline after block sequence props")}const a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!r||!o||o==="!"||o===Z.tagName&&a==="map"||o===me.tagName&&a==="seq")return Fn(n,e,t,i,o);let c=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!c){const h=e.schema.knownTags[o];if(h&&h.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),c=h;else return h?i(r,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):i(r,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Fn(n,e,t,i,o)}const u=Fn(n,e,t,i,o,c),d=c.resolve?.(u,h=>i(r,"TAG_RESOLVE_FAILED",h),e.options)??u,f=U(d)?d:new _(d);return f.range=u.range,f.tag=o,c?.format&&(f.format=c.format),f}l(ta,"composeCollection");function ui(n,e,t){const s=e.offset,i=na(e,n.options.strict,t);if(!i)return{value:"",type:null,comment:"",range:[s,s,s]};const r=i.mode===">"?_.BLOCK_FOLDED:_.BLOCK_LITERAL,o=e.source?sa(e.source):[];let a=o.length;for(let p=o.length-1;p>=0;--p){const y=o[p][1];if(y===""||y==="\r")a=p;else break}if(a===0){const p=i.chomp==="+"&&o.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,o.length-1)):"";let y=s+i.length;return e.source&&(y+=e.source.length),{value:p,type:r,comment:i.comment,range:[s,y,y]}}let c=e.indent+i.indent,u=e.offset+i.length,d=0;for(let p=0;p<a;++p){const[y,S]=o[p];if(S===""||S==="\r")i.indent===0&&y.length>c&&(c=y.length);else{y.length<c&&t(u+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),i.indent===0&&(c=y.length),d=p,c===0&&!n.atRoot&&t(u,"BAD_INDENT","Block scalar values in collections must be indented");break}u+=y.length+S.length+1}for(let p=o.length-1;p>=a;--p)o[p][0].length>c&&(a=p+1);let f="",h="",m=!1;for(let p=0;p<d;++p)f+=o[p][0].slice(c)+`
|
|
72
|
+
`;for(let p=d;p<a;++p){let[y,S]=o[p];u+=y.length+S.length+1;const b=S[S.length-1]==="\r";if(b&&(S=S.slice(0,-1)),S&&y.length<c){const A=`Block scalar lines must not be less indented than their ${i.indent?"explicit indentation indicator":"first line"}`;t(u-S.length-(b?2:1),"BAD_INDENT",A),y=""}r===_.BLOCK_LITERAL?(f+=h+y.slice(c)+S,h=`
|
|
73
|
+
`):y.length>c||S[0]===" "?(h===" "?h=`
|
|
74
|
+
`:!m&&h===`
|
|
75
75
|
`&&(h=`
|
|
76
76
|
|
|
77
|
-
`),f+=h+
|
|
78
|
-
`,
|
|
77
|
+
`),f+=h+y.slice(c)+S,h=`
|
|
78
|
+
`,m=!0):S===""?h===`
|
|
79
79
|
`?f+=`
|
|
80
80
|
`:h=`
|
|
81
|
-
`:(f+=h+
|
|
82
|
-
`+
|
|
81
|
+
`:(f+=h+S,h=" ",m=!1)}switch(i.chomp){case"-":break;case"+":for(let p=a;p<o.length;++p)f+=`
|
|
82
|
+
`+o[p][0].slice(c);f[f.length-1]!==`
|
|
83
83
|
`&&(f+=`
|
|
84
84
|
`);break;default:f+=`
|
|
85
|
-
`}const w=
|
|
85
|
+
`}const w=s+i.length+e.source.length;return{value:f,type:r,comment:i.comment,range:[s,w,w]}}l(ui,"resolveBlockScalar");function na({offset:n,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;const{source:i}=e[0],r=i[0];let o=0,a="",c=-1;for(let h=1;h<i.length;++h){const m=i[h];if(!a&&(m==="-"||m==="+"))a=m;else{const w=Number(m);!o&&w?o=w:c===-1&&(c=n+h)}}c!==-1&&s(c,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${i}`);let u=!1,d="",f=i.length;for(let h=1;h<e.length;++h){const m=e[h];switch(m.type){case"space":u=!0;case"newline":f+=m.source.length;break;case"comment":t&&!u&&s(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),f+=m.source.length,d=m.source.substring(1);break;case"error":s(m,"UNEXPECTED_TOKEN",m.message),f+=m.source.length;break;default:{const w=`Unexpected token in block scalar header: ${m.type}`;s(m,"UNEXPECTED_TOKEN",w);const p=m.source;p&&typeof p=="string"&&(f+=p.length)}}}return{mode:r,indent:o,chomp:a,comment:d,length:f}}l(na,"parseBlockScalarHeader");function sa(n){const e=n.split(/\n( *)/),t=e[0],s=t.match(/^( *)/),r=[s?.[1]?[s[1],t.slice(s[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)r.push([e[o],e[o+1]]);return r}l(sa,"splitLines");function fi(n,e,t){const{offset:s,type:i,source:r,end:o}=n;let a,c;const u=l((h,m,w)=>t(s+h,m,w),"_onError");switch(i){case"scalar":a=_.PLAIN,c=ia(r,u);break;case"single-quoted-scalar":a=_.QUOTE_SINGLE,c=ra(r,u);break;case"double-quoted-scalar":a=_.QUOTE_DOUBLE,c=oa(r,u);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${i}`),{value:"",type:null,comment:"",range:[s,s+r.length,s+r.length]}}const d=s+r.length,f=at(o,d,e,t);return{value:c,type:a,comment:f.comment,range:[s,d,f.offset]}}l(fi,"resolveFlowScalar");function ia(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),di(n)}l(ia,"plainValue");function ra(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),di(n.slice(1,-1)).replace(/''/g,"'")}l(ra,"singleQuotedValue");function di(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
|
|
86
86
|
`,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
|
|
87
|
-
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let
|
|
88
|
-
`?r
|
|
89
|
-
`:(r
|
|
90
|
-
`))if(
|
|
91
|
-
`){const{fold:
|
|
92
|
-
`)for(
|
|
93
|
-
`)for(
|
|
94
|
-
`&&!(
|
|
95
|
-
`)&&(t+=
|
|
96
|
-
`||
|
|
97
|
-
`);)
|
|
87
|
+
`,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(n);if(!s)return n;let i=s[1],r=" ",o=e.lastIndex;for(t.lastIndex=o;s=t.exec(n);)s[1]===""?r===`
|
|
88
|
+
`?i+=r:r=`
|
|
89
|
+
`:(i+=r+s[1],r=" "),o=t.lastIndex;const a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(n),i+r+(s?.[1]??"")}l(di,"foldLines");function oa(n,e){let t="";for(let s=1;s<n.length-1;++s){const i=n[s];if(!(i==="\r"&&n[s+1]===`
|
|
90
|
+
`))if(i===`
|
|
91
|
+
`){const{fold:r,offset:o}=aa(n,s);t+=r,s=o}else if(i==="\\"){let r=n[++s];const o=ca[r];if(o)t+=o;else if(r===`
|
|
92
|
+
`)for(r=n[s+1];r===" "||r===" ";)r=n[++s+1];else if(r==="\r"&&n[s+1]===`
|
|
93
|
+
`)for(r=n[++s+1];r===" "||r===" ";)r=n[++s+1];else if(r==="x"||r==="u"||r==="U"){const a={x:2,u:4,U:8}[r];t+=la(n,s+1,a,e),s+=a}else{const a=n.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(i===" "||i===" "){const r=s;let o=n[s+1];for(;o===" "||o===" ";)o=n[++s+1];o!==`
|
|
94
|
+
`&&!(o==="\r"&&n[s+2]===`
|
|
95
|
+
`)&&(t+=s>r?n.slice(r,s+1):i)}else t+=i}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}l(oa,"doubleQuotedValue");function aa(n,e){let t="",s=n[e+1];for(;(s===" "||s===" "||s===`
|
|
96
|
+
`||s==="\r")&&!(s==="\r"&&n[e+2]!==`
|
|
97
|
+
`);)s===`
|
|
98
98
|
`&&(t+=`
|
|
99
|
-
`),e+=1,n
|
|
100
|
-
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function
|
|
99
|
+
`),e+=1,s=n[e+1];return t||(t=" "),{fold:t,offset:e}}l(aa,"foldNewline");const ca={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
|
|
100
|
+
`,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function la(n,e,t,s){const i=n.substr(e,t),o=i.length===t&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;if(isNaN(o)){const a=n.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}l(la,"parseCharCode");function hi(n,e,t,s){const{value:i,type:r,comment:o,range:a}=e.type==="block-scalar"?ui(n,e,s):fi(e,n.options.strict,s),c=t?n.directives.tagName(t.source,f=>s(t,"TAG_RESOLVE_FAILED",f)):null;let u;n.options.stringKeys&&n.atKey?u=n.schema[oe]:c?u=ua(n.schema,i,c,t,s):e.type==="scalar"?u=fa(n,i,e,s):u=n.schema[oe];let d;try{const f=u.resolve(i,h=>s(t??e,"TAG_RESOLVE_FAILED",h),n.options);d=K(f)?f:new _(f)}catch(f){const h=f instanceof Error?f.message:String(f);s(t??e,"TAG_RESOLVE_FAILED",h),d=new _(i)}return d.range=a,d.source=i,r&&(d.type=r),c&&(d.tag=c),u.format&&(d.format=u.format),o&&(d.comment=o),d}l(hi,"composeScalar");function ua(n,e,t,s,i){if(t==="!")return n[oe];const r=[];for(const a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)r.push(a);else return a;for(const a of r)if(a.test?.test(e))return a;const o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[oe])}l(ua,"findScalarTagByName");function fa({atKey:n,directives:e,schema:t},s,i,r){const o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(s))||t[oe];if(t.compat){const a=t.compat.find(c=>c.default&&c.test?.test(s))??t[oe];if(o.tag!==a.tag){const c=e.tagString(o.tag),u=e.tagString(a.tag),d=`Value may be parsed as either ${c} or ${u}`;r(i,"TAG_RESOLVE_FAILED",d,!0)}}return o}l(fa,"findScalarTagByTest");function da(n,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let i=e[s];switch(i.type){case"space":case"comment":case"newline":n-=i.source.length;continue}for(i=e[++s];i?.type==="space";)n+=i.source.length,i=e[++s];break}}return n}l(da,"emptyScalarPosition");const ha={composeNode:pi,composeEmptyNode:qn};function pi(n,e,t,s){const i=n.atKey,{spaceBefore:r,comment:o,anchor:a,tag:c}=t;let u,d=!0;switch(e.type){case"alias":u=pa(n,e,s),(a||c)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":u=hi(n,e,c,s),a&&(u.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":u=ta(ha,n,e,t,s),a&&(u.anchor=a.source.substring(1));break;default:{const f=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",f),u=qn(n,e.offset,void 0,null,t,s),d=!1}}return a&&u.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),i&&n.options.stringKeys&&(!K(u)||typeof u.value!="string"||u.tag&&u.tag!=="tag:yaml.org,2002:str")&&s(c??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),r&&(u.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?u.comment=o:u.commentBefore=o),n.options.keepSourceTokens&&d&&(u.srcToken=e),u}l(pi,"composeNode");function qn(n,e,t,s,{spaceBefore:i,comment:r,anchor:o,tag:a,end:c},u){const d={type:"scalar",offset:da(e,t,s),indent:-1,source:""},f=hi(n,d,a,u);return o&&(f.anchor=o.source.substring(1),f.anchor===""&&u(o,"BAD_ALIAS","Anchor cannot be an empty string")),i&&(f.spaceBefore=!0),r&&(f.comment=r,f.range[2]=c),f}l(qn,"composeEmptyNode");function pa({options:n},{offset:e,source:t,end:s},i){const r=new wt(t.substring(1));r.source===""&&i(e,"BAD_ALIAS","Alias cannot be an empty string"),r.source.endsWith(":")&&i(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);const o=e+t.length,a=at(s,o,n.strict,i);return r.range=[e,o,a.offset],a.comment&&(r.comment=a.comment),r}l(pa,"composeAlias");function ma(n,e,{offset:t,start:s,value:i,end:r},o){const a=Object.assign({_directives:e},n),c=new Ge(void 0,a),u={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},d=De(s,{indicator:"doc-start",next:i??r?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(c.directives.docStart=!0,i&&(i.type==="block-map"||i.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),c.contents=i?pi(u,i,d,o):qn(u,d.end,s,null,d,o);const f=c.contents.range[2],h=at(r,f,!1,o);return h.comment&&(c.comment=h.comment),c.range=[t,f,h.offset],c}l(ma,"composeDoc");function ct(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];const{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}l(ct,"getErrorPos");function mi(n){let e="",t=!1,s=!1;for(let i=0;i<n.length;++i){const r=n[i];switch(r[0]){case"#":e+=(e===""?"":s?`
|
|
101
101
|
|
|
102
102
|
`:`
|
|
103
|
-
`)+(
|
|
104
|
-
${
|
|
105
|
-
${
|
|
106
|
-
${
|
|
107
|
-
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new
|
|
108
|
-
`}];switch(
|
|
109
|
-
`),d=
|
|
110
|
-
`,h=[{type:"block-scalar-header",offset:
|
|
111
|
-
`}),{type:"block-scalar",offset:
|
|
112
|
-
`),
|
|
113
|
-
`;if(
|
|
114
|
-
`});for(const
|
|
115
|
-
`};delete
|
|
103
|
+
`)+(r.substring(1)||" "),t=!0,s=!1;break;case"%":n[i+1]?.[0]!=="#"&&(i+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}l(mi,"parsePrelude");class Un{static{l(this,"Composer")}constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,i,r)=>{const o=ct(t);r?this.warnings.push(new ai(o,s,i)):this.errors.push(new Ce(o,s,i))},this.directives=new G({version:e.version||"1.2"}),this.options=e}decorate(e,t){const{comment:s,afterEmptyLine:i}=mi(this.prelude);if(s){const r=e.contents;if(t)e.comment=e.comment?`${e.comment}
|
|
104
|
+
${s}`:s;else if(i||e.directives.docStart||!r)e.commentBefore=s;else if(q(r)&&!r.flow&&r.items.length>0){let o=r.items[0];R(o)&&(o=o.key);const a=o.commentBefore;o.commentBefore=a?`${s}
|
|
105
|
+
${a}`:s}else{const o=r.commentBefore;r.commentBefore=o?`${s}
|
|
106
|
+
${o}`:s}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mi(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(const i of e)yield*this.next(i);yield*this.end(t,s)}*next(e){switch(e.type){case"directive":this.directives.add(e.source,(t,s,i)=>{const r=ct(e);r[0]+=t,this.onError(r,"BAD_DIRECTIVE",s,i)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{const t=ma(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{const t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,s=new Ce(ct(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){const s="Unexpected doc-end without preceding document";this.errors.push(new Ce(ct(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;const t=at(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){const s=this.doc.comment;this.doc.comment=s?`${s}
|
|
107
|
+
${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Ce(ct(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){const s=Object.assign({_directives:this.directives},this.options),i=new Ge(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),i.range=[0,t,t],this.decorate(i,!1),yield i}}}function ya(n,e=!0,t){if(n){const s=l((i,r,o)=>{const a=typeof i=="number"?i:Array.isArray(i)?i[0]:i.offset;if(t)t(a,r,o);else throw new Ce([a,a+1],r,o)},"_onError");switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return fi(n,e,s);case"block-scalar":return ui({options:{strict:e}},n,s)}}return null}l(ya,"resolveAsScalar");function ga(n,e){const{implicitKey:t=!1,indent:s,inFlow:i=!1,offset:r=-1,type:o="PLAIN"}=e,a=it({type:o,value:n},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=e.end??[{type:"newline",offset:-1,indent:s,source:`
|
|
108
|
+
`}];switch(a[0]){case"|":case">":{const u=a.indexOf(`
|
|
109
|
+
`),d=a.substring(0,u),f=a.substring(u+1)+`
|
|
110
|
+
`,h=[{type:"block-scalar-header",offset:r,indent:s,source:d}];return yi(h,c)||h.push({type:"newline",offset:-1,indent:s,source:`
|
|
111
|
+
`}),{type:"block-scalar",offset:r,indent:s,props:h,source:f}}case'"':return{type:"double-quoted-scalar",offset:r,indent:s,source:a,end:c};case"'":return{type:"single-quoted-scalar",offset:r,indent:s,source:a,end:c};default:return{type:"scalar",offset:r,indent:s,source:a,end:c}}}l(ga,"createScalarToken");function wa(n,e,t={}){let{afterKey:s=!1,implicitKey:i=!1,inFlow:r=!1,type:o}=t,a="indent"in n?n.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{const u=n.props[0];if(u.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=u.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}const c=it({type:o,value:e},{implicitKey:i||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case"|":case">":ba(n,c);break;case'"':Jn(n,c,"double-quoted-scalar");break;case"'":Jn(n,c,"single-quoted-scalar");break;default:Jn(n,c,"scalar")}}l(wa,"setScalarValue");function ba(n,e){const t=e.indexOf(`
|
|
112
|
+
`),s=e.substring(0,t),i=e.substring(t+1)+`
|
|
113
|
+
`;if(n.type==="block-scalar"){const r=n.props[0];if(r.type!=="block-scalar-header")throw new Error("Invalid block scalar header");r.source=s,n.source=i}else{const{offset:r}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:r,indent:o,source:s}];yi(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
|
|
114
|
+
`});for(const c of Object.keys(n))c!=="type"&&c!=="offset"&&delete n[c];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:i})}}l(ba,"setBlockScalarValue");function yi(n,e){if(e)for(const t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}l(yi,"addEndtoBlockProps");function Jn(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{const s=n.props.slice(1);let i=e.length;n.props[0].type==="block-scalar-header"&&(i-=n.props[0].source.length);for(const r of s)r.offset+=i;delete n.props,Object.assign(n,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{const i={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
|
|
115
|
+
`};delete n.items,Object.assign(n,{type:t,source:e,end:[i]});break}default:{const s="indent"in n?n.indent:-1,i="end"in n&&Array.isArray(n.end)?n.end.filter(r=>r.type==="space"||r.type==="comment"||r.type==="newline"):[];for(const r of Object.keys(n))r!=="type"&&r!=="offset"&&delete n[r];Object.assign(n,{type:t,indent:s,source:e,end:i})}}}l(Jn,"setFlowScalarValue");const Sa=l(n=>"type"in n?Kt(n):Dt(n),"stringify$1");function Kt(n){switch(n.type){case"block-scalar":{let e="";for(const t of n.props)e+=Kt(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(const t of n.items)e+=Dt(t);return e}case"flow-collection":{let e=n.start.source;for(const t of n.items)e+=Dt(t);for(const t of n.end)e+=t.source;return e}case"document":{let e=Dt(n);if(n.end)for(const t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(const t of n.end)e+=t.source;return e}}}l(Kt,"stringifyToken");function Dt({start:n,key:e,sep:t,value:s}){let i="";for(const r of n)i+=r.source;if(e&&(i+=Kt(e)),t)for(const r of t)i+=r.source;return s&&(i+=Kt(s)),i}l(Dt,"stringifyItem");const Vn=Symbol("break visit"),ka=Symbol("skip children"),gi=Symbol("remove item");function ve(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),wi(Object.freeze([]),n,e)}l(ve,"visit"),ve.BREAK=Vn,ve.SKIP=ka,ve.REMOVE=gi,ve.itemAtPath=(n,e)=>{let t=n;for(const[s,i]of e){const r=t?.[s];if(r&&"items"in r)t=r.items[i];else return}return t},ve.parentCollection=(n,e)=>{const t=ve.itemAtPath(n,e.slice(0,-1)),s=e[e.length-1][0],i=t?.[s];if(i&&"items"in i)return i;throw new Error("Parent collection not found")};function wi(n,e,t){let s=t(e,n);if(typeof s=="symbol")return s;for(const i of["key","value"]){const r=e[i];if(r&&"items"in r){for(let o=0;o<r.items.length;++o){const a=wi(Object.freeze(n.concat([[i,o]])),r.items[o],t);if(typeof a=="number")o=a-1;else{if(a===Vn)return Vn;a===gi&&(r.items.splice(o,1),o-=1)}}typeof s=="function"&&i==="key"&&(s=s(e,n))}}return typeof s=="function"?s(e,n):s}l(wi,"_visit");const Mt="\uFEFF",Rt="",Bt="",lt="",Ca=l(n=>!!n&&"items"in n,"isCollection"),va=l(n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar"),"isScalar");function Aa(n){switch(n){case Mt:return"<BOM>";case Rt:return"<DOC>";case Bt:return"<FLOW_END>";case lt:return"<SCALAR>";default:return JSON.stringify(n)}}l(Aa,"prettyToken");function bi(n){switch(n){case Mt:return"byte-order-mark";case Rt:return"doc-mode";case Bt:return"flow-error-end";case lt:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
116
116
|
`:case`\r
|
|
117
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(
|
|
118
|
-
`:case"\r":case" ":return!0;default:return!1}}
|
|
119
|
-
\r `),
|
|
117
|
+
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}l(bi,"tokenType");var Ta=Object.freeze({__proto__:null,BOM:Mt,DOCUMENT:Rt,FLOW_END:Bt,SCALAR:lt,createScalarToken:ga,isCollection:Ca,isScalar:va,prettyToken:Aa,resolveAsScalar:ya,setScalarValue:wa,stringify:Sa,tokenType:bi,visit:ve});function ne(n){switch(n){case void 0:case" ":case`
|
|
118
|
+
`:case"\r":case" ":return!0;default:return!1}}l(ne,"isEmpty");const Si=new Set("0123456789ABCDEFabcdef"),Oa=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Ft=new Set(",[]{}"),Ea=new Set(` ,[]{}
|
|
119
|
+
\r `),Wn=l(n=>!n||Ea.has(n),"isNotAnchorChar");class ki{static{l(this,"Lexer")}constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let s=this.next??"stream";for(;s&&(t||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
|
|
120
120
|
`?!0:t==="\r"?this.buffer[e+1]===`
|
|
121
|
-
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let
|
|
122
|
-
`||!
|
|
123
|
-
`||
|
|
124
|
-
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===
|
|
125
|
-
`,this.pos);if(
|
|
126
|
-
`,
|
|
127
|
-
`:e=
|
|
128
|
-
`)break}default:break e}if(!
|
|
129
|
-
`,
|
|
130
|
-
`;)
|
|
131
|
-
`&&
|
|
132
|
-
`?(
|
|
133
|
-
`,
|
|
134
|
-
`){const
|
|
121
|
+
`:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){const i=this.buffer[s+e+1];if(i===`
|
|
122
|
+
`||!i&&!this.atEnd)return e+s+1}return t===`
|
|
123
|
+
`||s>=this.indentNext||!t&&!this.atEnd?e+s:-1}if(t==="-"||t==="."){const s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&ne(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
|
|
124
|
+
`,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Mt&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){const r=e[s-1];if(r===" "||r===" "){t=s-1;break}else s=e.indexOf("#",s+1)}for(;;){const r=e[t-1];if(r===" "||r===" ")t-=1;else break}const i=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-i),this.pushNewline(),"stream"}if(this.atLineEnd()){const t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Rt,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==="...")&&ne(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&&!ne(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===":")&&ne(t)){const s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);const e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Wn),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);const i=this.getLine();if(i===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&i[0]!=="#"||s===0&&(i.startsWith("---")||i.startsWith("..."))&&ne(i[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(i[0]==="]"||i[0]==="}")))return this.flowLevel=0,yield Bt,yield*this.parseLineStart();let r=0;for(;i[r]===",";)r+=yield*this.pushCount(1),r+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(r+=yield*this.pushIndicators(),i[r]){case void 0:return"flow";case"#":return yield*this.pushCount(i.length-r),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Wn),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{const o=this.charAt(1);if(this.flowKey||ne(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){const e=this.charAt(0);let t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let r=0;for(;this.buffer[t-1-r]==="\\";)r+=1;if(r%2===0)break;t=this.buffer.indexOf('"',t+1)}const s=this.buffer.substring(0,t);let i=s.indexOf(`
|
|
125
|
+
`,this.pos);if(i!==-1){for(;i!==-1;){const r=this.continueScalar(i+1);if(r===-1)break;i=s.indexOf(`
|
|
126
|
+
`,r)}i!==-1&&(t=i-(s[i-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){const t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>ne(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let r=this.pos;s=this.buffer[r];++r)switch(s){case" ":t+=1;break;case`
|
|
127
|
+
`:e=r,t=0;break;case"\r":{const o=this.buffer[r+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
|
|
128
|
+
`)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{const r=this.continueScalar(e+1);if(r===-1)break;e=this.buffer.indexOf(`
|
|
129
|
+
`,r)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let i=e+1;for(s=this.buffer[i];s===" ";)s=this.buffer[++i];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
|
|
130
|
+
`;)s=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let r=e-1,o=this.buffer[r];o==="\r"&&(o=this.buffer[--r]);const a=r;for(;o===" ";)o=this.buffer[--r];if(o===`
|
|
131
|
+
`&&r>=this.pos&&r+1+t>a)e=r;else break}while(!0);return yield lt,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){const e=this.flowLevel>0;let t=this.pos-1,s=this.pos-1,i;for(;i=this.buffer[++s];)if(i===":"){const r=this.buffer[s+1];if(ne(r)||e&&Ft.has(r))break;t=s}else if(ne(i)){let r=this.buffer[s+1];if(i==="\r"&&(r===`
|
|
132
|
+
`?(s+=1,i=`
|
|
133
|
+
`,r=this.buffer[s+1]):t=s),r==="#"||e&&Ft.has(r))break;if(i===`
|
|
134
|
+
`){const o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&Ft.has(i))break;t=s}return!i&&!this.atEnd?this.setNext("plain-scalar"):(yield lt,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){const s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(Wn))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{const e=this.flowLevel>0,t=this.charAt(1);if(ne(t)||e&&Ft.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(;!ne(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(Oa.has(t))t=this.buffer[++e];else if(t==="%"&&Si.has(this.buffer[e+1])&&Si.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){const e=this.buffer[this.pos];return e===`
|
|
135
135
|
`?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
|
|
136
|
-
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,
|
|
136
|
+
`?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");const i=t-this.pos;return i>0&&(yield this.buffer.substr(this.pos,i),this.pos=t),i}*pushUntil(e){let t=this.pos,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}class Ci{static{l(this,"LineCounter")}constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,s=this.lineStarts.length;for(;t<s;){const r=t+s>>1;this.lineStarts[r]<e?t=r+1:s=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};const i=this.lineStarts[t-1];return{line:t,col:e-i+1}}}}function ye(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}l(ye,"includesToken");function vi(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}l(vi,"findNonEmptyIndex");function Ai(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}l(Ai,"isFlowToken");function qt(n){switch(n.type){case"document":return n.start;case"block-map":{const e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}l(qt,"getPrevProps");function Me(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}l(Me,"getFirstKeyStartProps");function Ti(n){if(n.start.type==="flow-seq-start")for(const e of n.items)e.sep&&!e.value&&!ye(e.start,"explicit-key-ind")&&!ye(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Ai(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}l(Ti,"fixFlowSeqItems");class zn{static{l(this,"Parser")}constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new ki,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(const s of this.lexer.lex(e,t))yield*this.next(s);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}const t=bi(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{const s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){const e=this.peek(1);if(this.type==="doc-end"&&(!e||e.type!=="doc-end")){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){const t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{const s=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in s?s.indent:0:t.type==="flow-collection"&&s.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Ti(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{const i=s.items[s.items.length-1];if(i.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(i.sep)i.value=t;else{Object.assign(i,{key:t,sep:[]}),this.onKeyLine=!i.explicitKey;return}break}case"block-seq":{const i=s.items[s.items.length-1];i.value?s.items.push({start:[],value:t}):i.value=t;break}case"flow-collection":{const i=s.items[s.items.length-1];!i||i.value?s.items.push({start:[],key:t,sep:[]}):i.sep?i.value=t:Object.assign(i,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){const i=t.items[t.items.length-1];i&&!i.sep&&!i.value&&i.start.length>0&&vi(i.start)===-1&&(t.indent===0||i.start.every(r=>r.type!=="comment"||r.indent<t.indent))&&(s.type==="document"?s.end=i.start:s.items.push({start:i.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{const e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{vi(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}const t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){const t=qt(this.peek(2)),s=Me(t);let i;e.end?(i=e.end,i.push(this.sourceToken),delete e.end):i=[this.sourceToken];const r={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:i}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
|
|
137
137
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
138
|
-
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const
|
|
138
|
+
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){const s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){const s=!this.onKeyLine&&this.indent===e.indent,i=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind";let r=[];if(i&&t.sep&&!t.value){const o=[];for(let a=0;a<t.sep.length;++a){const c=t.sep[a];switch(c.type){case"newline":o.push(a);break;case"space":break;case"comment":c.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(r=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":i||t.value?(r.push(this.sourceToken),e.items.push({start:r}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):i||t.value?(r.push(this.sourceToken),e.items.push({start:r,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(ye(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]});else if(Ai(t.key)&&!ye(t.sep,"newline")){const o=Me(t.start),a=t.key,c=t.sep;c.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:c}]})}else r.length>0?t.sep=t.sep.concat(r,this.sourceToken):t.sep.push(this.sourceToken);else if(ye(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{const o=Me(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||i?e.items.push({start:r,key:null,sep:[this.sourceToken]}):ye(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const o=this.flowScalar(this.type);i||t.value?(e.items.push({start:r,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{const o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!ye(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:r});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){const t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){const s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){const i=e.items[e.items.length-2]?.value?.end;if(Array.isArray(i)){Array.prototype.push.apply(i,t.start),i.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||ye(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){const s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){const t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s&&s.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{const i=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:i,sep:[]}):t.sep?this.stack.push(i):Object.assign(t,{key:i,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}const s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{const s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){const i=qt(s),r=Me(i);Ti(e);const o=e.end.splice(1,e.end.length);o.push(this.sourceToken);const a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:r,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
139
139
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
140
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=gn(e),n=rt(t);return n.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=gn(e),n=rt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:n,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(n=>n.type==="newline"||n.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function _i(s){const e=s.prettyErrors!==!1;return{lineCounter:s.lineCounter||e&&new wi||null,prettyErrors:e}}c(_i,"parseOptions");function Fc(s,e={}){const{lineCounter:t,prettyErrors:n}=_i(e),r=new _s(t?.addNewLine),i=new ws(e),a=Array.from(i.compose(r.parse(s)));if(n&&t)for(const o of a)o.errors.forEach(un(s,t)),o.warnings.forEach(un(s,t));return a.length>0?a:Object.assign([],{empty:!0},i.streamInfo())}c(Fc,"parseAllDocuments");function Si(s,e={}){const{lineCounter:t,prettyErrors:n}=_i(e),r=new _s(t?.addNewLine),i=new ws(e);let a=null;for(const o of i.compose(r.parse(s),!0,s.length))if(!a)a=o;else if(a.options.logLevel!=="silent"){a.errors.push(new Ke(o.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return n&&t&&(a.errors.forEach(un(s,t)),a.warnings.forEach(un(s,t))),a}c(Si,"parseDocument");function qc(s,e,t){let n;typeof e=="function"?n=e:t===void 0&&e&&typeof e=="object"&&(t=e);const r=Si(s,t);if(!r)return null;if(r.warnings.forEach(i=>jr(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(qc,"parse");function Uc(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 je(s)&&!n?s.toString(t):new mt(s,n,t).toString(t)}c(Uc,"stringify");var Vc=Object.freeze({__proto__:null,Alias:Jt,CST:Kc,Composer:ws,Document:mt,Lexer:gi,LineCounter:wi,Pair:ee,Parser:_s,Scalar:P,Schema:Nn,YAMLError:fs,YAMLMap:re,YAMLParseError:Ke,YAMLSeq:xe,YAMLWarning:si,isAlias:Ee,isCollection:W,isDocument:je,isMap:ze,isNode:G,isPair:z,isScalar:V,isSeq:We,parse:qc,parseAllDocuments:Fc,parseDocument:Si,stringify:Uc,visit:Pe,visitAsync:Zt});const Zc="membrane",Jc=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function zc(s){return we.join(s,Zc)}c(zc,"getMembraneDir");const Wc={ignored:Jc,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Gc extends Oa{static{c(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=zc(e.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(gt.existsSync(this.membraneDir)||gt.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=Ta.watch(this.membraneDir,Wc),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("deleted",e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.emit("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const n=we.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(n);const o={filePath:t,relativePath:n,data:void 0};this.emit(e,o);return}const r=this.readFileContent(t);if(!this.hasContentChanged(n,r,e))return;const a=this.processFileEvent(t,r);this.updateCache(n,r),this.emit(e,a)}readFileContent(e){return gt.readFileSync(e,"utf8")}processFileEvent(e,t){const n=we.relative(this.membraneDir,e);let r;try{r=t?Vc.parse(t):void 0}catch{r=void 0}return{filePath:e,relativePath:n,data:r}}hasContentChanged(e,t,n){if(n==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const r=this.getContentHash(t);return this.contentCache[e]!==r}getContentHash(e){return Ca.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]})}}var K={},wn={},Ci;function Oi(){if(Ci)return wn;Ci=1,Object.defineProperty(wn,"__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"),wn.default=s,wn}c(Oi,"requireJsCamelcase");var bn={},Ti;function Ai(){if(Ti)return bn;Ti=1,Object.defineProperty(bn,"__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"),bn.default=s,bn}c(Ai,"requireJsSnakecase");var vn={},Ei;function xi(){if(Ei)return vn;Ei=1,Object.defineProperty(vn,"__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"),vn.default=s,vn}c(xi,"requireJsPascalcase");var kn={},Ni;function Hc(){if(Ni)return kn;Ni=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-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return c(s,"toDotCase"),kn.default=s,kn}c(Hc,"requireJsDotcase");var _n={},$i;function Yc(){if($i)return _n;$i=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():""}return c(s,"toPathCase"),_n.default=s,_n}c(Yc,"requireJsPathcase");var Sn={},Ii;function Qc(){if(Ii)return Sn;Ii=1,Object.defineProperty(Sn,"__esModule",{value:!0});function s(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,r){return n+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return c(s,"toTextCase"),Sn.default=s,Sn}c(Qc,"requireJsTextcase");var Cn={},Li;function Xc(){if(Li)return Cn;Li=1,Object.defineProperty(Cn,"__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"),Cn.default=s,Cn}c(Xc,"requireJsSentencecase");var On={},ji;function el(){if(ji)return On;ji=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().replace(/( ?)(\w+)( ?)/g,function(t,n,r,i){return n+r.charAt(0).toUpperCase()+r.slice(1)+i}):""}return c(s,"toHeaderCase"),On.default=s,On}c(el,"requireJsHeadercase");var Tn={},Pi;function Ri(){if(Pi)return Tn;Pi=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,"toKebabCase"),Tn.default=s,Tn}c(Ri,"requireJsKebabcase");var it={},Ss={},Di;function at(){return Di||(Di=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})}}(Ss)),Ss}c(at,"requireUtils");var Ki;function tl(){if(Ki)return it;Ki=1;var s=it&&it.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var a=Array(n),o=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,o++)a[o]=l[u];return a};Object.defineProperty(it,"__esModule",{value:!0});var e=at();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(a){var o=n[a],l=a.toLowerCase();r.recursive&&(e.isValidObject(o)?e.belongToTypes(o,r.keepTypesOnRecursion)||(o=t(o,r)):r.recursiveInArray&&e.isArrayObject(o)&&(o=s(o).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]=o}),i}return c(t,"lowerKeys"),it.default=t,it}c(tl,"requireLowercaseKeysObject");var ot={},Mi;function nl(){if(Mi)return ot;Mi=1;var s=ot&&ot.__spreadArrays||function(){for(var n=0,r=0,i=arguments.length;r<i;r++)n+=arguments[r].length;for(var a=Array(n),o=0,r=0;r<i;r++)for(var l=arguments[r],u=0,d=l.length;u<d;u++,o++)a[o]=l[u];return a};Object.defineProperty(ot,"__esModule",{value:!0});var e=at();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(a){var o=n[a],l=a.toUpperCase();r.recursive&&(e.isValidObject(o)?e.belongToTypes(o,r.keepTypesOnRecursion)||(o=t(o,r)):r.recursiveInArray&&e.isArrayObject(o)&&(o=s(o).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]=o}),i}return c(t,"upperKeys"),ot.default=t,ot}c(nl,"requireUppercaseKeysObject");var ct={},Bi;function sl(){if(Bi)return ct;Bi=1;var s=ct&&ct.__spreadArrays||function(){for(var r=0,i=0,a=arguments.length;i<a;i++)r+=arguments[i].length;for(var o=Array(r),l=0,i=0;i<a;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)o[l]=u[d];return o};Object.defineProperty(ct,"__esModule",{value:!0});var e=at(),t=Oi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var a={};return Object.keys(r).forEach(function(o){var l=r[o],u=t.default(o);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}))),a[u]=l}),a}return c(n,"camelKeys"),ct.default=n,ct}c(sl,"requireCamelcaseKeysObject");var lt={},Fi;function rl(){if(Fi)return lt;Fi=1;var s=lt&<.__spreadArrays||function(){for(var r=0,i=0,a=arguments.length;i<a;i++)r+=arguments[i].length;for(var o=Array(r),l=0,i=0;i<a;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)o[l]=u[d];return o};Object.defineProperty(lt,"__esModule",{value:!0});var e=at(),t=Ai();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var a={};return Object.keys(r).forEach(function(o){var l=r[o],u=t.default(o);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}))),a[u]=l}),a}return c(n,"snakeKeys"),lt.default=n,lt}c(rl,"requireSnakecaseKeysObject");var ut={},qi;function il(){if(qi)return ut;qi=1;var s=ut&&ut.__spreadArrays||function(){for(var r=0,i=0,a=arguments.length;i<a;i++)r+=arguments[i].length;for(var o=Array(r),l=0,i=0;i<a;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)o[l]=u[d];return o};Object.defineProperty(ut,"__esModule",{value:!0});var e=at(),t=xi();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var a={};return Object.keys(r).forEach(function(o){var l=r[o],u=t.default(o);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}))),a[u]=l}),a}return c(n,"pascalKeys"),ut.default=n,ut}c(il,"requirePascalcaseKeysObject");var dt={},Ui;function al(){if(Ui)return dt;Ui=1;var s=dt&&dt.__spreadArrays||function(){for(var r=0,i=0,a=arguments.length;i<a;i++)r+=arguments[i].length;for(var o=Array(r),l=0,i=0;i<a;i++)for(var u=arguments[i],d=0,f=u.length;d<f;d++,l++)o[l]=u[d];return o};Object.defineProperty(dt,"__esModule",{value:!0});var e=at(),t=Ri();function n(r,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(r))return null;i=e.validateOptions(i);var a={};return Object.keys(r).forEach(function(o){var l=r[o],u=t.default(o);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}))),a[u]=l}),a}return c(n,"kebabKeys"),dt.default=n,dt}c(al,"requireKebabcaseKeysObject");var Vi;function ol(){if(Vi)return K;Vi=1,Object.defineProperty(K,"__esModule",{value:!0}),K.kebabKeys=K.pascalKeys=K.snakeKeys=K.camelKeys=K.upperKeys=K.lowerKeys=K.toLowerCase=K.toUpperCase=K.toKebabCase=K.toHeaderCase=K.toSentenceCase=K.toTextCase=K.toPathCase=K.toDotCase=K.toPascalCase=K.toSnakeCase=K.toCamelCase=void 0;var s=Oi();K.toCamelCase=s.default;var e=Ai();K.toSnakeCase=e.default;var t=xi();K.toPascalCase=t.default;var n=Hc();K.toDotCase=n.default;var r=Yc();K.toPathCase=r.default;var i=Qc();K.toTextCase=i.default;var a=Xc();K.toSentenceCase=a.default;var o=el();K.toHeaderCase=o.default;var l=Ri();K.toKebabCase=l.default;var u=tl();K.lowerKeys=u.default;var d=nl();K.upperKeys=d.default;var f=sl();K.camelKeys=f.default;var h=rl();K.snakeKeys=h.default;var y=il();K.pascalKeys=y.default;var w=al();K.kebabKeys=w.default;var p=c(function(_){return String(_||"").toLowerCase()},"toLowerCase");K.toLowerCase=p;var m=c(function(_){return String(_||"").toUpperCase()},"toUpperCase");K.toUpperCase=m;var b={toCamelCase:s.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:n.default,toPathCase:r.default,toTextCase:i.default,toSentenceCase:a.default,toHeaderCase:o.default,toKebabCase:l.default,toUpperCase:m,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:y.default,kebabKeys:w.default};return K.default=b,K}c(ol,"requireLib");var Cs,Zi;function cl(){return Zi||(Zi=1,Cs=ol()),Cs}c(cl,"requireJsConvertCase");var ft=cl();const $t={[$.Integration]:{element:"integration",elements:"integrations",exportable:!1},[$.Connector]:{element:"connector",elements:"connectors",exportable:!1},[$.Action]:{element:"action",elements:"actions",integrationSpecific:!0},[$.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[$.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[$.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[$.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[$.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0},[$.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0},[$.Customer]:{element:"customer",elements:"customers"},[$.FlowInstance]:{element:"flowInstance",elements:"flowInstances"},[$.FlowRun]:{element:"flowRun",elements:"flowRuns"},[$.Scenario]:{element:"scenario",elements:"scenarios"},[$.ActionInstance]:{element:"actionInstance",elements:"actionInstances"},[$.Connection]:{element:"connection",elements:"connections"},[$.FieldMappingInstance]:{element:"fieldMappingInstance",elements:"fieldMappingInstances"},[$.DataSourceInstance]:{element:"dataSourceInstance",elements:"dataSourceInstances"},[$.DataLinkTableInstance]:{element:"dataLinkTableInstance",elements:"dataLinkTableInstances"},[$.AppEventSubscription]:{element:"appEventSubscription",elements:"appEventSubscriptions"},[$.AppDataSchemaInstance]:{element:"appDataSchemaInstance",elements:"appDataSchemaInstances"},[$.ExternalEventSubscription]:{element:"externalEventSubscription",elements:"externalEventSubscriptions"},[$.ExternalEventLogRecord]:{element:"externalEventLogRecord",elements:"externalEventLogRecords"},[$.ExternalEventPull]:{element:"externalEventPull",elements:"externalEventPulls"},[$.DataCollection]:{element:"dataCollection",elements:"dataCollections"},[$.Screen]:{element:"screen",elements:"screens"},[$.ActionRunLogRecord]:{element:"actionRunLogRecord",elements:"actionRunLogRecords"}};class ll{static{c(this,"WorkspaceElementService")}constructor(e){this.fileWatcher=e,this.setupEventHandlers()}client;workspaceDataCache={};cacheExpirationTime=5*60*1e3;lastCacheUpdate=0;async init(){this.client=await wr.getClient(this.fileWatcher.getCwd())}setupEventHandlers(){this.fileWatcher.on("added",e=>this.processElementChange(e,"added")),this.fileWatcher.on("changed",e=>this.processElementChange(e,"changed")),this.fileWatcher.on("deleted",e=>this.processElementChange(e,"deleted"))}async processElementChange(e,t){try{const n=pr(e.relativePath);if(!n||!n.key||!n.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${n.key} of type ${n.type}`),t){case"added":case"changed":await this.pushElement(n.type,{...e.data,key:n.key});break;case"deleted":break}}catch(n){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,n)}}async pushElement(e,t){if(!$t[e])throw new Error(`Unknown element type: ${e}`);const r={...t},i=await this.getWorkspaceData();delete r.integrationId;const a=this.matchElement(r,e,i);a?await this.handleExistingElement(e,r,a):await this.handleNewElement(e,r,i)}async handleExistingElement(e,t,n){const r=$t[e],i=ft.toCamelCase(he[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await this.client[i](n.id).put(t),console.debug(`Updated ${t.integrationKey||"universal"} ${r.element} ${t.key}`);else if(this.hasParent(t))try{await this.client[i](n.id).reset(),console.debug(`Customization reset ${t.integrationKey||"universal"} ${r.element} ${t.key}`)}catch(a){throw console.debug("Error resetting element:",n,t),a}else console.warn(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${r.element} ${t.key}`)}async handleNewElement(e,t,n){const r=$t[e],i=ft.toCamelCase(he[e].name),a=ft.toCamelCase(he[e].namePlural);if(this.hasParent(t)){try{await this.client[i]({key:t.key}).apply([t.integrationKey])}catch{try{await this.client[i]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey,n);await this.client[a].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await this.client[i]({key:t.key,integrationKey:t.integrationKey}).put(t),console.debug(`Applied & Customized ${t.integrationKey||"universal"} ${r.element} ${t.key}`)}catch(o){throw console.debug("Error customizing element:",t),o}else console.debug(`Applied universal ${r.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const o=this.findIntegrationId(t.integrationKey,n);t.integrationId=o}await this.client[a].create(t),console.debug(`Created ${t.integrationKey||"universal"} ${r.element} ${t.key}`)}catch(o){throw console.debug(`Error creating element ${e}`,this.hasParent(t),t.integrationKey,t),o}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}matchElement(e,t,n){const r=n[t]?.filter(i=>i.key===e.key&&i.integrationKey===e.integrationKey&&!i.archivedAt);if(!(!r||r.length===0)){if(r.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return r[0]}}findIntegrationId(e,t){const n=t.integration?.find(r=>r.key===e);if(!n)throw new Error(`Integration with key ${e} not found`);return n.id}async getWorkspaceData(){const e=Date.now();if(this.lastCacheUpdate&&e-this.lastCacheUpdate<this.cacheExpirationTime)return this.workspaceDataCache;console.debug("Refreshing workspace data cache");const t={};try{const n=await this.client.integrations.findAll();t.integration=n.map(r=>({id:r.id,key:r.key,name:r.name}));for(const r of Object.keys($t)){const i=$t[r];if(i.exportable!==!1)try{const a=[],o=await this.client[i.elements].findAll();if(a.push(...o),i.integrationSpecific)for(const l of n)try{const u=await this.client[i.elements].findAll({integrationId:l.id});a.push(...u.map(d=>({...d,integrationKey:l.key})))}catch(u){console.error(`Failed to fetch ${r} for integration ${l.key}:`,u)}t[r]=a}catch(a){console.error(`Failed to fetch ${r} elements:`,a),t[r]=[]}}return this.workspaceDataCache=t,this.lastCacheUpdate=e,console.debug("Workspace data cache refreshed successfully"),t}catch(n){return console.error("Failed to refresh workspace data cache:",n),Object.keys(this.workspaceDataCache).length>0?(console.debug("Using existing workspace data cache due to refresh failure"),this.workspaceDataCache):{integration:[]}}}}const ul={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},dl={info:v.blue,success:v.green,warning:v.yellow,error:v.red,debug:v.gray};class N{static{c(this,"Logger")}static formatMessage(e,t,n={}){const r=n.timestamp?`${v.gray(new Date().toISOString())} `:"",i=n.prefix?`${v.gray(n.prefix)} `:"",a=n.suffix?` ${v.gray(n.suffix)}`:"",o=ul[t],l=dl[t];return`${r}${o} ${i}${l(e)}${a}`}static info(e,t){let n=v.blue;if(t?.color&&(n=v[t.color.toLowerCase()]||v.blue),t?.timestamp){const r=new Date().toLocaleTimeString();console.debug(`${v.gray(`[${r}]`)} ${n(e)}`)}else console.debug(n(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(v.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
141
|
-
${
|
|
142
|
-
${
|
|
143
|
-
`)).action(async()=>{try{N.header("Opening Workspace in Browser"),N.info("Loading configuration...");const e=Le();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");N.info("Retrieving workspace ID...");const n=`https://console.integration.app/w/${await br(process.cwd())}`;N.info(`Opening ${n}...`);const{default:r}=await import("open");await r(n),N.success("Browser opened successfully")}catch(e){e instanceof Error&&(N.error(e.message),process.exit(1)),N.error("An unknown error occurred"),process.exit(1)}})}c(yl,"setupOpenCommand");const le={[$.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:c(s=>({id:s.id,key:s.key,name:s.name,connectorId:s.connectorId,baseUri:s.baseUri,connectorVersion:s.connectorVersion}),"exportCleanup")},[$.Connector]:{element:"connector",elements:"connectors",exportable:!1},[$.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:c(s=>(delete s.integration,s),"exportCleanup")},[$.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[$.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[$.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[$.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[$.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,exportCleanup:c(s=>(delete s.dataSourceId,s),"exportCleanup")},[$.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0}};function gl(s){return delete s.workspaceId,delete s.createdAt,delete s.updatedAt,delete s.revision,delete s.parentRevision,Object.keys(s).map(e=>{e.match(/universal.*Revision/g)&&delete s[e]}),s}c(gl,"baseExportCleanup");async function Gi(s,e="full"){const t={};N.info("Getting remote workspace data");const n=await s.integrations.findAll();t.integration=n.map(r=>Os("integration",r));for(const r of Object.keys(le)){const i=le[r];if(i.exportable===!1)continue;const a=[];N.info(`Reading ${i.elements} from remote workspace`);const o=await s[i.elements].findAll();if(a.push(...o.map(l=>Os(r,l))),i.integrationSpecific)for(const l of n){const u=await s[i.elements].findAll({integrationId:l.id});a.push(...u.map(d=>(d.integrationKey=l.key,Os(r,d))))}a.length>0&&e=="full"&&(console.table(a.map(l=>({key:l.key,integrationKey:l.integrationKey,universal:!l.integrationKey})).reduce((l,u)=>(l||(l={}),l[u.key]||(l[u.key]={}),u.universal&&(l[u.key].universal=!0),u.integrationKey&&(l[u.key].integration?l[u.key].integration+=` ${u.integrationKey}`:l[u.key].integration=u.integrationKey),l),{})),console.groupEnd()),t[r]=a}return N.success("Remote workspace data retrieved successfully"),t}c(Gi,"getWorkspaceData");function wl(s){const e={},t={};for(const n of Object.keys(s))if(e[n]=[],t[n]=[],le[n]?.integrationSpecific)for(const i of s[n])i.integrationKey||i.integration||i.integrationId?t[n].push(i):e[n].push(i);else e[n].push(...s[n]);return{universalElements:e,integrationSpecificElements:t}}c(wl,"splitWorkspaceData");function Os(s,e){return e=gl(e),le[s].exportCleanup?le[s].exportCleanup(e):e}c(Os,"cleanUpForExport");function It(s){return Object.keys(s).some(e=>/universal.*Id/g.test(e)||/parentId/g.test(e))}c(It,"hasParent");function X(s,e){console.debug("\x1B[0m",`\x1B[${{Reset:"\x1B[0m",Bright:"\x1B[1m",Dim:"\x1B[2m",Underscore:"\x1B[4m",Blink:"\x1B[5m",Reverse:"\x1B[7m",Hidden:"\x1B[8m",Black:"\x1B[30m",Red:"\x1B[31m",Green:"\x1B[32m",Yellow:"\x1B[33m",Blue:"\x1B[34m",Magenta:"\x1B[35m",Cyan:"\x1B[36m",White:"\x1B[37m",Gray:"\x1B[90m",BgBlack:"\x1B[40m",BgRed:"\x1B[41m",BgGreen:"\x1B[42m",BgYellow:"\x1B[43m",BgBlue:"\x1B[44m",BgMagenta:"\x1B[45m",BgCyan:"\x1B[46m",BgWhite:"\x1B[47m",BgGray:"\x1B[100m"}[e]}`,s,"\x1B[0m")}c(X,"coloredLog");function Lt(s){return he[s].apiPath}c(Lt,"getWorkspaceElementTypePath");function Hi(s,e){for(const t of Object.keys(e))s[t]=[...s[t]||[],...e[t]];return s}c(Hi,"mergeWorkspaceData");const Yi=[$.Integration,$.Scenario,$.Action,$.Flow,$.AppDataSchema,$.AppEventType,$.DataLinkTable,$.DataSource,$.FieldMapping],bl="membrane",vl="membrane.config.yml";function jt(){const s=process.cwd(),e=we.join(s,bl),t=we.join(s,vl),n=e,r=we.join(n,"workspace.yaml");return{membraneDirPath:e,configPath:t,payloadDirPath:n,workspaceDataFilePath:r}}c(jt,"getPaths");const Qi="connectors",Xi="development",Ts={};async function kl({client:s,basePath:e,allConnectors:t=!1}){const n=await s.integrations.findAll(),r=new Set,i={};for(const a of n){const o=a.connectorId,l=a.connectorVersion;if(!i[o]?.has(a.connectorVersion)){const u=await Al({client:s,connectorId:o});(!!u.workspaceId||t)&&(r.has(o)||(await El({basePath:e,connector:u}),r.add(o)),i[o]||(i[o]=new Set),i[o].has(l)||(await xl({client:s,connector:u,connectorVersion:l,basePath:e}),i[o].add(l)))}}}c(kl,"pullConnectors");async function _l({client:s,workspaceData:e,pushContext:t,workspaceId:n}){const r={};console.debug("[Push] Loading custom connectors");const i=s,a=await i.get(`/connectors?workspaceId=${n}`);console.debug("[Push] Loading public connectors"),e.connector=a;const o=As(),l=R.existsSync(o)?R.readdirSync(o):[];for(const u of l){console.debug(`[Push] Loading connector from: ${u}`);const d=R.readdirSync(B.join(o,u)),f=await Sl(u);if(delete f.baseUri,f.uuid&&e.connector?.find(y=>y.uuid==f.uuid))r[f.id]=e.connector.find(y=>y.uuid==f.uuid).id,X(`Matched ${f.name} uuid: ${f.uuid}`,"Blue");else if(!r[f.id]){console.debug(`Creating connector ${f.name} (${f.key})`);const y=await i.post("connectors",{...f,workspaceId:n});r[f.id]=y.id}const h=d.filter(y=>R.statSync(B.join(o,u,y)).isDirectory());for(const y of h)await Tl({client:s,connector:f,version:y,connectorId:r[f.id]})}t.connectorsMapping=r}c(_l,"pushConnectors");function As(){const s=jt();return B.join(s.membraneDirPath,Qi)}c(As,"getConnectorsPath");async function Sl(s){return fe.load(R.readFileSync(B.join(As(),s,`${s}.yml`),"utf8"))}c(Sl,"readConnector");async function Cl(s,e){return console.debug(`Zipping ${s} into ${e}`),new Promise((t,n)=>{const r=R.createWriteStream(e),i=xa("zip",{zlib:{level:9}});r.on("close",()=>{X(`Successfully created ${e}`,"Green"),t()}),r.on("end",()=>{console.debug("Data has been drained")}),i.on("warning",o=>{o.code==="ENOENT"?console.warn(o):n(o)}),i.on("error",o=>{n(o)}),i.pipe(r);const a=R.readdirSync(s);for(const o of a){const l=B.join(s,o),u=R.statSync(l);u.isFile()?i.file(l,{name:o}):u.isDirectory()&&i.directory(l,o)}i.finalize()})}c(Cl,"createZipArchive");async function Ol(s,e){return console.debug(`Unzipping into ${e}`),new Promise((t,n)=>{const r=$a.Parse();r.on("entry",i=>{const a=i.path;if(i.type==="Directory"){const l=B.join(e,a);R.mkdirSync(l,{recursive:!0}),i.autodrain()}else{const l=B.join(e,a),u=B.dirname(l);R.mkdirSync(u,{recursive:!0});const d=R.createWriteStream(l);i.pipe(d),d.on("finish",()=>{console.debug(`Extracted: ${a}`)})}}),r.on("end",()=>{X(`Successfully extracted to ${e}`,"Green"),t()}),r.on("error",i=>{n(i)}),r.write(s),r.end()})}c(Ol,"extractZipArchive");async function Tl({client:s,connector:e,version:t,connectorId:n}){const r=B.join(As(),An(e),ea(t)),i=B.join(r,"src");if(!R.existsSync(i)){console.debug(`No src directory found for ${e.name} version ${t}`);return}const a=B.join(r,"src.zip");try{await Cl(i,a);const o=new Na;if(o.append("file",R.createReadStream(a),"file.zip"),console.debug(`Pushing connector version ${t} for ${e.name}`),t==Xi)console.debug(`Uploading connector ${n}`),await s.post(`connectors/${n}/upload`,o,{headers:{...o.getHeaders()}});else{if(o.append("version",t),o.append("changelog","Imported Version"),(await s.get(`/connectors/${n}/versions`)).find(u=>u.version==t)){X(`Version ${t} already published`,"Blue");return}console.debug(`Publishing version ${t} of connector ${n}`),await s.post(`connectors/${n}/publish-version`,o,{headers:{...o.getHeaders()}})}X(`Successfully pushed connector version ${t} for ${e.name}`,"Green")}finally{R.existsSync(a)&&R.unlinkSync(a)}}c(Tl,"pushConnectorVersion");async function Al({client:s,connectorId:e}){if(Ts[e])return Ts[e];const t=await s.get(`connectors/${e}`);return Ts[e]=t,t}c(Al,"getConnector");async function El({basePath:s,connector:e}){const t=An(e),n=B.join(s,Qi,t);R.mkdirSync(n,{recursive:!0});const r=B.join(n,`${An(e)}.yml`);R.writeFileSync(r,fe.dump(e)),X(`Pulled connector ${e.name}`,"Green")}c(El,"pullConnector");async function xl({client:s,connector:e,connectorVersion:t,basePath:n}){const r=An(e),i=ea(t),a=B.join(n,"connectors",r,i),o=await s.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});R.mkdirSync(a,{recursive:!0});const l=B.join(a,"src.zip");R.writeFileSync(l,o);const u=B.join(a,"src");R.existsSync(u)&&await Ol(o,u),N.info(`[Pull] Connector Version: ${e.name} (${i})`)}c(xl,"pullConnectorVersion");function An(s){return s.key}c(An,"getConnectorDirName");function ea(s){return s??Xi}c(ea,"getConnectorVersionDirName");async function Nl(s){const{outputPath:e,allConnectors:t,client:n}=s;await kl({client:n,basePath:e,allConnectors:t});const r=await Gi(n);for(const i of Object.keys(r))if(r[i].length>0){try{R.readdirSync(e)}catch{R.mkdirSync(e,{recursive:!0})}const a=Lt(i);for(const o of r[i]){try{R.readdirSync(B.join(e,a,`${o.key}`))}catch{R.mkdirSync(B.join(e,a,`${o.key}`),{recursive:!0})}if(o.integration||o.integrationKey){const l=o.integration?o.integration.key:o.integrationKey;try{R.readdirSync(B.join(e,a,`${o.key}`,`${l}`))}catch{R.mkdirSync(B.join(e,a,`${o.key}`,`${l}`),{recursive:!0})}R.writeFileSync(B.join(e,a,`${o.key}`,`${l}`,`${l}.yaml`),fe.dump(o))}else R.writeFileSync(B.join(e,a,o.key,`${o.key}.yaml`),fe.dump(o))}}X(`Data written to ${e} successfully.`,"BgGreen")}c(Nl,"pullWorkspace");const $l="default";async function Il(s,e){const t={iss:s,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Bt.sign(t,e)}c(Il,"generateAccessToken$1");function Ll(s){s.command("pull").description("Pull workspace data from specified workspace").option("-w, --workspace <workspace>","Workspace to pull from",$l).option("-a, --all-connectors","Include store connectors in export",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull -w prod # Pull from prod workspace"," membrane pull -w dev # Pull from dev workspace"," membrane pull -a # Pull with all connectors"," membrane pull -w dev -a # Pull from dev workspace with all connectors",""].join(`
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
${
|
|
140
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;const t=qt(e),s=Me(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}}function Oi(n){const e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new Ci||null,prettyErrors:e}}l(Oi,"parseOptions");function $a(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e),o=Array.from(r.compose(i.parse(n)));if(s&&t)for(const a of o)a.errors.forEach(jt(n,t)),a.warnings.forEach(jt(n,t));return o.length>0?o:Object.assign([],{empty:!0},r.streamInfo())}l($a,"parseAllDocuments");function Ei(n,e={}){const{lineCounter:t,prettyErrors:s}=Oi(e),i=new zn(t?.addNewLine),r=new Un(e);let o=null;for(const a of r.compose(i.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new Ce(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(jt(n,t)),o.warnings.forEach(jt(n,t))),o}l(Ei,"parseDocument");function Ia(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);const i=Ei(n,t);if(!i)return null;if(i.warnings.forEach(r=>Ms(i.options.logLevel,r)),i.errors.length>0){if(i.options.logLevel!=="silent")throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:s},t))}l(Ia,"parse");function Na(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){const i=Math.round(t);t=i<1?void 0:i>8?{indent:8}:{indent:i}}if(n===void 0){const{keepUndefined:i}=t??e??{};if(!i)return}return we(n)&&!s?n.toString(t):new Ge(n,s,t).toString(t)}l(Na,"stringify");var La=Object.freeze({__proto__:null,Alias:wt,CST:Ta,Composer:Un,Document:Ge,Lexer:ki,LineCounter:Ci,Pair:z,Parser:zn,Scalar:_,Schema:en,YAMLError:Dn,YAMLMap:Z,YAMLParseError:Ce,YAMLSeq:me,YAMLWarning:ai,isAlias:pe,isCollection:q,isDocument:we,isMap:Ee,isNode:U,isPair:R,isScalar:K,isSeq:$e,parse:Ia,parseAllDocuments:$a,parseDocument:Ei,stringify:Na,visit:be,visitAsync:gt});const _a="membrane",Pa=["**/node_modules/**","**/.git/**","**/.DS_Store","**/Thumbs.db","**/*.tmp","**/*.swp","**/*.swo","**/*.log","**/*.lock","**/dist/**","**/build/**","**/.cache/**","**/.next/**","**/.vscode/**","**/.idea/**"];function xa(n){return H.join(n,_a)}l(xa,"getMembraneDir");const ja={ignored:Pa,persistent:!0,ignoreInitial:!0,followSymlinks:!1,depth:10,awaitWriteFinish:{stabilityThreshold:500,pollInterval:100},ignorePermissionErrors:!0,atomic:!0,usePolling:!1,alwaysStat:!1,interval:1e3,binaryInterval:300};class Ka extends xr{static{l(this,"FileWatcher")}constructor(e){super(),this.options=e,this.membraneDir=xa(e.cwd)}isWatching=!1;watcher;membraneDir;contentCache={};async start(){this.isWatching||(M.existsSync(this.membraneDir)||M.mkdirSync(this.membraneDir,{recursive:!0}),this.watcher=jr.watch(this.membraneDir,ja),this.watcher.on("add",e=>this.handleFileSystemEvent("added",e)).on("change",e=>this.handleFileSystemEvent("changed",e)).on("unlink",e=>this.handleFileSystemEvent("deleted",e)).on("ready",()=>this.isWatching=!0))}async stop(){!this.isWatching||!this.watcher||(await this.watcher.close(),this.isWatching=!1,this.watcher=void 0,this.clearCache(),this.emit("stopped"))}getCwd(){return this.options.cwd}handleFileSystemEvent(e,t){const s=H.relative(this.membraneDir,t);if(e==="deleted"){this.removeFromCache(s);const a={filePath:t,relativePath:s,data:void 0};this.emit(e,a);return}const i=this.readFileContent(t);if(!this.hasContentChanged(s,i,e))return;const o=this.processFileEvent(t,i);this.updateCache(s,i),this.emit(e,o)}readFileContent(e){return M.readFileSync(e,"utf8")}processFileEvent(e,t){const s=H.relative(this.membraneDir,e);let i;try{i=t?La.parse(t):void 0}catch{i=void 0}return{filePath:e,relativePath:s,data:i}}hasContentChanged(e,t,s){if(s==="added")return!0;if(!t)return this.contentCache[e]!==void 0;const i=this.getContentHash(t);return this.contentCache[e]!==i}getContentHash(e){return Ar.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]})}}var x={},Ut={},$i;function Ii(){if($i)return Ut;$i=1,Object.defineProperty(Ut,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toCamelCase"),Ut.default=n,Ut}l(Ii,"requireJsCamelcase");var Jt={},Ni;function Li(){if(Ni)return Jt;Ni=1,Object.defineProperty(Jt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}return l(n,"toSnakeCase"),Jt.default=n,Jt}l(Li,"requireJsSnakecase");var Vt={},_i;function Pi(){if(_i)return Vt;_i=1,Object.defineProperty(Vt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"$"+i}).toLowerCase().replace(/(\$)(\w?)/g,function(t,s,i){return i.toUpperCase()}):""}return l(n,"toPascalCase"),Vt.default=n,Vt}l(Pi,"requireJsPascalcase");var Wt={},xi;function Da(){if(xi)return Wt;xi=1,Object.defineProperty(Wt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}return l(n,"toDotCase"),Wt.default=n,Wt}l(Da,"requireJsDotcase");var zt={},ji;function Ma(){if(ji)return zt;ji=1,Object.defineProperty(zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}return l(n,"toPathCase"),zt.default=n,zt}l(Ma,"requireJsPathcase");var Ht={},Ki;function Ra(){if(Ki)return Ht;Ki=1,Object.defineProperty(Ht,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}return l(n,"toTextCase"),Ht.default=n,Ht}l(Ra,"requireJsTextcase");var Gt={},Di;function Ba(){if(Di)return Gt;Di=1,Object.defineProperty(Gt,"__esModule",{value:!0});function n(e){if(e===void 0&&(e=""),!e)return"";var t=String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(s,i,r){return i+"_"+r.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}return l(n,"toSentenceCase"),Gt.default=n,Gt}l(Ba,"requireJsSentencecase");var Yt={},Mi;function Fa(){if(Mi)return Yt;Mi=1,Object.defineProperty(Yt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(t,s,i,r){return s+i.charAt(0).toUpperCase()+i.slice(1)+r}):""}return l(n,"toHeaderCase"),Yt.default=n,Yt}l(Fa,"requireJsHeadercase");var Zt={},Ri;function Bi(){if(Ri)return Zt;Ri=1,Object.defineProperty(Zt,"__esModule",{value:!0});function n(e){return e===void 0&&(e=""),e?String(e).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,s,i){return s+"_"+i.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}return l(n,"toKebabCase"),Zt.default=n,Zt}l(Bi,"requireJsKebabcase");var Re={},Hn={},Fi;function Be(){return Fi||(Fi=1,function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.belongToTypes=n.isValidObject=n.isArrayObject=n.validateOptions=n.DefaultOption=void 0,n.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},n.validateOptions=function(e){return e===void 0&&(e=n.DefaultOption),e.recursive==null?e=n.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},n.isArrayObject=function(e){return e!=null&&Array.isArray(e)},n.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},n.belongToTypes=function(e,t){return(t||[]).some(function(s){return e instanceof s})}}(Hn)),Hn}l(Be,"requireUtils");var qi;function qa(){if(qi)return Re;qi=1;var n=Re&&Re.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Re,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toLowerCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"lowerKeys"),Re.default=t,Re}l(qa,"requireLowercaseKeysObject");var Fe={},Ui;function Ua(){if(Ui)return Fe;Ui=1;var n=Fe&&Fe.__spreadArrays||function(){for(var s=0,i=0,r=arguments.length;i<r;i++)s+=arguments[i].length;for(var o=Array(s),a=0,i=0;i<r;i++)for(var c=arguments[i],u=0,d=c.length;u<d;u++,a++)o[a]=c[u];return o};Object.defineProperty(Fe,"__esModule",{value:!0});var e=Be();function t(s,i){if(i===void 0&&(i=e.DefaultOption),!e.isValidObject(s))return null;i=e.validateOptions(i);var r={};return Object.keys(s).forEach(function(o){var a=s[o],c=o.toUpperCase();i.recursive&&(e.isValidObject(a)?e.belongToTypes(a,i.keepTypesOnRecursion)||(a=t(a,i)):i.recursiveInArray&&e.isArrayObject(a)&&(a=n(a).map(function(u){var d=u;if(e.isValidObject(u))e.belongToTypes(d,i.keepTypesOnRecursion)||(d=t(u,i));else if(e.isArrayObject(u)){var f=t({key:u},i);d=f.key}return d}))),r[c]=a}),r}return l(t,"upperKeys"),Fe.default=t,Fe}l(Ua,"requireUppercaseKeysObject");var qe={},Ji;function Ja(){if(Ji)return qe;Ji=1;var n=qe&&qe.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(qe,"__esModule",{value:!0});var e=Be(),t=Ii();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"camelKeys"),qe.default=s,qe}l(Ja,"requireCamelcaseKeysObject");var Ue={},Vi;function Va(){if(Vi)return Ue;Vi=1;var n=Ue&&Ue.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ue,"__esModule",{value:!0});var e=Be(),t=Li();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"snakeKeys"),Ue.default=s,Ue}l(Va,"requireSnakecaseKeysObject");var Je={},Wi;function Wa(){if(Wi)return Je;Wi=1;var n=Je&&Je.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Je,"__esModule",{value:!0});var e=Be(),t=Pi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"pascalKeys"),Je.default=s,Je}l(Wa,"requirePascalcaseKeysObject");var Ve={},zi;function za(){if(zi)return Ve;zi=1;var n=Ve&&Ve.__spreadArrays||function(){for(var i=0,r=0,o=arguments.length;r<o;r++)i+=arguments[r].length;for(var a=Array(i),c=0,r=0;r<o;r++)for(var u=arguments[r],d=0,f=u.length;d<f;d++,c++)a[c]=u[d];return a};Object.defineProperty(Ve,"__esModule",{value:!0});var e=Be(),t=Bi();function s(i,r){if(r===void 0&&(r=e.DefaultOption),!e.isValidObject(i))return null;r=e.validateOptions(r);var o={};return Object.keys(i).forEach(function(a){var c=i[a],u=t.default(a);r.recursive&&(e.isValidObject(c)?e.belongToTypes(c,r.keepTypesOnRecursion)||(c=s(c,r)):r.recursiveInArray&&e.isArrayObject(c)&&(c=n(c).map(function(d){var f=d;if(e.isValidObject(d))e.belongToTypes(f,r.keepTypesOnRecursion)||(f=s(d,r));else if(e.isArrayObject(d)){var h=s({key:d},r);f=h.key}return f}))),o[u]=c}),o}return l(s,"kebabKeys"),Ve.default=s,Ve}l(za,"requireKebabcaseKeysObject");var Hi;function Ha(){if(Hi)return x;Hi=1,Object.defineProperty(x,"__esModule",{value:!0}),x.kebabKeys=x.pascalKeys=x.snakeKeys=x.camelKeys=x.upperKeys=x.lowerKeys=x.toLowerCase=x.toUpperCase=x.toKebabCase=x.toHeaderCase=x.toSentenceCase=x.toTextCase=x.toPathCase=x.toDotCase=x.toPascalCase=x.toSnakeCase=x.toCamelCase=void 0;var n=Ii();x.toCamelCase=n.default;var e=Li();x.toSnakeCase=e.default;var t=Pi();x.toPascalCase=t.default;var s=Da();x.toDotCase=s.default;var i=Ma();x.toPathCase=i.default;var r=Ra();x.toTextCase=r.default;var o=Ba();x.toSentenceCase=o.default;var a=Fa();x.toHeaderCase=a.default;var c=Bi();x.toKebabCase=c.default;var u=qa();x.lowerKeys=u.default;var d=Ua();x.upperKeys=d.default;var f=Ja();x.camelKeys=f.default;var h=Va();x.snakeKeys=h.default;var m=Wa();x.pascalKeys=m.default;var w=za();x.kebabKeys=w.default;var p=l(function(b){return String(b||"").toLowerCase()},"toLowerCase");x.toLowerCase=p;var y=l(function(b){return String(b||"").toUpperCase()},"toUpperCase");x.toUpperCase=y;var S={toCamelCase:n.default,toSnakeCase:e.default,toPascalCase:t.default,toDotCase:s.default,toPathCase:i.default,toTextCase:r.default,toSentenceCase:o.default,toHeaderCase:a.default,toKebabCase:c.default,toUpperCase:y,toLowerCase:p,lowerKeys:u.default,upperKeys:d.default,camelKeys:f.default,snakeKeys:h.default,pascalKeys:m.default,kebabKeys:w.default};return x.default=S,x}l(Ha,"requireLib");var Gn,Gi;function Ga(){return Gi||(Gi=1,Gn=Ha()),Gn}l(Ga,"requireJsConvertCase");var We=Ga();const ut={[I.Integration]:{element:"integration",elements:"integrations",exportable:!1},[I.Connector]:{element:"connector",elements:"connectors",exportable:!1},[I.Action]:{element:"action",elements:"actions",integrationSpecific:!0},[I.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[I.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[I.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[I.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[I.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0},[I.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0},[I.Customer]:{element:"customer",elements:"customers"},[I.FlowInstance]:{element:"flowInstance",elements:"flowInstances"},[I.FlowRun]:{element:"flowRun",elements:"flowRuns"},[I.Scenario]:{element:"scenario",elements:"scenarios"},[I.ActionInstance]:{element:"actionInstance",elements:"actionInstances"},[I.Connection]:{element:"connection",elements:"connections"},[I.FieldMappingInstance]:{element:"fieldMappingInstance",elements:"fieldMappingInstances"},[I.DataSourceInstance]:{element:"dataSourceInstance",elements:"dataSourceInstances"},[I.DataLinkTableInstance]:{element:"dataLinkTableInstance",elements:"dataLinkTableInstances"},[I.AppEventSubscription]:{element:"appEventSubscription",elements:"appEventSubscriptions"},[I.AppDataSchemaInstance]:{element:"appDataSchemaInstance",elements:"appDataSchemaInstances"},[I.ExternalEventSubscription]:{element:"externalEventSubscription",elements:"externalEventSubscriptions"},[I.ExternalEventLogRecord]:{element:"externalEventLogRecord",elements:"externalEventLogRecords"},[I.ExternalEventPull]:{element:"externalEventPull",elements:"externalEventPulls"},[I.DataCollection]:{element:"dataCollection",elements:"dataCollections"},[I.Screen]:{element:"screen",elements:"screens"},[I.ActionRunLogRecord]:{element:"actionRunLogRecord",elements:"actionRunLogRecords"}};class Ya{static{l(this,"WorkspaceElementService")}constructor(e){this.fileWatcher=e,this.setupEventHandlers()}client;workspaceDataCache={};cacheExpirationTime=5*60*1e3;lastCacheUpdate=0;async init(){this.client=await Cs.getClient(this.fileWatcher.getCwd())}setupEventHandlers(){this.fileWatcher.on("added",e=>this.processElementChange(e,"added")),this.fileWatcher.on("changed",e=>this.processElementChange(e,"changed")),this.fileWatcher.on("deleted",e=>this.processElementChange(e,"deleted"))}async processElementChange(e,t){try{const s=ws(e.relativePath);if(!s||!s.key||!s.type){console.debug(`Skipping file change - could not extract element reference from: ${e.relativePath}`);return}switch(console.debug(`Processing ${t} element: ${s.key} of type ${s.type}`),t){case"added":case"changed":await this.pushElement(s.type,{...e.data,key:s.key});break;case"deleted":break}}catch(s){console.error(`Failed to process event ${t} for element ${e.relativePath}:`,s)}}async pushElement(e,t){if(!ut[e])throw new Error(`Unknown element type: ${e}`);const i={...t},r=await this.getWorkspaceData();delete i.integrationId;const o=this.matchElement(i,e,r);o?await this.handleExistingElement(e,i,o):await this.handleNewElement(e,i,r)}async handleExistingElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name);if(!this.hasParent(t)||this.elementIsCustomized(t)&&this.hasParent(t))await this.client[r](s.id).put(t),console.debug(`Updated ${t.integrationKey||"universal"} ${i.element} ${t.key}`);else if(this.hasParent(t))try{await this.client[r](s.id).reset(),console.debug(`Customization reset ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(o){throw console.debug("Error resetting element:",s,t),o}else console.warn(`Corrupted element detected. Manual migration required: ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}async handleNewElement(e,t,s){const i=ut[e],r=We.toCamelCase(ie[e].name),o=We.toCamelCase(ie[e].namePlural);if(this.hasParent(t)){try{await this.client[r]({key:t.key}).apply([t.integrationKey])}catch{try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t)}catch{const u=this.findIntegrationId(t.integrationKey,s);await this.client[o].create({...t,integrationId:u})}}if(this.elementIsCustomized(t))try{await this.client[r]({key:t.key,integrationKey:t.integrationKey}).put(t),console.debug(`Applied & Customized ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug("Error customizing element:",t),a}else console.debug(`Applied universal ${i.element} ${t.key} to ${t.integrationKey}`)}else try{if(t.integrationKey){delete t.integration;const a=this.findIntegrationId(t.integrationKey,s);t.integrationId=a}await this.client[o].create(t),console.debug(`Created ${t.integrationKey||"universal"} ${i.element} ${t.key}`)}catch(a){throw console.debug(`Error creating element ${e}`,this.hasParent(t),t.integrationKey,t),a}}hasParent(e){return Object.keys(e).some(t=>/universal.*Id/g.test(t)||/parentId/g.test(t))}elementIsCustomized(e){return!!(e.integrationKey&&(e.customized||e.isCustomized))}matchElement(e,t,s){const i=s[t]?.filter(r=>r.key===e.key&&r.integrationKey===e.integrationKey&&!r.archivedAt);if(!(!i||i.length===0)){if(i.length>1)throw new Error(`More than one ${e.integrationKey||"universal"} ${t} with key ${e.key} found in the workspace`);return i[0]}}findIntegrationId(e,t){const s=t.integration?.find(i=>i.key===e);if(!s)throw new Error(`Integration with key ${e} not found`);return s.id}async getWorkspaceData(){const e=Date.now();if(this.lastCacheUpdate&&e-this.lastCacheUpdate<this.cacheExpirationTime)return this.workspaceDataCache;console.debug("Refreshing workspace data cache");const t={};try{const s=await this.client.integrations.findAll();t.integration=s.map(i=>({id:i.id,key:i.key,name:i.name}));for(const i of Object.keys(ut)){const r=ut[i];if(r.exportable!==!1)try{const o=[],a=await this.client[r.elements].findAll();if(o.push(...a),r.integrationSpecific)for(const c of s)try{const u=await this.client[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>({...d,integrationKey:c.key})))}catch(u){console.error(`Failed to fetch ${i} for integration ${c.key}:`,u)}t[i]=o}catch(o){console.error(`Failed to fetch ${i} elements:`,o),t[i]=[]}}return this.workspaceDataCache=t,this.lastCacheUpdate=e,console.debug("Workspace data cache refreshed successfully"),t}catch(s){return console.error("Failed to refresh workspace data cache:",s),Object.keys(this.workspaceDataCache).length>0?(console.debug("Using existing workspace data cache due to refresh failure"),this.workspaceDataCache):{integration:[]}}}}const Za={info:"\u{1F4DD}",success:"\u2728",warning:"\u26A0\uFE0F",error:"\u274C",debug:"\u{1F50D}"},Qa={info:k.blue,success:k.green,warning:k.yellow,error:k.red,debug:k.gray};class E{static{l(this,"Logger")}static formatMessage(e,t,s={}){const i=s.timestamp?`${k.gray(new Date().toISOString())} `:"",r=s.prefix?`${k.gray(s.prefix)} `:"",o=s.suffix?` ${k.gray(s.suffix)}`:"",a=Za[t],c=Qa[t];return`${i}${a} ${r}${c(e)}${o}`}static info(e,t){let s=k.blue;if(t?.color&&(s=k[t.color.toLowerCase()]||k.blue),t?.timestamp){const i=new Date().toLocaleTimeString();console.debug(`${k.gray(`[${i}]`)} ${s(e)}`)}else console.debug(s(e))}static group(e,t){}static groupEnd(){}static newLine(){}static success(e,t){console.debug(this.formatMessage(e,"success",t))}static warning(e,t){console.debug(this.formatMessage(e,"warning",t))}static error(e,t){console.error(this.formatMessage(e,"error",t))}static debug(e,t){t?.prefix?console.debug(k.gray(`[${t.prefix}] ${e}`),t.error?`
|
|
141
|
+
${k.red(t.error)}`:""):console.debug(k.gray(e),t?.error?`
|
|
142
|
+
${k.red(t.error)}`:"")}static step(e,t){}static header(e){console.debug(),console.debug(k.bold.cyan(`\u25B6 ${e}`)),console.debug()}static table(e,t){if(e.length===0)return;const s=t||Object.keys(e[0]),i=e.map(r=>{const o={};return s.forEach(a=>{o[a]=r[a]}),o});console.table(i,s)}static divider(){}}const Yi=Sr(process.argv.slice(2)),Zi=Yi.cwd?mr(Yi.cwd):process.cwd();async function Xa(){try{await ec.init()}catch(n){E.error(n.toString()),process.exit(1)}}l(Xa,"startBackgroundServices");const Qi=new Ka({cwd:Zi}),ec=new Ya(Qi),tc=l(()=>g(Gr,{cwd:Zi,children:g(po,{fileWatcher:Qi,children:g(Qr,{children:g(kr,{value:{fetcher:ro()},children:g(Co,{})})})})}),"App");function nc(){Xa(),br(g(tc,{}))}l(nc,"runAgent");async function sc(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Ye.sign(t,e)}l(sc,"generateAdminAccessToken");async function ic(n,e){return(await ln.get(`${n}/docs-json`,{headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"}})).data}l(ic,"fetchOpenApiSchema");function Xi(n,e=!0){if(!n)return e?F.string():F.string().optional();let t;switch(n.type){case"integer":t=F.coerce.number().int();break;case"number":t=F.coerce.number();break;case"boolean":t=F.coerce.boolean();break;case"string":default:t=F.string();break}return n.format==="uuid"?t=F.string().uuid():n.format==="email"?t=F.string().email():n.format==="date"?t=F.string().regex(/^\d{4}-\d{2}-\d{2}$/):n.format==="date-time"&&(t=F.string().datetime()),n.enum&&(t=F.enum(n.enum)),(n.type==="integer"||n.type==="number")&&(n.minimum!==void 0&&(t=t.min(n.minimum)),n.maximum!==void 0&&(t=t.max(n.maximum))),n.type==="string"&&(n.minLength!==void 0&&(t=t.min(n.minLength)),n.maxLength!==void 0&&(t=t.max(n.maxLength))),e?t:t.optional()}l(Xi,"convertOpenApiSchemaToZod");function er(n){const e=n.match(/\{([^}]+)\}/g);return e?e.map(t=>t.slice(1,-1)):[]}l(er,"extractPathParameters");function rc(n,e,t,s,i){const r=n.operationId||`${t}_${e.replace(/[^a-zA-Z0-9]/g,"_")}`,o=n.description||n.summary||`${t.toUpperCase()} ${e}`,a={},c={},u={};if(n.parameters){for(const f of n.parameters)if(f.in==="path")c[f.name]=Xi(f.schema,!0).describe(f.description||`Path parameter: ${f.name}`);else if(f.in==="query"){const h=f.required===!0;u[f.name]=Xi(f.schema,h).describe(f.description||`Query parameter: ${f.name}`)}}Object.keys(c).length>0&&(a.params=F.object(c).describe("Path parameters")),Object.keys(u).length>0&&(a.query=F.object(u).describe("Query parameters")),n.requestBody&&n.requestBody.content&&n.requestBody.content["application/json"]&&(a.body=F.any().describe("Request body"));const d=Object.keys(a).length>0?F.object(a):F.object({});return{name:r,description:o,parameters:d,async execute(f){try{const h=er(e);if(h.length>0){if(!f.params)throw new Error(`Missing required path parameters: ${h.join(", ")}`);const b=h.filter(C=>!(C in f.params));if(b.length>0)throw new Error(`Missing required path parameters: ${b.join(", ")}`)}let m=`${s}${e}`;if(f.params)for(const[b,C]of Object.entries(f.params)){const A=`{${b}}`;m.includes(A)&&(m=m.replace(A,String(C)))}const w=er(m);if(w.length>0)throw new Error(`Unresolved path parameters: ${w.join(", ")}`);const p=new URLSearchParams;if(f.query)for(const[b,C]of Object.entries(f.query))C!=null&&p.append(b,String(C));p.toString()&&(m+=`?${p.toString()}`);const y={method:t.toUpperCase(),headers:{Authorization:`Bearer ${i}`,"Content-Type":"application/json"}};f.body&&t.toLowerCase()!=="get"&&(y.data=f.body);const S=await ln.request({url:m,...y});return{content:[{type:"text",text:JSON.stringify(S.data,null,2)}]}}catch(h){return ln.isAxiosError(h)?{content:[{type:"text",text:`Error: ${h.response?.data?`HTTP ${h.response.status}: ${h.response.statusText} - ${JSON.stringify(h.response.data)}`:`HTTP ${h.response?.status||"unknown"}: ${h.message}`}`}],isError:!0}:h instanceof Error?{content:[{type:"text",text:`Error: API call failed: ${h.message}`}],isError:!0}:{content:[{type:"text",text:"Error: API call failed with unknown error"}],isError:!0}}}}}l(rc,"createApiTool");function oc(n,e,t){const s=[];if(!n.paths)return s;for(const[i,r]of Object.entries(n.paths))if(typeof r=="object"&&r!==null){for(const[o,a]of Object.entries(r))if(["get","post","put","delete","patch"].includes(o)&&a&&typeof a=="object"){const c=rc(a,i,o,e,t);s.push(c)}}return s}l(oc,"convertOpenApiToTools");function ac(n){n.command("mcp").description("Launch MCP server with OpenAPI endpoints as tools (API URI is read from membrane.config.yml)").addHelpText("after",["","Examples:"," membrane mcp # Launch MCP server using API URI from membrane.config.yml",""].join(`
|
|
143
|
+
`)).action(async()=>{try{process.env.FASTMCP_SUPPRESS_WARNINGS="true";const e=de();e||(console.error("No membrane.config.yml found. Please run `membrane init` first."),process.exit(1)),(!e.workspaceKey||!e.workspaceSecret)&&(console.error("Missing workspace credentials"),process.exit(1));const t=e.apiUri||gn,s=await sc(e.workspaceKey,e.workspaceSecret),i=await ic(t,s),r=oc(i,t,s),o=new Mr({name:"Membrane API",instructions:`This MCP server lets you interact with Membrane to configure, run, and troubleshoot integrations.
|
|
144
|
+
Use it for anything related to Membrane or integrations.
|
|
145
|
+
`,version:"1.0.0"});for(const u of r){const d=u.execute;u.execute=async f=>(Wr(process.pid,process.cwd()),d(f)),o.addTool(u)}pn({isRunning:!0,startTime:new Date().toISOString(),toolsCount:r.length,lastActivity:new Date().toISOString(),processId:process.pid,cwd:process.cwd(),agentName:process.env.AGENT_NAME||"Unnamed Agent"});const a=setInterval(()=>{pn({processId:process.pid,cwd:process.cwd(),lastActivity:new Date().toISOString()})},5e3),c=l(async()=>{clearInterval(a),Qe(process.pid,process.cwd());try{await o.stop()}catch{}},"cleanup");await o.start({transportType:"stdio"}),process.on("SIGINT",async()=>{await c(),process.exit(0)}),process.on("SIGTERM",async()=>{await c(),process.exit(0)}),process.on("exit",()=>{Qe(process.pid,process.cwd())}),process.on("uncaughtException",async u=>{console.error("Uncaught exception:",u.message),await c(),process.exit(1)}),process.on("unhandledRejection",async u=>{console.error("Unhandled rejection:",u),await c(),process.exit(1)})}catch(e){e instanceof Error&&(console.error(e.message),process.exit(1)),console.error("An unknown error occurred"),process.exit(1)}})}l(ac,"setupMcpCommand");function cc(n){n.command("open").description("Open the workspace in the browser").addHelpText("after",["","Examples:"," membrane open # Open workspace in browser",""].join(`
|
|
146
|
+
`)).action(async()=>{try{E.header("Opening Workspace in Browser"),E.info("Loading configuration...");const e=de();if(!e)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!e.workspaceKey||!e.workspaceSecret)throw new Error("Missing workspace credentials");E.info("Retrieving workspace ID...");const s=`https://console.integration.app/w/${await vs(process.cwd())}`;E.info(`Opening ${s}...`);const{default:i}=await import("open");await i(s),E.success("Browser opened successfully")}catch(e){e instanceof Error&&(E.error(e.message),process.exit(1)),E.error("An unknown error occurred"),process.exit(1)}})}l(cc,"setupOpenCommand");const ee={[I.Integration]:{element:"integration",elements:"integrations",exportable:!1,exportCleanup:l(n=>({id:n.id,key:n.key,name:n.name,connectorId:n.connectorId,baseUri:n.baseUri,connectorVersion:n.connectorVersion}),"exportCleanup")},[I.Connector]:{element:"connector",elements:"connectors",exportable:!1},[I.Action]:{element:"action",elements:"actions",integrationSpecific:!0,exportCleanup:l(n=>(delete n.integration,n),"exportCleanup")},[I.AppDataSchema]:{element:"appDataSchema",elements:"appDataSchemas"},[I.AppEventType]:{element:"appEventType",elements:"appEventTypes"},[I.DataLinkTable]:{element:"dataLinkTable",elements:"dataLinkTables"},[I.DataSource]:{element:"dataSource",elements:"dataSources",integrationSpecific:!0},[I.FieldMapping]:{element:"fieldMapping",elements:"fieldMappings",integrationSpecific:!0,exportCleanup:l(n=>(delete n.dataSourceId,n),"exportCleanup")},[I.Flow]:{element:"flow",elements:"flows",integrationSpecific:!0}};function lc(n){return delete n.workspaceId,delete n.createdAt,delete n.updatedAt,delete n.revision,delete n.parentRevision,Object.keys(n).map(e=>{e.match(/universal.*Revision/g)&&delete n[e]}),n}l(lc,"baseExportCleanup");async function tr(n,e="full"){const t={};E.info("Getting remote workspace data");const s=await n.integrations.findAll();t.integration=s.map(i=>Yn("integration",i));for(const i of Object.keys(ee)){const r=ee[i];if(r.exportable===!1)continue;const o=[];E.info(`Reading ${r.elements} from remote workspace`);const a=await n[r.elements].findAll();if(o.push(...a.map(c=>Yn(i,c))),r.integrationSpecific)for(const c of s){const u=await n[r.elements].findAll({integrationId:c.id});o.push(...u.map(d=>(d.integrationKey=c.key,Yn(i,d))))}o.length>0&&e=="full"&&(console.table(o.map(c=>({key:c.key,integrationKey:c.integrationKey,universal:!c.integrationKey})).reduce((c,u)=>(c||(c={}),c[u.key]||(c[u.key]={}),u.universal&&(c[u.key].universal=!0),u.integrationKey&&(c[u.key].integration?c[u.key].integration+=` ${u.integrationKey}`:c[u.key].integration=u.integrationKey),c),{})),console.groupEnd()),t[i]=o}return E.success("Remote workspace data retrieved successfully"),t}l(tr,"getWorkspaceData");function uc(n){const e={},t={};for(const s of Object.keys(n))if(e[s]=[],t[s]=[],ee[s]?.integrationSpecific)for(const r of n[s])r.integrationKey||r.integration||r.integrationId?t[s].push(r):e[s].push(r);else e[s].push(...n[s]);return{universalElements:e,integrationSpecificElements:t}}l(uc,"splitWorkspaceData");function Yn(n,e){return e=lc(e),ee[n].exportCleanup?ee[n].exportCleanup(e):e}l(Yn,"cleanUpForExport");function ft(n){return Object.keys(n).some(e=>/universal.*Id/g.test(e)||/parentId/g.test(e))}l(ft,"hasParent");function W(n,e){console.debug("\x1B[0m",`\x1B[${{Reset:"\x1B[0m",Bright:"\x1B[1m",Dim:"\x1B[2m",Underscore:"\x1B[4m",Blink:"\x1B[5m",Reverse:"\x1B[7m",Hidden:"\x1B[8m",Black:"\x1B[30m",Red:"\x1B[31m",Green:"\x1B[32m",Yellow:"\x1B[33m",Blue:"\x1B[34m",Magenta:"\x1B[35m",Cyan:"\x1B[36m",White:"\x1B[37m",Gray:"\x1B[90m",BgBlack:"\x1B[40m",BgRed:"\x1B[41m",BgGreen:"\x1B[42m",BgYellow:"\x1B[43m",BgBlue:"\x1B[44m",BgMagenta:"\x1B[45m",BgCyan:"\x1B[46m",BgWhite:"\x1B[47m",BgGray:"\x1B[100m"}[e]}`,n,"\x1B[0m")}l(W,"coloredLog");function dt(n){return ie[n].apiPath}l(dt,"getWorkspaceElementTypePath");function nr(n,e){for(const t of Object.keys(e))n[t]=[...n[t]||[],...e[t]];return n}l(nr,"mergeWorkspaceData");const sr=[I.Integration,I.Scenario,I.Action,I.Flow,I.AppDataSchema,I.AppEventType,I.DataLinkTable,I.DataSource,I.FieldMapping],ir="connectors",rr="development",Zn={};async function fc({client:n,basePath:e,allConnectors:t=!1}){const s=await n.integrations.findAll(),i=new Set,r={};for(const o of s){const a=o.connectorId,c=o.connectorVersion;if(!r[a]?.has(o.connectorVersion)){const u=await gc({client:n,connectorId:a});(!!u.workspaceId||t)&&(i.has(a)||(await wc({basePath:e,connector:u}),i.add(a)),r[a]||(r[a]=new Set),r[a].has(c)||(await bc({client:n,connector:u,connectorVersion:c,basePath:e}),r[a].add(c)))}}}l(fc,"pullConnectors");async function dc({client:n,workspaceData:e,pushContext:t,workspaceId:s}){const i={};console.debug("[Push] Loading custom connectors");const r=n,o=await r.get(`/connectors?workspaceId=${s}`);console.debug("[Push] Loading public connectors"),e.connector=o;const a=Qn(),c=P.existsSync(a)?P.readdirSync(a):[];for(const u of c){console.debug(`[Push] Loading connector from: ${u}`);const d=P.readdirSync(j.join(a,u)),f=await hc(u);if(delete f.baseUri,f.uuid&&e.connector?.find(m=>m.uuid==f.uuid))i[f.id]=e.connector.find(m=>m.uuid==f.uuid).id,W(`Matched ${f.name} uuid: ${f.uuid}`,"Blue");else if(!i[f.id]){console.debug(`Creating connector ${f.name} (${f.key})`);const m=await r.post("connectors",{...f,workspaceId:s});i[f.id]=m.id}const h=d.filter(m=>P.statSync(j.join(a,u,m)).isDirectory());for(const m of h)await yc({client:n,connector:f,version:m,connectorId:i[f.id]})}t.connectorsMapping=i}l(dc,"pushConnectors");function Qn(){const n=Xe();return j.join(n.membraneDirPath,ir)}l(Qn,"getConnectorsPath");async function hc(n){return se.load(P.readFileSync(j.join(Qn(),n,`${n}.yml`),"utf8"))}l(hc,"readConnector");async function pc(n,e){return console.debug(`Zipping ${n} into ${e}`),new Promise((t,s)=>{const i=P.createWriteStream(e),r=Rr("zip",{zlib:{level:9}});i.on("close",()=>{W(`Successfully created ${e}`,"Green"),t()}),i.on("end",()=>{console.debug("Data has been drained")}),r.on("warning",a=>{a.code==="ENOENT"?console.warn(a):s(a)}),r.on("error",a=>{s(a)}),r.pipe(i);const o=P.readdirSync(n);for(const a of o){const c=j.join(n,a),u=P.statSync(c);u.isFile()?r.file(c,{name:a}):u.isDirectory()&&r.directory(c,a)}r.finalize()})}l(pc,"createZipArchive");async function mc(n,e){return console.debug(`Unzipping into ${e}`),new Promise((t,s)=>{const i=Fr.Parse();i.on("entry",r=>{const o=r.path;if(r.type==="Directory"){const c=j.join(e,o);P.mkdirSync(c,{recursive:!0}),r.autodrain()}else{const c=j.join(e,o),u=j.dirname(c);P.mkdirSync(u,{recursive:!0});const d=P.createWriteStream(c);r.pipe(d),d.on("finish",()=>{console.debug(`Extracted: ${o}`)})}}),i.on("end",()=>{W(`Successfully extracted to ${e}`,"Green"),t()}),i.on("error",r=>{s(r)}),i.write(n),i.end()})}l(mc,"extractZipArchive");async function yc({client:n,connector:e,version:t,connectorId:s}){const i=j.join(Qn(),Qt(e),or(t)),r=j.join(i,"src"),o=j.join(i,"src.zip");if(P.existsSync(r)&&(console.debug(`Archiving source code for ${e.name} version ${t}`),await pc(r,o)),!P.existsSync(o)){E.warning(`No source code found for ${e.name} version ${t}`);return}try{const a=new Br;if(a.append("file",P.createReadStream(o),"file.zip"),console.debug(`Pushing connector version ${t} for ${e.name}`),t==rr)console.debug(`Uploading connector ${s}`),await n.post(`connectors/${s}/upload`,a,{headers:{...a.getHeaders()}});else{if(a.append("version",t),a.append("changelog","Imported Version"),(await n.get(`/connectors/${s}/versions`)).find(u=>u.version==t)){W(`Version ${t} already published`,"Blue");return}console.debug(`Publishing version ${t} of connector ${s}`),await n.post(`connectors/${s}/publish-version`,a,{headers:{...a.getHeaders()}})}E.success(`Successfully pushed connector version ${t} for ${e.name}`)}catch(a){E.error(`Error pushing connector version ${t} for ${e.name}`,a)}finally{P.existsSync(o)&&P.unlinkSync(o)}}l(yc,"pushConnectorVersion");async function gc({client:n,connectorId:e}){if(Zn[e])return Zn[e];const t=await n.get(`connectors/${e}`);return Zn[e]=t,t}l(gc,"getConnector");async function wc({basePath:n,connector:e}){const t=Qt(e),s=j.join(n,ir,t);P.mkdirSync(s,{recursive:!0});const i=j.join(s,`${Qt(e)}.yml`);P.writeFileSync(i,se.dump(e)),W(`Pulled connector ${e.name}`,"Green")}l(wc,"pullConnector");async function bc({client:n,connector:e,connectorVersion:t,basePath:s}){const i=Qt(e),r=or(t),o=j.join(s,"connectors",i,r),a=await n.get(`connectors/${e.id}/download`,{version:t},{responseType:"arraybuffer",headers:{Accept:"application/zip"},timeout:1e6});P.mkdirSync(o,{recursive:!0});const c=j.join(o,"src.zip");P.writeFileSync(c,a);const u=j.join(o,"src");P.existsSync(u)&&await mc(a,u),E.info(`[Pull] Connector Version: ${e.name} (${r})`)}l(bc,"pullConnectorVersion");function Qt(n){return n.key}l(Qt,"getConnectorDirName");function or(n){return n??rr}l(or,"getConnectorVersionDirName");async function Sc(n){const{outputPath:e,allConnectors:t,client:s}=n;await fc({client:s,basePath:e,allConnectors:t});const i=await tr(s);for(const r of Object.keys(i))if(i[r].length>0){try{P.readdirSync(e)}catch{P.mkdirSync(e,{recursive:!0})}const o=dt(r);for(const a of i[r]){try{P.readdirSync(j.join(e,o,`${a.key}`))}catch{P.mkdirSync(j.join(e,o,`${a.key}`),{recursive:!0})}if(a.integration||a.integrationKey){const c=a.integration?a.integration.key:a.integrationKey;try{P.readdirSync(j.join(e,o,`${a.key}`,`${c}`))}catch{P.mkdirSync(j.join(e,o,`${a.key}`,`${c}`),{recursive:!0})}P.writeFileSync(j.join(e,o,`${a.key}`,`${c}`,`${c}.yaml`),se.dump(a))}else P.writeFileSync(j.join(e,o,a.key,`${a.key}.yaml`),se.dump(a))}}W(`Data written to ${e} successfully.`,"BgGreen")}l(Sc,"pullWorkspace");const kc="default";async function Cc(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Ye.sign(t,e)}l(Cc,"generateAccessToken$1");function vc(n){n.command("pull").description("Pull workspace data from specified workspace").option("-w, --workspace <workspace>","Workspace to pull from",kc).option("-a, --all-connectors","Include store connectors in export",!1).addHelpText("after",["","Examples:"," membrane pull # Pull from default workspace"," membrane pull -w prod # Pull from prod workspace"," membrane pull -w dev # Pull from dev workspace"," membrane pull -a # Pull with all connectors"," membrane pull -w dev -a # Pull from dev workspace with all connectors",""].join(`
|
|
147
|
+
`)).action(async e=>{E.header("Pulling Workspace Data"),E.divider(),E.info("Loading configuration...");const t=de();if(!t)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!t.workspaceKey||!t.workspaceSecret)throw new Error("Missing workspace credentials");const s=Xe(),i=new pt({token:await Cc(t.workspaceKey,t.workspaceSecret),apiUri:t.apiUri});E.info("Pulling from workspace..."),await Sc({allConnectors:e.allConnectors,outputPath:s.membraneDirPath,client:i}),E.divider(),E.success("Pull completed successfully")})}l(vc,"setupPullCommand");async function Ac(){const n={};for(const e of sr){E.info(`Loading ${ie[e].namePlural}`);const t=[],i=Xe().membraneDirPath,r=[j.join(i,dt(e))],o=j.join(i,We.toCamelCase(dt(e)));r.includes(o)||r.push(o);for(const a of r)P.existsSync(a)&&t.push(...await ar(a));n[e]=[...n[e]||[],...t]}return n}l(Ac,"readTopLevelElements");async function Tc(){const n={},t=Xe().membraneDirPath,s=j.join(t,dt(I.Integration)),i=P.readdirSync(s);for(const r of i)if(P.statSync(j.join(s,r)).isDirectory()){const o=await cr(s,r);for(const a of sr){const c=j.join(s,r,dt(a)),u=await ar(c);u.forEach(d=>{d.integrationKey=o?.key}),n[a]=[...n[a]||[],...u]}}return n}l(Tc,"readIntegrationLevelElements");async function ar(n){const e=[];if(!P.existsSync(n))return e;E.info(`Reading ${n}`);const t=P.readdirSync(n);for(const s of t){const i=await cr(n,s);i&&(e.push(i),E.success(`Loaded ${s}`))}return e}l(ar,"readWorkspaceElementsFromDir");async function cr(n,e){const t=j.join(n,e),i=P.statSync(t).isDirectory()?j.join(t,`${e}.yaml`):t;if(P.existsSync(i))return se.load(P.readFileSync(i,"utf8"))}l(cr,"readWorkspaceElementFromDirItem");async function Oc({client:n}){const t=(await n.get("org-workspace-id")).id,s=await tr(n,"minified"),i={};E.info("Loading local workspace data");const r=await Ac();nr(i,r);const o=await Tc();nr(i,o);const{universalElements:a,integrationSpecificElements:c}=uc(i),u={connectorsMapping:{}};return await Ec({sourceData:i,workspaceData:s,pushContext:u,iApp:n,workspaceId:t}),s.integration=await n.integrations.findAll(),W("Syncing Universal Elements","BgBlue"),E.group("Syncing Universal Elements"),await lr(a,s,n),E.groupEnd(),W("Syncing Integration Specific Elements","BgBlue"),E.group("Syncing Integration Specific Elements"),await lr(c,s,n),E.groupEnd(),E.success("Data written successfully."),u}l(Oc,"pushWorkspace");async function Ec({sourceData:n,workspaceData:e,pushContext:t,iApp:s,workspaceId:i}){W("Matching imported integrations and connectors with existing ones","BgBlue"),await dc({client:s,workspaceData:e,pushContext:t,workspaceId:i});const r=[];for(const o of n.integration){const a=e.integration.find(u=>u.key==o.key),c={connectorId:o.connectorId,connectorVersion:o.connectorVersion,name:o.name,key:o.key};t.connectorsMapping[o.connectorId]&&(c.connectorId=t.connectorsMapping[o.connectorId]),a?(console.debug(`[Push] Updating integration ${o.key}`),await s.integration(a.id).patch(c)):(console.debug(`[Push] Creating integration ${o.key}`),await s.integrations.create(c)),W(`Imported integration ${o.name} (${o.key})`,"Green")}if(r.length>0)throw E.table(r.map(o=>({key:o.key,name:o.name}))),W("Integration missmatch errors. Make sure you have those applications in your destination workspace","BgRed"),new Error("Integration missmatch errors")}l(Ec,"syncIntegrations");async function lr(n,e,t){for(const s of Object.keys(n))if(ee[s]?.exportable!==!1)for(const r of n[s]){delete r.integrationId;const o=$c(r,s,e),a=We.toCamelCase(ie[s].name),c=We.toCamelCase(ie[s].namePlural);if(o)if(!ft(r)||ur(r)&&ft(r))await t[a](o.id).put(r),W(`Updated ${r.integrationKey||"universal"} ${ee[s].element} ${r.key}`,"Cyan");else if(ft(r)){try{await t[a](o.id).reset()}catch(u){throw console.debug(o,r),u}W(`Customization reset ${r.integrationKey||"universal"} ${ee[s].element} ${r.key}`,"Magenta")}else W(`Corrupted. Migrate Manually ${r.integrationKey||"universal"} ${ee[s].element} ${r.key}`,"Red");else if(ft(r)){try{await t[a]({key:r.key}).apply([r.integrationKey])}catch{try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch{await t[c].create({...r,integrationId:e.integration.find(f=>f.key==r.integrationKey).id})}}if(ur(r)){try{await t[a]({key:r.key,integrationKey:r.integrationKey}).put(r)}catch(u){throw console.debug(o,r),u}W(`Applied & Customized ${r.integrationKey||"universal"} ${ee[s].element} ${r.key}`,"Green")}else W(`Applied universal ${ee[s].element} ${r.key} to ${r.integrationKey} `,"Green")}else{try{r.integrationKey&&(delete r.integration,r.integrationId=e.integration.find(u=>u.key==r.integrationKey).id),await t[c].create(r)}catch(u){throw console.debug(`Error creating element ${s}`,ft(r),r.integrationKey,r),u}W(`Created ${r.integrationKey||"universal"} ${ee[s].element} ${r.key}`,"Green")}}}l(lr,"syncElements");function ur(n){return n.integrationKey&&(n.customized||n.isCustomized)}l(ur,"elementIsCustomized");function $c(n,e,t){const s=t[e]?.filter(i=>i.key==n.key&&i.integrationKey==n.integrationKey&&!i.archivedAt);if(s.length>1)throw new Error(`More than one ${n.integrationKey||"universal"} ${e} with key ${n.key} found in the workspace`);if(s.length==1)return s[0]}l($c,"matchElement");const fr="default";async function Ic(n,e){const t={iss:n,exp:Math.floor(Date.now()/1e3)+3600,isAdmin:!0};return Ye.sign(t,e)}l(Ic,"generateAccessToken");function Nc(n){n.command("push").description("Push workspace data to specified workspace").option("-w, --workspace <workspace>","Workspace to push to",fr).addHelpText("after",["","Examples:"," membrane push # Push to default workspace"," membrane push -w prod # Push to prod workspace"," membrane push -w dev # Push to dev workspace",""].join(`
|
|
148
|
+
`)).action(async e=>{try{E.header("Pushing Workspace Data"),E.info("Loading configuration...");const t=de();if(!t)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!t.workspaceKey||!t.workspaceSecret)throw new Error("Missing workspace credentials");const s=e.workspace||fr;E.info("Preparing push configuration...");const i=new pt({token:await Ic(t.workspaceKey,t.workspaceSecret),apiUri:t.apiUri});E.info(`Pushing to workspace ${s}...`),await Oc({client:i}),E.success(`Push to workspace ${s} completed successfully`)}catch(t){t instanceof Error&&(E.error(t.message),process.exit(1)),E.error("An unknown error occurred"),process.exit(1)}})}l(Nc,"setupPushCommand");class Lc{static{l(this,"BaseRunner")}constructor(e){if(this.options=e,this.fsPaths=Xe(),e&&typeof e=="object"){const t=e;"client"in t&&t.client&&(this.client=t.client),"workspace"in t&&(this.workspace=t.workspace)}}client;workspace;fsPaths}const _c="claude-sonnet-4-20250514";class ss{static{l(this,"TestEnvironment")}client;connectionId;testsDir;testBasePath;options;llm;state={};constructor({connectionId:e,testsDir:t,testBasePath:s,client:i,options:r,llm:o}){this.client=i,this.connectionId=e,this.testsDir=t,this.testBasePath=s,this.llm=o,this.options=r}static async create({connectionId:e,testBasePath:t,options:s}){const i=de();if(!i)throw new Error("No membrane.config.yml found. Please run `membrane init` first.");if(!i.workspaceKey||!i.workspaceSecret)throw new Error("Missing workspace credentials");if(!i.anthropicApiKey)throw new Error("Anthropic API key not configured. Run `membrane init` to set up testing.");const r=new pt({token:await this.createMembraneToken(i),apiUri:i.apiUri}),o=new qr({apiKey:i.anthropicApiKey}),a={complete:l(async({prompt:c,maxTokens:u})=>{const d=await o.messages.create({model:_c,max_tokens:u,messages:[{role:"user",content:c}]});return d.content[0].type==="text"?d.content[0].text:""},"complete")};return new ss({client:r,options:s,connectionId:e,testsDir:"src/testing/tests",testBasePath:t,llm:a})}async run(e){this.state={};const t={};for(const s of e)await s.run(),un(t,s.getResult());this.writeResults(t)}async readYaml(e){const t=j.join(this.testsDir,this.testBasePath,this.connectionId,e);if(P.existsSync(t))return se.load(P.readFileSync(t,"utf8"))}async writeYaml(e,t){const s=j.join(this.testsDir,this.testBasePath,this.connectionId,e);P.mkdirSync(j.dirname(s),{recursive:!0}),P.writeFileSync(s,se.dump(t,{noRefs:!0}))}writeResults(e){const t=j.join(this.testsDir,this.testBasePath,this.connectionId);P.mkdirSync(t,{recursive:!0});const s=j.join(t,"test-results.yaml");P.writeFileSync(s,se.dump(e,{noRefs:!0})),console.debug(`[TestRunner] Results written to: ${s}`)}static async createMembraneToken(e){const t=e.testCustomerId||"test-customer",s={id:t,name:t},i={issuer:e.workspaceKey,expiresIn:7200,algorithm:"HS512"};return Ye.sign(s,e.workspaceSecret,i)}}Jr.interpolate=/{{([\s\S]+?)}}/g;function Xn(n,e){if(typeof n=="string"){const t=Ur(n),s={state:e,random:{number:l(()=>Ze.number.int(),"number"),alphaNumeric:l(r=>Ze.string.alphanumeric(r),"alphaNumeric")},faker:{company:{name:l(()=>Ze.company.name(),"name"),catchPhrase:l(()=>Ze.company.catchPhrase(),"catchPhrase")},internet:{email:l(()=>Ze.internet.email(),"email")}},entries:e["journal-entries"],orders:e["purchase-orders"]||e["sales-orders"],bills:e["vendor-bills"]},i=t(s);return n.includes("{{")&&n.includes("}}")&&(console.debug(`[TEMPLATE] Input: ${n}`),console.debug(`[TEMPLATE] Output: ${i}`)),i}return Array.isArray(n)?n.map(t=>Xn(t,e)):typeof n=="object"&&n!==null?Object.fromEntries(Object.entries(n).map(([t,s])=>[t,Xn(s,e)])):n}l(Xn,"processNode");function Pc(n,e){return Xn(n,e)}l(Pc,"handleTemplate");class xc{static{l(this,"BaseTestSuite")}result;environment;constructor({environment:e}){this.environment=e,this.result={}}async run(){}getResult(){return this.result}async runTest(e){console.debug(`${k.bold.cyan("[start]")} ${k.yellow(e.path)}`);let t=!1,s=!1,i={},r={},o;for(;!t;)try{r=await e.readTestCase(),r||(r=await e.generateConfig(),await this.environment.writeYaml(e.getTestCasePath(),r),console.debug(`${k.bold.yellow("[initialized]")} ${k.yellow(e.path)}`)),o=Pc(r,this.environment.state),await e.run(o),console.debug(`${k.bold.green("[success]")} ${k.yellow(e.path)}`),t=!0,i=e.getResult(),on(this.result,e.path,i)}catch(c){if(console.error(`${k.bold.red("[error]")} ${k.yellow(e.path)}: ${c}`),this.environment.options.fix&&!s){s=!0;try{await e.fix(c);continue}catch(u){console.error(`${k.bold.red("[fix fail]")} ${k.yellow(e.path)}: ${u}`)}}on(this.result,e.path,{error:re(c)}),t=!0,i={error:re(c)}}const a={...o,result:i};await this.environment.writeYaml(e.getTestCasePath(),a)}async runTestSuite(e){await e.run(),un(this.result,e.getResult())}}class ge{static{l(this,"BaseTester")}environment;level;logs;assertions;resultsLocator;path;constructor({environment:e,path:t}){this.environment=e,this.logs=[],this.assertions=[],this.path=t,this.level=0}async fix(e){const t=await this.readTestCase();if(!t)throw new Error(`No config found for test ${this.path}`);const s=await this.fixTestCase({config:t,error:e});console.debug(k.bold.yellow("[auto-fix]"),this.path),await this.environment.writeYaml(this.getTestCasePath(),s)}async readTestCase(){const e=this.getTestCasePath();return this.environment.readYaml(e)}async generateConfig(){return{}}async fixTestCase(e){throw new Error(`Auto-fix is not implemented for test ${this.path}`)}getResult(){return{logs:this.logs,assertions:this.assertions}}async assert(e,t,s){try{const i=await e();i?(this.logMsg(`\u2705 ${t}`),this.assertions.push({message:t,result:i})):(this.logMsg(`\u274C ${t}`),this.assertions.push({message:t,result:!1,details:s}))}catch(i){this.assertions.push({message:t,result:!1,details:re(i)}),this.logMsg(`\u274C ${t}: ${i.message}`)}}logMsg(e){console.debug(`${" ".repeat(this.level*2)}${e}`)}getTestCasePath(){return`${this.path}.test.yml`}}function es(n,e){const t={};for(const s in e){if(!(s in n)){t[s]=e[s];continue}const i=n[s],r=e[s];if(i&&r&&typeof i=="object"&&typeof r=="object"){if(Array.isArray(i)&&Array.isArray(r)){const o=r.filter(a=>!i.some(c=>{if(typeof c=="object"&&typeof a=="object"&&c!==null&&a!==null&&!Array.isArray(c)&&!Array.isArray(a)){for(const u in a)if(!(u in c)||!ts(c[u],a[u]))return!1;return!0}else return JSON.stringify(c)===JSON.stringify(a)}));o.length>0&&(t[s]=o)}else if(!Array.isArray(i)&&!Array.isArray(r)){const o=es(i,r);o!==null&&(t[s]=o)}else t[s]=r;continue}ts(i,r)||(t[s]=r)}return Object.keys(t).length===0?null:t}l(es,"getNotMatchingSubFields");function ts(n,e){if(n==e||n?.toString?.()===e?.toString?.())return!0;const t=new Date(n),s=new Date(e);return!isNaN(t.getTime())&&!isNaN(s.getTime())?t.getTime()===s.getTime():!1}l(ts,"softCompare");class jc extends ge{static{l(this,"DataCollectionCreateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/create`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create(e.input);await this.assert(()=>!!t.id,"Returned ID of a created record"),t.id&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id});const s=an(this.dataCollection);if(this.dataCollection.findById){const r=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t.id});await this.assert(()=>!!r.record,"Record is returned from findById"),r.record&&(this.environment.state[this.dataCollectionKey]={createdRecordId:t.id,createdRecord:r.record.fields});const o=as(s),a=mt(e.input.fields,o,{skipUnknownFields:!0}),c=mt(r.record.fields,o),u=es(c,a);await this.assert(()=>!u,"Returned fields match created fields",{difference:u,sentFields:a,receivedFields:c})}const i=_r(s);if(i.length>0){const r={};i.forEach(a=>{const c=Pr(e.input.fields,a);typeof c<"u"&&on(r,a,c)});const o=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).create({fields:r});await this.assert(()=>!!o.id,"Record can be created with schema-defined required fields only")}}async generateConfig(){const e=an(this.dataCollection);if(!e?.properties)throw new Error("No fields schema found for data collection");return{input:{fields:await this.generateFieldsWithLLM(e)}}}async fixTestCase({config:e,error:t}){const s=re(t),i=an(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to create a data record in a data collection with the following fields schema:
|
|
149
|
+
|
|
150
|
+
${JSON.stringify(i,null,2)}
|
|
148
151
|
|
|
149
152
|
I tried to create a record with these fields:
|
|
150
153
|
|
|
@@ -152,9 +155,9 @@ ${JSON.stringify(e.input?.fields,null,2)}
|
|
|
152
155
|
|
|
153
156
|
But got this error:
|
|
154
157
|
|
|
155
|
-
${JSON.stringify(
|
|
158
|
+
${JSON.stringify(s)}
|
|
156
159
|
|
|
157
|
-
${this.getExampleRecordsPrompt(
|
|
160
|
+
${this.getExampleRecordsPrompt(r)}
|
|
158
161
|
|
|
159
162
|
Please analyze the error and provide:
|
|
160
163
|
1. A fixed fields object that would work (as a JSON object)
|
|
@@ -166,7 +169,7 @@ Format your response as a JSON object with two fields:
|
|
|
166
169
|
"fields": { ... fixed fields ... }
|
|
167
170
|
}.
|
|
168
171
|
|
|
169
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
172
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),s=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
170
173
|
|
|
171
174
|
${this.getExampleRecordsPrompt(t)}
|
|
172
175
|
|
|
@@ -175,14 +178,14 @@ ${JSON.stringify(e,null,2)}.
|
|
|
175
178
|
|
|
176
179
|
Do not populate fields with null or empty strings, unless the schema explicitly requires it.
|
|
177
180
|
|
|
178
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
181
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:s,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
|
|
179
182
|
|
|
180
|
-
${Object.entries(e).map(([
|
|
181
|
-
${JSON.stringify(
|
|
183
|
+
${Object.entries(e).map(([s,i])=>`Example records from collection "${s}":
|
|
184
|
+
${JSON.stringify(i,null,2)}`).join(`
|
|
182
185
|
|
|
183
186
|
`)}.
|
|
184
187
|
|
|
185
|
-
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,
|
|
188
|
+
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,s=[];return cs(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),s.push({key:r,parameters:o}))}return i}),s}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(s=>({id:s.id,fields:s.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),s={};for(const i of t){const r=ls(i);s[r]=await this.fetchExampleRecords(i)}return s}}class Kc extends ge{static{l(this,"DataCollectionDeleteTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/delete`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} delete`);try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).delete({id:t})}catch(s){throw s}if(this.dataCollection.findById)try{await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t})}catch(s){if(s?.data?.data?.response?.status===404){await this.assert(()=>!0,"Record is not found after deletion");return}throw s}else await this.assert(()=>!0,"No findById capability, skipping verification")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test delete operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test delete for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const s=re(t),i=`I'm trying to delete a record from a data collection.
|
|
186
189
|
|
|
187
190
|
I tried to delete a record with this ID:
|
|
188
191
|
|
|
@@ -190,7 +193,7 @@ ${JSON.stringify(e.input?.id,null,2)}
|
|
|
190
193
|
|
|
191
194
|
But got this error:
|
|
192
195
|
|
|
193
|
-
${JSON.stringify(
|
|
196
|
+
${JSON.stringify(s)}
|
|
194
197
|
|
|
195
198
|
Please analyze the error and provide:
|
|
196
199
|
1. A fixed ID that would work (as a string)
|
|
@@ -202,7 +205,7 @@ Format your response as a JSON object with two fields:
|
|
|
202
205
|
"id": "fixed id"
|
|
203
206
|
}.
|
|
204
207
|
|
|
205
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
208
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Dc extends ge{static{l(this,"DataCollectionFindByIdTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/find-by-id`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} find-by-id`);const s=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:t});await this.assert(()=>!!s.record,"Record is returned from findById"),await this.assert(()=>s.record.id===t,"Returned record ID matches requested ID")}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test findById operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!t?.records?.length)throw new Error(`No records found to test findById for ${this.dataCollectionKey}`);e=t.records[0].id}return{input:{id:e}}}async fixTestCase({config:e,error:t}){const s=re(t),i=`I'm trying to find a record by ID in a data collection.
|
|
206
209
|
|
|
207
210
|
I tried to find a record with this ID:
|
|
208
211
|
|
|
@@ -210,7 +213,7 @@ ${JSON.stringify(e.input?.id,null,2)}
|
|
|
210
213
|
|
|
211
214
|
But got this error:
|
|
212
215
|
|
|
213
|
-
${JSON.stringify(
|
|
216
|
+
${JSON.stringify(s)}
|
|
214
217
|
|
|
215
218
|
Please analyze the error and provide:
|
|
216
219
|
1. A fixed ID that would work (as a string)
|
|
@@ -222,7 +225,7 @@ Format your response as a JSON object with two fields:
|
|
|
222
225
|
"id": "fixed id"
|
|
223
226
|
}.
|
|
224
227
|
|
|
225
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
228
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{id:o.id}}}}class Mc extends ge{static{l(this,"DataCollectionListTester")}dataCollectionKey;constructor({environment:e,dataCollectionKey:t}){super({environment:e,path:`data/${t}/list`}),this.dataCollectionKey=t}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list(e.input);if(await this.assert(()=>Array.isArray(t.records),"Response has records field as array"),e.input.sort){const{field:s,direction:i}=e.input.sort,r=t.records;if(r.length>1)for(let o=1;o<r.length;o++){const a=r[o-1].fields[s],c=r[o].fields[s];a==null||c==null||(i==="asc"?await this.assert(()=>a<=c,`Records are sorted by ${s} in ascending order`):await this.assert(()=>a>=c,`Records are sorted by ${s} in descending order`))}}}async generateConfig(){return{input:{}}}async fixTestCase({config:e,error:t}){const s=re(t),i=`I'm trying to list records from a data collection.
|
|
226
229
|
|
|
227
230
|
I tried to list records with these parameters:
|
|
228
231
|
|
|
@@ -230,7 +233,7 @@ ${JSON.stringify(e.input,null,2)}
|
|
|
230
233
|
|
|
231
234
|
But got this error:
|
|
232
235
|
|
|
233
|
-
${JSON.stringify(
|
|
236
|
+
${JSON.stringify(s)}
|
|
234
237
|
|
|
235
238
|
Please analyze the error and provide:
|
|
236
239
|
1. Fixed parameters that would work (as a JSON object)
|
|
@@ -242,7 +245,7 @@ Format your response as a JSON object with two fields:
|
|
|
242
245
|
"input": { ... fixed parameters ... }
|
|
243
246
|
}.
|
|
244
247
|
|
|
245
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
248
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input}}}class Rc extends ge{static{l(this,"DataCollectionMatchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/match`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).match(e.input);await this.assert(()=>!!t.record,"Response contains a record");const s=t.record,r=(await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:s.id})).record;for(const[o,a]of Object.entries(e.input.query)){const c=r.fields[o];await this.assert(()=>ts(c,a),`Record field ${o} matches input value - expected ${JSON.stringify(a)} got ${JSON.stringify(c)}`)}}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test match operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e?.records?.length)throw new Error("No records found to test match");const t=e.records[0];if(!t?.fields)throw new Error("First record has no fields to match against");const s={},i=t.fields||{},r=Object.entries(i).filter(([o,a])=>o!=="links"&&a!=null&&a!=="").slice(0,1);if(r.length===0)throw new Error("No usable fields found in record for matching");for(const[o,a]of r)s[o]=a;return{input:{query:s}}}async fixTestCase({config:e,error:t}){const s=re(t),i=`I'm trying to match a record in a data collection.
|
|
246
249
|
|
|
247
250
|
I tried to match a record with this query:
|
|
248
251
|
|
|
@@ -250,7 +253,7 @@ ${JSON.stringify(e.input?.query,null,2)}
|
|
|
250
253
|
|
|
251
254
|
But got this error:
|
|
252
255
|
|
|
253
|
-
${JSON.stringify(
|
|
256
|
+
${JSON.stringify(s)}
|
|
254
257
|
|
|
255
258
|
Please analyze the error and provide:
|
|
256
259
|
1. Fixed query that would work (as a JSON object)
|
|
@@ -262,12 +265,12 @@ Format your response as a JSON object with two fields:
|
|
|
262
265
|
"query": { ... fixed query ... }
|
|
263
266
|
}.
|
|
264
267
|
|
|
265
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
268
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:{query:o.query}}}}class Bc extends ge{static{l(this,"DataCollectionSearchTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/search`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).search(e.input);await this.assert(()=>Array.isArray(t.records),"Response has records field as array");const s=t.records.some(i=>i.id===e.expectedRecordId);s||console.debug(k.yellow(`Search query "${e.input.query}" did not return expected record`)),await this.assert(()=>s,"Search returns expected record")}async generateConfig(){if(!this.dataCollection.list)throw new Error(`Can't find a record to test search operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const e=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!e.records.length)throw new Error("No records found to test search");const t=e.records[0],s=await this.getSearchQueryWithLLM(t.fields);if(!s)throw new Error("Unable to generate search query. LLM could not identify a suitable field value from the record to use as the search query.");return{input:{query:s},expectedRecordId:t.id}}async getSearchQueryWithLLM(e){const t=`You are given the fields of a record from a data collection. Identify the BEST single field value that a user is MOST likely to type when searching for this record (e.g. name, title, email, external id). Ignore null, empty strings, technical IDs, HTML, and timestamps unless they are obviously human-searchable. Make sure the field value is as unique as possible for this record. RETURN ONLY the field value as a plain string. No additional text, no JSON, no quotes.
|
|
266
269
|
|
|
267
270
|
Record fields:
|
|
268
271
|
${JSON.stringify(e,null,2)}
|
|
269
272
|
|
|
270
|
-
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
|
|
273
|
+
Field value:`;try{return(await this.environment.llm.complete({prompt:t,maxTokens:1e3})).trim()||null}catch{return null}}async fixTestCase({config:e,error:t}){const s=re(t),i=`I'm trying to search records in a data collection.
|
|
271
274
|
|
|
272
275
|
I tried to search records with these parameters:
|
|
273
276
|
|
|
@@ -275,7 +278,7 @@ ${JSON.stringify(e.input,null,2)}
|
|
|
275
278
|
|
|
276
279
|
But got this error:
|
|
277
280
|
|
|
278
|
-
${JSON.stringify(
|
|
281
|
+
${JSON.stringify(s)}
|
|
279
282
|
|
|
280
283
|
Please analyze the error and provide:
|
|
281
284
|
1. Fixed parameters that would work (as a JSON object)
|
|
@@ -287,9 +290,9 @@ Format your response as a JSON object with two fields:
|
|
|
287
290
|
"input": { ... fixed parameters ... }
|
|
288
291
|
}.
|
|
289
292
|
|
|
290
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
293
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,r=await this.environment.llm.complete({prompt:i,maxTokens:1e3}),o=JSON.parse(r.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,o.explanation),{input:o.input,expectedRecordId:e.expectedRecordId}}}class Fc extends ge{static{l(this,"DataCollectionSpecTester")}dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/spec`}),this.dataCollection=s}async run(){const e=Object.keys(this.dataCollection.fieldsSchema).length;await this.assert(()=>e>0,"Fields schema has field definitions")}}class qc extends ge{static{l(this,"DataCollectionUpdateTester")}dataCollectionKey;dataCollection;constructor({environment:e,dataCollectionKey:t,dataCollection:s}){super({environment:e,path:`data/${t}/update`}),this.dataCollectionKey=t,this.dataCollection=s}async run(e){const t=this.environment.state[this.dataCollectionKey]?.createdRecordId||e?.input?.id;if(!t)throw new Error(`No ID found in state or config for ${this.dataCollectionKey} update`);const s=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).update({...e.input,id:t});if(await this.assert(()=>!!s.id,"Returned ID of updated record"),this.environment.state[this.dataCollectionKey]||(this.environment.state[this.dataCollectionKey]={}),this.environment.state[this.dataCollectionKey].createdRecordId=s.id,this.dataCollection.findById){const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).findById({id:s.id});await this.assert(()=>!!i.record,"Record is returned from findById");const r=cn(this.dataCollection),o=as(r),a=mt(e.input.fields,o,{skipUnknownFields:!0}),c=mt(i.record.fields,o),u=es(c,a);await this.assert(()=>!u,"Returned fields match updated fields",{difference:u,sentFields:a,receivedFields:c})}}async generateConfig(){let e=this.environment.state[this.dataCollectionKey]?.createdRecordId;if(!e){if(!this.dataCollection.list)throw new Error(`Can't find a record to test update operation for ${this.dataCollectionKey}. List operation is not implemented for this data collection`);const i=await this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).list({});if(!i?.records?.length)throw new Error(`No records found to test update for ${this.dataCollectionKey}`);e=i.records[0].id}const t=cn(this.dataCollection);if(!t?.properties)throw new Error("No fields schema found for data collection");const s=await this.generateFieldsWithLLM(t);return{input:{id:e,fields:s}}}async fixTestCase({config:e,error:t}){const s=re(t),i=cn(this.dataCollection),r=await this.getExampleRecordsForSchema(i),o=`I'm trying to update a data record in a data collection with the following fields schema:
|
|
291
294
|
|
|
292
|
-
${JSON.stringify(
|
|
295
|
+
${JSON.stringify(i,null,2)}
|
|
293
296
|
|
|
294
297
|
I tried to update a record with ID "${e.input?.id}" and these fields:
|
|
295
298
|
|
|
@@ -297,9 +300,9 @@ ${JSON.stringify(e.input?.fields,null,2)}
|
|
|
297
300
|
|
|
298
301
|
But got this error:
|
|
299
302
|
|
|
300
|
-
${JSON.stringify(
|
|
303
|
+
${JSON.stringify(s)}
|
|
301
304
|
|
|
302
|
-
${this.getExampleRecordsPrompt(
|
|
305
|
+
${this.getExampleRecordsPrompt(r)}
|
|
303
306
|
|
|
304
307
|
Please analyze the error and provide:
|
|
305
308
|
1. A fixed fields object that would work (as a JSON object)
|
|
@@ -311,7 +314,7 @@ Format your response as a JSON object with two fields:
|
|
|
311
314
|
"fields": { ... fixed fields ... }
|
|
312
315
|
}.
|
|
313
316
|
|
|
314
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
317
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,a=await this.environment.llm.complete({prompt:o,maxTokens:1e4}),c=JSON.parse(a.trim());return console.warn(k.bold.yellow("[auto-fix]"),`${this.path}:`,c.explanation),{input:{id:e.input.id,fields:c.fields}}}async generateFieldsWithLLM(e){const t=await this.getExampleRecordsForSchema(e),s=`Generate a valid JSON object that matches this JSONSchema. Return only the JSON object, no other text.
|
|
315
318
|
|
|
316
319
|
${this.getExampleRecordsPrompt(t)}
|
|
317
320
|
|
|
@@ -320,16 +323,16 @@ ${JSON.stringify(e,null,2)}.
|
|
|
320
323
|
|
|
321
324
|
Do not populate fields with null or empty strings, unless the schema explicitly requires it.
|
|
322
325
|
|
|
323
|
-
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,
|
|
326
|
+
Only return the JSON object, no other text or wrapping (like \`\`\`json or \`\`\`).`,i=await this.environment.llm.complete({prompt:s,maxTokens:1e4});return JSON.parse(i.trim())}getExampleRecordsPrompt(e){return`When a field has a "referenceCollection" property, its value should be an ID of a record from that collection. Here are some example records you can use as references:
|
|
324
327
|
|
|
325
|
-
${Object.entries(e).map(([
|
|
326
|
-
${JSON.stringify(
|
|
328
|
+
${Object.entries(e).map(([s,i])=>`Example records from collection "${s}":
|
|
329
|
+
${JSON.stringify(i,null,2)}`).join(`
|
|
327
330
|
|
|
328
331
|
`)}.
|
|
329
332
|
|
|
330
|
-
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,
|
|
331
|
-
`),"createExperimentalWarning");function
|
|
332
|
-
`)).action(async(t,
|
|
333
|
-
${
|
|
333
|
+
If you don't have an example for a given collection, leave the field empty instead of coming up with a fake record id.`}async findReferenceCollections(e){const t=new Set,s=[];return cs(e,i=>{if(i.referenceCollection){const r=i.referenceCollection.key,o=i.referenceCollection.parameters,a=`${r}:${JSON.stringify(o||{})}`;t.has(a)||(t.add(a),s.push({key:r,parameters:o}))}return i}),s}async fetchExampleRecords(e){return(await this.environment.client.connection(this.environment.connectionId).dataCollection(e.key).list({parameters:e.parameters})).records.map(s=>({id:s.id,fields:s.fields}))}async getExampleRecordsForSchema(e){const t=await this.findReferenceCollections(e),s={};for(const i of t){const r=ls(i);s[r]=await this.fetchExampleRecords(i)}return s}}const ns={spec:{testerClass:Fc},create:{testerClass:jc,operationKey:"create"},"find-by-id":{testerClass:Dc,operationKey:"findById"},list:{testerClass:Mc,operationKey:"list"},match:{testerClass:Rc,operationKey:"match"},search:{testerClass:Bc,operationKey:"search"},update:{testerClass:qc,operationKey:"update"},delete:{testerClass:Kc,operationKey:"delete"}};class Uc extends xc{static{l(this,"DataCollectionTestSuite")}dataCollectionKey;testMethod;constructor({environment:e,dataCollectionKey:t,testMethod:s}){super({environment:e}),this.dataCollectionKey=t,this.testMethod=s}async run(){const e=await this.fetchDataCollection(),t=this.testMethod?[this.createTester(this.testMethod,e)]:this.createAllAvailableTesters(e);E.info("\u{1F680} Running tests...");for(const s of t)await this.runTest(s);this.displayTestSummary(t.length)}async fetchDataCollection(){return this.environment.client.connection(this.environment.connectionId).dataCollection(this.dataCollectionKey).get()}isOperationAvailable(e,t){return t?!!e[t]:!0}createTester(e,t){const s=ns[e];if(!s)throw new Error(`Unknown test method "${e}". Available: ${this.getAvailableTestMethods(t).join(", ")}`);const i="operationKey"in s?s.operationKey:void 0;if(!this.isOperationAvailable(t,i))throw new Error(`${i} operation not available for data collection "${this.dataCollectionKey}"`);return this.instantiateTester(s,t)}createAllAvailableTesters(e){return Object.entries(ns).filter(([,t])=>{const s="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,s)}).map(([,t])=>this.instantiateTester(t,e))}instantiateTester(e,t){const s={environment:this.environment,dataCollectionKey:this.dataCollectionKey,dataCollection:t};return new e.testerClass(s)}getAvailableTestMethods(e){return Object.entries(ns).filter(([,t])=>{const s="operationKey"in t?t.operationKey:void 0;return this.isOperationAvailable(e,s)}).map(([t])=>t)}displayTestSummary(e){E.info(`\u{1F4CA} ${e} test${e===1?"":"s"} executed`)}}class Jc extends Lc{static{l(this,"TestRunner")}constructor(e){super(e)}async initialize(){E.debug("Initializing test runner",{prefix:"TestRunner"})}async run(){try{const{testPath:e,path:t,fix:s}=this.options,i=e.split("/");i.length<2&&(E.error("Invalid test path. Expected format: <type>/<name>[/additional/path][/method]"),process.exit(1));const[r,o,...a]=i;r!=="connectors"&&(E.error(`Test type "${r}" is not yet fully implemented. Currently only "connectors" is fully supported.`),E.error("Supported test types: connectors"),process.exit(1));const c=o,u=r,d=[...a,...t?t.split("/"):[]].join("/"),f=await ss.create({connectionId:c,testBasePath:u,options:{fix:s}}),m=await f.client.get(`connections/${c}/data`),w=[],p=d?d.split("/"):[];if(p.length===0||p[0]==="data"){p[0]==="data"&&p.shift();let S,b;p.length>=1&&(b=p[0],p.length>=2&&p[1].trim()!==""&&(S=p[1]));for(const C of m){if(b&&b!==C.key)continue;const A=new Uc({environment:f,dataCollectionKey:C.key,testMethod:S});w.push(A)}}w.length===0&&(E.error(`No test suites found for path: ${e}${d?"/"+d:""}`),process.exit(1));const y={};for(const S of w){await S.run();const b=S.getResult();E.debug(`Suite ${S.constructor.name} result:`,{prefix:"TestRunner"}),un(y,b)}console.debug("[TestRunner] All results collected:",Object.keys(y)),f.writeResults(y)}catch(e){throw console.error("Error in TestRunner.run():",e),e}}}const Xt=l(()=>[k.yellow("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510"),k.yellow("\u2502 \u26A0\uFE0F EXPERIMENTAL FEATURE WARNING \u2502"),k.yellow("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524"),k.yellow("\u2502 The test command is experimental and subject to rapid changes. \u2502"),k.yellow("\u2502 Features, APIs, and file structures may change without notice. \u2502"),k.yellow("\u2502 Use in production environments is not recommended. \u2502"),k.yellow("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518"),""].join(`
|
|
334
|
+
`),"createExperimentalWarning");function Vc(n){n.command("test").description("\u26A0\uFE0F EXPERIMENTAL: Test management commands - This feature is experimental and will be changing rapidly. Use at your own risk.").addHelpText("after",Xt()).action(async()=>{console.warn(Xt()),E.error("Please specify a subcommand. Use --help for available options."),process.exit(1)}).command("run").description("Run integration tests for various membrane components").argument("<testPath>",'Test path (e.g., "connectors/netsuite", "actions/create-contact", "connectors/hubspot/data/contacts", "connectors/netsuite/data/contacts/create")').option("-p, --path <path>","Additional path filter within the test scope").option("--fix","Enable auto-fix for test issues").addHelpText("after",["",k.bold("Examples:"),` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite")} # Test all data collections for netsuite connector`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts")} # Test specific data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/create")} # Test specific method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/netsuite/data/contacts/delete")} # Test delete method for data collection`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run actions/create-contact")} # Test specific action`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/hubspot/events")} # Test events for hubspot`,` ${k.gray("\u25B8")} ${k.cyan("membrane test run connectors/salesforce --fix")} # Run tests with auto-fix enabled`,"",k.gray("For more information, visit:"),k.blue(" https://docs.integration.app/cli"),"",Xt()].join(`
|
|
335
|
+
`)).action(async(t,s)=>{try{console.warn(Xt()),t||(E.error("Test path is required"),process.exit(1)),E.header(`Testing: ${t}`);const i=new Jc({testPath:t,path:s.path,fix:s.fix});await i.initialize(),await i.run(),E.success("Tests completed")}catch(i){i instanceof Error&&(E.error(i.message),process.exit(1)),E.error("An unknown error occurred"),process.exit(1)}})}l(Vc,"setupTestCommand");const Wc=l(()=>{try{const n=Kr(import.meta.url),e=yr(n),t=gr(e,"..","package.json");return JSON.parse(vr(t,"utf-8")).version}catch{return"1.0.0"}},"getPackageVersion"),dr=Wc();function zc(){const n=new Dr().name("membrane").description("Command-line interface for Membrane Agent").version(dr,"-v, --version","Output the version number");n.configureHelp({sortSubcommands:!0,subcommandTerm:l(e=>k.cyan(e.name()),"subcommandTerm"),commandUsage:l(e=>e.name()==="membrane"?`${k.cyan(e.name())} ${k.gray("[options]")} ${k.cyan("[command]")}`:e.usage(),"commandUsage"),optionTerm:l(e=>{const t=e.flags;return`${k.gray("\u25B8")} ${k.cyan(t)}`},"optionTerm"),subcommandDescription:l(e=>k.gray(e.description()),"subcommandDescription"),optionDescription:l(e=>k.gray(e.description),"optionDescription"),commandDescription:l(e=>k.gray(e.description()),"commandDescription")}),n.addHelpText("beforeAll",`
|
|
336
|
+
${k.bold.cyan("Membrane Agent CLI")} ${k.gray(`v${dr}`)}
|
|
334
337
|
|
|
335
|
-
`),
|
|
338
|
+
`),vc(n),Nc(n),Vc(n),cc(n),ac(n),process.argv.length===2&&(n.outputHelp(),process.exit(0)),n.parse()}l(zc,"runCLI");const hr=["--cwd"];function Hc(){const n=process.argv.slice(2);return n.some((e,t)=>t>0&&hr.includes(n[t-1])?!1:!hr.includes(e))}l(Hc,"hasCLIArguments"),Hc()?zc():nc();
|